Skip to content

Repository files navigation

Increase C# API Library

The Increase C# SDK provides convenient access to the Increase REST API from applications written in C#.

The REST API documentation can be found on increase.com.

Installation

Install the package from NuGet:

dotnet add package Increase.Api

Requirements

This library requires .NET Standard 2.0 or later.

Usage

See the examples directory for complete and runnable examples.

usingSystem;usingIncrease.Api;usingIncrease.Api.Models.Accounts;IncreaseClientclient=new();AccountCreateParamsparameters=new(){Name="New Account!",EntityID="entity_n8y8tnk2p9339ti393yi",ProgramID="program_i2v2os4mwza1oetokh9i",};varaccount=awaitclient.Accounts.Create(parameters);Console.WriteLine(account);

Client configuration

Configure the client using environment variables:

usingIncrease.Api;// Configured using the INCREASE_API_KEY, INCREASE_WEBHOOK_SECRET and INCREASE_BASE_URL environment variablesIncreaseClientclient=new();

Or manually:

usingIncrease.Api;IncreaseClientclient=new(){ApiKey="My API Key"};

Or using a combination of the two approaches.

See this table for the available options:

PropertyEnvironment variableRequiredDefault value
ApiKeyINCREASE_API_KEYtrue-
WebhookSecretINCREASE_WEBHOOK_SECRETfalse-
BaseUrlINCREASE_BASE_URLtrue"https://api.increase.com"

Modifying configuration

To temporarily use a modified client configuration, while reusing the same connection and thread pools, call WithOptions on any client or service:

usingSystem;varaccount=awaitclient.WithOptions(options =>optionswith{BaseUrl="https://example.com",Timeout=TimeSpan.FromSeconds(42),}).Accounts.Create(parameters);Console.WriteLine(account);

Using a with expression makes it easy to construct the modified options.

The WithOptions method does not affect the original client or service.

Requests and responses

To send a request to the Increase API, build an instance of some Params class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a C# class.

For example, client.Accounts.Create should be called with an instance of AccountCreateParams, and it will return an instance of Task<Account>.

Binary responses

The SDK defines methods that return binary responses, which are used for API responses that shouldn't necessarily be parsed, like non-JSON data.

These methods return HttpResponse:

usingSystem;usingIncrease.Api.Models.Files;FileContentsParamsparameters=new(){FileID="file_makxrc67oh9l6sg7w9yc"};varresponse=awaitclient.Files.Contents(parameters);Console.WriteLine(response);

To save the response content to a file, or any Stream, use the CopyToAsync method:

usingSystem.IO;usingvarresponse=awaitclient.Files.Contents(parameters);usingvarcontentStream=awaitresponse.ReadAsStream();usingvarfileStream=File.Open(path,FileMode.OpenOrCreate);awaitcontentStream.CopyToAsync(fileStream);// Or any other Stream

Raw responses

The SDK defines methods that deserialize responses into instances of C# classes. However, these methods don't provide access to the response headers, status code, or the raw response body.

To access this data, prefix any HTTP method call on a client or service with WithRawResponse:

varresponse=awaitclient.WithRawResponse.Accounts.Create(parameters);varstatusCode=response.StatusCode;varheaders=response.Headers;

The raw HttpResponseMessage can also be accessed through the RawMessage property.

For non-streaming responses, you can deserialize the response into an instance of a C# class if needed:

usingSystem;usingIncrease.Api.Models.Accounts;varresponse=awaitclient.WithRawResponse.Accounts.Create(parameters);Accountdeserialized=awaitresponse.Deserialize();Console.WriteLine(deserialized);

Error handling

The SDK throws custom unchecked exception types:

  • IncreaseApiException: Base class for API errors. See this table for which exception subclass is thrown for each HTTP status code:
StatusException
400IncreaseBadRequestException
401IncreaseUnauthorizedException
403IncreaseForbiddenException
404IncreaseNotFoundException
422IncreaseUnprocessableEntityException
429IncreaseRateLimitException
5xxIncrease5xxException
othersIncreaseUnexpectedStatusCodeException

Additionally, all 4xx errors inherit from Increase4xxException.

  • IncreaseIOException: I/O networking errors.

  • IncreaseInvalidDataException: Failure to interpret successfully parsed data. For example, when accessing a property that's supposed to be required, but the API unexpectedly omitted it from the response.

  • IncreaseException: Base class for all exceptions.

Pagination

The SDK defines methods that return a paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages.

Auto-pagination

To iterate through all results across all pages, use the Paginate method, which automatically fetches more pages as needed. The method returns an IAsyncEnumerable:

usingSystem;varpage=awaitclient.Accounts.List(parameters);awaitforeach(variteminpage.Paginate()){Console.WriteLine(item);}

Manual pagination

To access individual page items and manually request the next page, use the Items property, and HasNext and Next methods:

usingSystem;varpage=awaitclient.Accounts.List();while(true){foreach(variteminpage.Items){Console.WriteLine(item);}if(!page.HasNext()){break;}page=awaitpage.Next();}

Network options

Retries

The SDK automatically retries 2 times by default, with a short exponential backoff between requests.

Only the following error types are retried:

  • Connection errors (for example, due to a network connectivity problem)
  • 408 Request Timeout
  • 409 Conflict
  • 429 Rate Limit
  • 5xx Internal

The API may also explicitly instruct the SDK to retry or not retry a request.

To set a custom number of retries, configure the client using the MaxRetries method:

usingIncrease.Api;IncreaseClientclient=new(){MaxRetries=3};

Or configure a single method call using WithOptions:

usingSystem;varaccount=awaitclient.WithOptions(options =>optionswith{MaxRetries=3}).Accounts.Create(parameters);Console.WriteLine(account);

Timeouts

Requests time out after 1 minute by default.

To set a custom timeout, configure the client using the Timeout option:

usingSystem;usingIncrease.Api;IncreaseClientclient=new(){Timeout=TimeSpan.FromSeconds(42)};

Or configure a single method call using WithOptions:

usingSystem;varaccount=awaitclient.WithOptions(options =>optionswith{Timeout=TimeSpan.FromSeconds(42)}).Accounts.Create(parameters);Console.WriteLine(account);

Proxies

To route requests through a proxy, configure your client with a custom HttpClient:

usingSystem.Net;usingSystem.Net.Http;usingIncrease.Api;varhttpClient=newHttpClient(newHttpClientHandler{Proxy=newWebProxy("https://example.com:8080")});IncreaseClientclient=new(){HttpClient=httpClient};

Environments

The SDK sends requests to the production environment by default. To send requests to a different environment, configure the client like so:

usingIncrease.Api;usingIncrease.Api.Core;IncreaseClientclient=new(){BaseUrl=EnvironmentUrl.Sandbox};

Undocumented API functionality

The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.

Parameters

To set undocumented parameters, a constructor exists that accepts dictionaries for additional header, query, and body values. If the method type doesn't support request bodies (e.g. GET requests), the constructor will only accept a header and query dictionary.

usingSystem.Collections.Generic;usingSystem.Text.Json;usingIncrease.Api.Models.Accounts;AccountCreateParamsparameters=new(rawHeaderData:newDictionary<string,JsonElement>(){{"Custom-Header",JsonSerializer.SerializeToElement(42)}},rawQueryData:newDictionary<string,JsonElement>(){{"custom_query_param",JsonSerializer.SerializeToElement(42)}},rawBodyData:newDictionary<string,JsonElement>(){{"custom_body_param",JsonSerializer.SerializeToElement(42)}}){// Documented properties can still be added here.// In case of conflict, these parameters take precedence over the custom parameters.Name="New Account!"};

The raw parameters can also be accessed through the RawHeaderData, RawQueryData, and RawBodyData (if available) properties.

This can also be used to set a documented parameter to an undocumented or not yet supported value, as long as the parameter is optional. If the parameter is required, omitting its init property will result in a compile-time error. To work around this, the FromRawUnchecked method can be used:

usingSystem.Collections.Generic;usingSystem.Text.Json;usingIncrease.Api.Models.Accounts;varparameters=AccountCreateParams.FromRawUnchecked(rawHeaderData:newDictionary<string,JsonElement>(),rawQueryData:newDictionary<string,JsonElement>(),rawBodyData:newDictionary<string,JsonElement>{{"name",JsonSerializer.SerializeToElement("custom value")}});

Nested Parameters

Undocumented properties, or undocumented values of documented properties, on nested parameters can be set similarly, using a dictionary in the constructor of the nested parameter.

usingSystem.Collections.Generic;usingSystem.Text.Json;usingIncrease.Api.Models.Accounts;AccountCreateParamsparameters=new(){Loan=new(newDictionary<string,JsonElement>{{"custom_nested_param",JsonSerializer.SerializeToElement(42)}})};

Required properties on the nested parameter can also be changed or omitted using the FromRawUnchecked method:

usingSystem.Collections.Generic;usingSystem.Text.Json;usingIncrease.Api.Models.Accounts;AccountCreateParamsparameters=new(){Loan=Loan.FromRawUnchecked(newDictionary<string,JsonElement>{{"required_property",JsonSerializer.SerializeToElement("custom value")}})};

Response properties

To access undocumented response properties, the RawData property can be used:

usingSystem.Text.Json;varresponse=client.Accounts.Create(parameters)
if (response.RawData.TryGetValue("my_custom_key",outJsonElementvalue)){// Do something with `value`}

RawData is a IReadonlyDictionary<string, JsonElement>. It holds the full data received from the API server.

Response validation

In rare cases, the API may return a response that doesn't match the expected type. For example, the SDK may expect a property to contain a string, but the API could return something else.

By default, the SDK will not throw an exception in this case. It will throw IncreaseInvalidDataException only if you directly access the property.

If you would prefer to check that the response is completely well-typed upfront, then either call Validate:

varaccount=client.Accounts.Create(parameters);account.Validate();

Or configure the client using the ResponseValidation option:

usingIncrease.Api;IncreaseClientclient=new(){ResponseValidation=true};

Or configure a single method call using WithOptions:

usingSystem;varaccount=awaitclient.WithOptions(options =>optionswith{ResponseValidation=true}).Accounts.Create(parameters);Console.WriteLine(account);

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
  2. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

About

C# / .NET library for the Increase API

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Contributors

Languages