Giter VIP home page Giter VIP logo

crowdin-api-client-ruby's Introduction

Crowdin Ruby client

The Crowdin Ruby client is a lightweight interface to the Crowdin API. It provides common services for making API requests.

Crowdin API is a full-featured RESTful API that helps you to integrate localization into your development process. The endpoints that we use allow you to easily make calls to retrieve information and to execute actions needed.

Requirements

  • Ruby >= 2.4

Installation

Add this line to your application's Gemfile:

gem 'crowdin-api', '~> 1.11.0'

And then execute:

bundle install

Or install it yourself as:

gem install crowdin-api

Quick start

Initialization

require 'crowdin-api'

# Initialize a new Client instance with config options
crowdin = Crowdin::Client.new do |config|
  config.api_token = 'YourApiToken'
end

# Or you can initialize Enterprise Client instance by specifying your
# organization_domain in config options
crowdin = Crowdin::Client.new do |config|
  config.api_token = 'YourEnterpriseApiToken'
  config.organization_domain = 'YourOrganizationDomain'
end
# Note: we use full specified organization domain if that includes '.com'
# config.organization_domain = your_domain -> https://your_domain.api.crowdin.com
# config.organization_domain = your_domain.com -> https://your_domain.com

# All supported Crowdin Client config options now:
crowdin = Crowdin::Client.new do |config|
  config.api_token = 'YourApiToken' # [String] required
  config.organization_domain = 'YourOrganizationDomain' # [String] optional
  config.project_id = 'YourProjectId' # [Integer] nil by default
  config.enable_logger = true # [Boolean] false by default
  config.request_timeout = 60 # [nil, Integer] disabled by default
end
# Note: Client will initialize default Logger instance if you have specify
# enable_logger to true, you can change it by crowdin.logger = YourLogger

# Also you can specify proxy by adding it to ENV['http_proxy'] before Client initialization

To generate a new token in Crowdin, follow these steps:

  • Go to Account Settings > API tab, Personal Access Tokens section, and click New Token.
  • Specify Token Name and click Create.

To generate a new token in Crowdin Enterprise, follow these steps:

  • Go to Account Settings > Access tokens tab and click New token.
  • Specify Token Name, select Scopes and Projects, click Create.

Usage

# Create Project
project = crowdin.add_project(name: your_project_name, sourceLanguageId: your_language_id)

# Get list of Projects
projects = crowdin.list_projects

# Get list of Projects with offset and limit
projects = crowdin.list_projects(offset: 10, limit: 20)

# Get specified project
project = crowdin.get_project(your_project_id)

# Edit project
project = crowdin.edit_project(project_id, [{ op: 'replace',
                                              path: '/name',
                                              value: 'your_new_project_name' }])

# Add Storage
storage = crowdin.add_storage(File.open('YourFilename.extension', 'r'))
# or you can specify only absolute path to file
storage = crowdin.add_storage('YourFilename.extension')

# Download file
file = crowdin.download_file(your_file_id, your_destination, your_project_id)
# your_destination - filename or absolute path to the file, optional
# Without a destination option, the file will not be saved automatically
# project_id is optional, as it can be initialized with a Crowdin Client

# File revisions
# with initialized project_id in your Client
file_revisions = crowdin.list_file_revisions(your_file_id, limit: 10)
# or you can specify your project_id
file_revisions = crowdin.list_file_revisions(your_file_id, { limit: 10 }, your_project_id)

# Note: more examples you can find in spec folder

Fetch all records

There is a possibility to fetch all records from paginatable methods using fetch_all method.

# FetchAll options:
# * limit, Integer, default: 500 | How many records need to load per one request
# * offset, Integer, default: 0
# * request_delay, Integer (seconds), default: 0 | Delay between requests. To specify a delay in milliseconds use float values like 0.100

# Examples:

@crowdin.fetch_all(:list_projects)

# with options
@crowdin.fetch_all(:list_projects, { limit: 10, request_delay: 1 })

