Skip to content

bilasdk/csharp

Repository files navigation

Bila C# API Library

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

It is generated with Stainless.

Installation

Install the package from NuGet:

dotnet add package Usebila

Requirements

This library requires .NET Standard 2.0 or later.

Usage

using System;
using Usebila;
using Usebila.Models.Accounts;

BilaClient client = new()
{
    ApiKey = "Your API key",
    BaseUrl = EnvironmentUrl.Sandbox, // either EnvironmentUrl.Production or EnvironmentUrl.Sandbox
};

AccountListParams parameters = new();

AccountListResponse accounts = await client.Accounts.List(parameters);

Console.WriteLine(accounts);

Examples

Runnable examples live in the examples directory. Each file demonstrates a specific area of the API:

Example Description
accounts.cs Retrieve accounts, list accounts, and check balances
banks.cs List supported banks and financial institutions
collections.cs Collect payments via mobile money
resolve.cs Verify bank account and mobile money details
transactions.cs Retrieve and list transaction history
transfer-recipients.cs Manage payout recipients
transfers.cs Send payouts via bank transfer and mobile money
webhooks.cs Configure webhooks and manage delivery history

To run an example from this repository:

dotnet run --project examples -- accounts

Replace accounts with any example from the table above. Set your API key via the BILA_API_KEY environment variable or in the example file before running.

Client configuration

Configure the client using environment variables:

using Usebila;

// Configured using the BILA_API_KEY and BILA_BASE_URL environment variables
BilaClient client = new();

Or manually:

using Usebila;

BilaClient client = new() { ApiKey = "My API Key" };

Or using a combination of the two approaches.

See this table for the available options:

Property Environment variable Required Default value
ApiKey BILA_API_KEY true -
BaseUrl BILA_BASE_URL true "https://api.usebila.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:

using System;

var accounts = await client
    .WithOptions(options =>
        options with
        {
            BaseUrl = "https://example.com",
            Timeout = TimeSpan.FromSeconds(42),
        }
    )
    .Accounts.List(parameters);

Console.WriteLine(accounts);

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 Bila 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.List should be called with an instance of AccountListParams, and it will return an instance of Task<AccountListResponse>.

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:

var response = await client.WithRawResponse.Accounts.List();
var statusCode = response.StatusCode;
var headers = 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:

using System;
using Usebila.Models.Accounts;

var response = await client.WithRawResponse.Accounts.List();
AccountListResponse deserialized = await response.Deserialize();
Console.WriteLine(deserialized);

Error handling

The SDK throws custom unchecked exception types:

  • BilaApiException: Base class for API errors. See this table for which exception subclass is thrown for each HTTP status code:
Status Exception
400 BilaBadRequestException
401 BilaUnauthorizedException
403 BilaForbiddenException
404 BilaNotFoundException
422 BilaUnprocessableEntityException
429 BilaRateLimitException
5xx Bila5xxException
others BilaUnexpectedStatusCodeException

Additionally, all 4xx errors inherit from Bila4xxException.

  • BilaIOException: I/O networking errors.

  • BilaInvalidDataException: 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.

  • BilaException: Base class for all exceptions.

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:

using Usebila;

BilaClient client = new() { MaxRetries = 3 };

Or configure a single method call using WithOptions:

using System;

var accounts = await client
    .WithOptions(options =>
        options with { MaxRetries = 3 }
    )
    .Accounts.List(parameters);

Console.WriteLine(accounts);

Timeouts

Requests time out after 1 minute by default.

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

using System;
using Usebila;

BilaClient client = new() { Timeout = TimeSpan.FromSeconds(42) };

Or configure a single method call using WithOptions:

using System;

var accounts = await client
    .WithOptions(options =>
        options with { Timeout = TimeSpan.FromSeconds(42) }
    )
    .Accounts.List(parameters);

Console.WriteLine(accounts);

Proxies

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

using System.Net;
using System.Net.Http;
using Usebila;

var httpClient = new HttpClient
(
    new HttpClientHandler
    {
        Proxy = new WebProxy("https://example.com:8080")
    }
);

BilaClient client = 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:

using Usebila;
using Usebila.Core;

BilaClient client = 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.

using System.Collections.Generic;
using System.Text.Json;
using Usebila.Models.Accounts;

AccountListParams parameters = new
(
    rawHeaderData: new Dictionary<string, JsonElement>()
    {
        { "Custom-Header", JsonSerializer.SerializeToElement(42) }
    },

    rawQueryData: new Dictionary<string, JsonElement>()
    {
        { "custom_query_param", JsonSerializer.SerializeToElement(42) }
    }
)
{
    // Documented properties can still be added here.
    // In case of conflict, these parameters take precedence over the custom parameters.
    Page = 1
};

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:

using System.Collections.Generic;
using System.Text.Json;
using Usebila.Models.TransferRecipients;

var parameters = TransferRecipientCreateBankAccountParams.FromRawUnchecked
(

    rawHeaderData: new Dictionary<string, JsonElement>(),
    rawQueryData: new Dictionary<string, JsonElement>(),
    rawBodyData: new Dictionary<string, JsonElement>
    {
        {
            "accountNumber",
            JsonSerializer.SerializeToElement("custom value")
        }
    }
);

Response properties

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

using System.Text.Json;

var response = client.Accounts.List()
if (response.RawData.TryGetValue("my_custom_key", out JsonElement value))
{
    // 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 BilaInvalidDataException 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:

var accounts = client.Accounts.List();
accounts.Validate();

Or configure the client using the ResponseValidation option:

using Usebila;

BilaClient client = new() { ResponseValidation = true };

Or configure a single method call using WithOptions:

using System;

var accounts = await client
    .WithOptions(options =>
        options with { ResponseValidation = true }
    )
    .Accounts.List(parameters);

Console.WriteLine(accounts);

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

No description, website, or topics provided.

Resources

License

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors