Skip to content

Latest commit

 

History

History
256 lines (192 loc) · 8.73 KB

README.md

File metadata and controls

256 lines (192 loc) · 8.73 KB

Crowdin .NET client Tweet GitHub Repo stars

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

Our 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 perform necessary actions.

Requirements

  • .NET Standard 2.0 support
  • C# language version - 8.0+

Installation

Install via NuGet:

// Package Manager
Install-Package Crowdin.Api -Version 2.27.0

// .Net CLI
dotnet add package Crowdin.Api --version 2.27.0

// Package Reference
<PackageReference Include="Crowdin.Api" Version="2.27.0" />

// Paket CLI
paket add Crowdin.Api --version 2.27.0

Usage examples

Initialization

Instantiate a client with all available APIs:

var credentials = new CrowdinCredentials
{
    AccessToken = "<paste token here>",
    Organization = "organizationName (for Crowdin Enterprise only)"
};
var client = new CrowdinApiClient(credentials);

Or use only the executors you need:

var credentials = new CrowdinCredentials
{
    AccessToken = "<paste token here>",
    Organization = "organizationName (for Crowdin Enterprise only)"
};

var client = new CrowdinApiClient(credentials);
var executor = new SourceFilesApiExecutor(client);

Storage

  1. List storages
ResponseList<StorageResource> storages = await client.Storage.ListStorages();
  1. Add storage
await using FileStream fileStream = File.Open("/path/to/file", FileMode.Open);
StorageResource storageResource = await client.Storage.AddStorage(fileStream, filename: "MyFile");

Projects

  1. List projects
ResponseList<EnterpriseProject> response = await client.ProjectsGroups.ListProjects<EnterpriseProject>();
  1. Edit project
const int projectId = 1;

// Edit info & settings with one request
var patches = new List<ProjectPatch>
{
    // Edit project info
    new ProjectInfoPatch
    {
        Value = "name",
        Path = ProjectInfoPathCode.Cname,
        Operation = PatchOperation.Replace
    },
    new ProjectInfoPatch
    {
        Value = "value here",
        Path = new ProjectInfoPath(ProjectInfoPathCode.LanguageMapping, "languageId", "mapping"),
        Operation = PatchOperation.Test
    },

    // Edit project settings
    new ProjectSettingPatch
    {
        Value = true,
        Path = ProjectSettingPathCode.AutoSubstitution,
        Operation = PatchOperation.Replace
    }
};

// PATCH request
var projectSettingsResponse = await client.ProjectsGroups.EditProject<ProjectSettings>(projectId, patches);
Console.WriteLine(projectSettingsResponse);

Fetch all records

Get a list of all the data available from the API via automatic pagination control:

const int parentId = 1;
const int maxAmountOfItems = 50; // amount of needed items. Optional parameter, default: no limit
const int amountPerRequest = 10; // amount of items in response per 1 request. Optional parameter, default: 25

Group[] allGroups = await CrowdinApiClient.WithFetchAll((limit, offset) =>
{
    Console.WriteLine("Limit: {0} | Offset: {1}", limit, offset);
    return client.ProjectsGroups.ListGroups(parentId, limit, offset);
}, maxAmountOfItems, amountPerRequest);

Only for list async methods that return Task<ResponseList<T>>.

Sorting

An optional orderBy parameter is used to apply sorting.

var executor = new ProjectsGroupsApiExecutor(mockClient.Object);

ResponseList<EnterpriseProject> projectsList = await executor.ListProjects<EnterpriseProject>(
        userId, groupId, hasManagerAccess,
        orderBy: new[]
        {
            new SortingRule
            {
                Field = "createdAt",
                Order = SortingOrder.Descending
            },
            new SortingRule
            {
                Field = "name",
                Order = SortingOrder.Ascending
            }
        });

Property SortingRule.Order is also optional (ascending order applied by default).

Rate limiting

API client has built-in support for rate limiting services. The library provides an implementation of Exponential Backoff Algorithm.

Usage:

var rateLimiter = new ExponentialBackoffRateLimiter(new RateLimitConfiguration
{
    // Maximum attempts count
    MaxAttempts = 5,
    // Maximum delay (top limit)
    MaxDelay = TimeSpan.FromSeconds(5),
    // Initial delay (bottom limit)
    InitialDelay = TimeSpan.FromMilliseconds(200),
});

// Pass created Rate Limiter instance as named argument to API client instance
// If rate limiter not passed - the request will fail immediately after HTTP 429 Too Many Requests error
var client = new CrowdinApiClient(new CrowdinCredentials
{
    AccessToken = "<paste token here>",
    Organization = "optional organization (for Enterprise API)"
}, rateLimiter: rateLimiter);

A custom rate limiting service should also implement the IRateLimiter interface. Rate limiting is disabled by default because users may be using custom resilience approaches (such as Polly) that may conflict with each other. This solution only covers simple resilience cases. If you need advanced customization - please try Polly or alternatives.

Retry configuration

Pass retry service (built-in or custom):

IRetryService myRetryService = new RetryService(new RetryConfiguration
{
    RetriesCount = 5,
    WaitIntervalMilliseconds = 1000,
    SkipRetryConditions =
    {
        exception => ((CrowdinApiException) exception).Code.GetValueOrDefault() == 1
    }
});

var apiClient = new CrowdinApiClient(new CrowdinCredentials
{
    AccessToken = "<paste token here>",
    Organization = "optional organization (for Enterprise API)"
}, retryService: myRetryService);

A custom retry service should also implement the IRetryService interface.

Contribution

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

Seeking Assistance

If you find any problems or would like to suggest a feature, please feel free to file an issue on GitHub at the Issues Page.

License

The Crowdin .NET client is licensed under the MIT License.
See the LICENSE 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.