# playing with response per fetch
# Note: the block actually don't make any effect to finite result
@crowdin.fetch_all(:list_projects, { limit: 10, request_delay: 1 }) { |response| puts response['data'] }

# also, you could specify a retry configuration to handle some exceptions
# fetch all execution will be terminated if response status code is the same as one of the error_messages array value
# otherwise, the request will be retried so many times, as indicated at retries_count
@crowdin.fetch_all(:list_projects, {}, { request_delay: 2, retries_count: 3, error_messages: ['401'] })

Command-Line Client

The Crowdin Ruby client support crowdin-console, where you can test endpoints easier

$ bundle exec crowdin-console --enable-logger --api-token API_TOKEN --project-id PROJECT_ID

Or Crowdin Enterprise

$ bundle exec crowdin-console --enable-logger --enterprise --api-token API_TOKEN --organization-domain DOMAIN --project-id PROJECT_ID

Note: you can specify full organization domain by adding '.com'

When execute you'll have IRB console with configured @crowdin instance

> @crowdin.list_projects

Seeking Assistance

If you find any problems or would like to suggest a feature, please read the How can I contribute section in our contributing guidelines.

Contributing

If you would like to contribute please read the Contributing guidelines.

License

The Crowdin Ruby Client is licensed under the MIT License.
See the LICENSE.md file distributed with this work for additional 
information regarding copyright ownership.

Except as contained in the LICENSE file, the name(s) of the above copyright
holders shall not be used in advertising or otherwise to promote the sale,
use or other dealings in this Software without prior written authorization.

crowdin-api-client-ruby's People

Contributors

andrii-bodnar avatar antonm-svitla-sge avatar araujotadeu avatar artem-vavilov avatar cmrd-senya avatar dependabot[bot] avatar erwan avatar halle avatar keshandrr avatar laasem avatar mamantoha avatar mohanthanigaivelan avatar sabarish98 avatar sugan0tech avatar tessi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

crowdin-api-client-ruby's Issues

Pagination support

Hello @keshandrr !

I know that you're going to add pagination support to the API client.

What is a current state of it? Have you already started working on it?

We could help and contribute the development of pagination support, in case it can speed things up.

But in order to contribute we should coordinate what and how we build to get an acceptable result.

download_bundle 1.8 response break

We were using version 1.6 of the AI, but when updating it to 1.8, we noticed a compatibility break in the response ( from the release notes, that's expected ). But since I could not find a confirmation of how to use the new response in the docs I am asking here.

Method: download_bundle

Responses
Version 1.6 / 1.7

BUNDLE bundle-XXXXXXX-XXX-XXXXX-XXX-XXXXXXXXX.zip

Version 1.8

{"data"=>{"url"=>"", "expireIn"=>"2024-04-12T13:17:41+00:00"}}

If I understood correctly, the downloaded local file name is the export it with a prefix and the .zip extensions. Something like

bundle-<EXPORT_ID>.zip

Is that correct?

Is there another way to get the local file name?

Fix source file uploading in `v1.7.0`

After updating from v1.6.0 to v1.7.0, JSON files began to upload corrupted.

Issues

  1. #add_file New JSON files are corrupted as their JSON data content has been replaced with the local file path string.
Original file content Uploaded file content
{"data": "Data"} "/path/to/file.json"
  1. #update_or_restore_file Returns error:
{
  "errors" => [
    "error" => {
      "key"    => "storageId",
      "errors" => [
        "code"    => "fileInvalid",
        "message" => "Uploaded file \"file.json\" is invalid and cannot be processed"
      ]
    }
  ]
}

Glossaries API updates

We're happy to announce a significant update for Crowdin Glossaries that allows managing the terminology in a more advanced way.

There are a lot of new things and some changes in the Crowdin API.

New APIs:

Updates:

The translationOfTermId is deprecated and the conceptId added in:

Edit Term - new path options

All of these changes should be reflected in this API Client.

String-based API support

Crowdin has recently released a new type of projects - String-based.

In string-based projects, the focus is on managing translatable content as individual strings rather than source files. In this project type, after uploading source files, Crowdin parses them into source strings. Unlike file-based projects, source files aren’t stored, and the emphasis is on managing the content at the string level. This approach is beneficial when dealing with projects that involve continuous content updates, dynamic content, or where a string-oriented structure is preferred.

As a result, the API differs a bit from the file-based projects. Most of the endpoints are the same, but some endpoints have different parameters or return different responses, some endpoints are not available at all, and some new endpoints are available only for string-based projects.

We should update the API clients to support string-based projects as well.

References:

It has been implemented for the following clients:

Refactor fetch_all feature

Currently, the list of available methods for the fetch_all feature is hardcoded.

It's a bad approach since we need to maintain this list and there is a risk to forget adding some new methods.

We need to refactor this feature and get rid of these hardcoded values. Also, it would be great to somehow validate the passed method (if it supports pagination), or add some graceful exception handling for that.

Tasks Settings Templates API support

Auto generated docs

As a Crowdin Ruby API client user, I would like to have online docs to navigate and explore the client resources, methods, parameters, etc.

Examples:

These docs should be generated using GH Actions and deployed to GH Pages. Workflow example: docs.yml

The possible tool for that is rdoc.

Steps:

  • Explore tools to generate docs from code, and choose the best one.
  • Create a config and provide a command to generate the docs.
  • If needed, add additional annotations to the API Client code (ignore some unneeded methods in docs, add some method or parameter descriptions, etc).
  • Set up the GH workflow. @andrii-bodnar can help with that.
  • Set up the GH pages feature for the repo. @andrii-bodnar

Document API resources methods

The Autogenerated online documentation was added in #32. In this PR only the Bundles, Projects, Storage, and Source Files resources were documented.

Example of the method annotation:

https://github.com/crowdin/crowdin-api-client-ruby/blob/main/lib/crowdin-api/api_resources/bundles.rb#L6-L8


We need to add annotations for the rest API resources:


API reference:

Each API resource documentation can be delivered in a separate PR. Also, it's a good idea to join some resources into one PR.

Global retry configuration

Problem

There is a possibility to configure retry configuration for requests to handle some exceptions:

@crowdin.fetch_all(:list_projects, {}, { request_delay: 2, retries_count: 3, error_messages: ['401'] })

But this retry configuration applies only to the fetch_all methods and not to all the API Client methods.

Narrative

We need to make the retry configuration global so in this case, we'll be able to configure retry options for any request to Crowdin.

Possible solution: move this configuration to the client configuration level and consider these options in each API request to Crowdin

Also, this feature should be better documented in the Readme.

Additional info

Good reference - Crowdin JS API Client Retry Configuration

AI API support

Recently, Crowdin introduced new AI features, including a new set of API endpoints to manage and interact with these AI resources.

The new AI API endpoints should be added to the Crowdin API clients to allow users to programmatically interact with these new features.

References:

File translations always download to current working directory

When calling the build_project_file_translation method, the resulting file is downloaded into the current working directory of the process. This is inconvenient for a few reasons:

  1. The filename is determined by the filename in Crowdin, so this runs the risk of overwriting a local file.
  2. There is no way to set a different destination, despite this being possible for other API methods (like the download_* methods).
  3. The only way I can think of to control where the resulting file ends up is to change the working directory with Dir.chdir, which has global effects in the process.

It would be really helpful to be able to pass a destination into the build_project_file_translation method, and other similar methods.

Add the option to choose between instant file downloading and returning response data

The response from Build Project File Translation contains important etag data, which is not accessible through the #build_project_file_translation method, as it returns only the downloaded file's path.

def fetch_response_data(doc)
if doc['data'].is_a?(Hash) && doc['data']['url'] && doc['data']['url'].include?('response-content-disposition')
download_file(doc['data']['url'])
else
doc
end
end

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.