Building a Currency Converter in C#

currencyapi.com provides currency data with update rates ranging from daily to minutely update frequencies. Hence, it is the perfect data provider for your C# currency converter. Developer experience is important to us. Therefore, you may access our API using the C# SDK, or alternatively via simple GET requests using an HTTP client. Furthermore, we provide a Postman collection to make the implementation even easier for you. In this tutorial, we will focus on accessing the API directly using GET requests.

Simple C# Currency Converter Example

The C# SDK needs the fewest lines of code. This example uses only .NET's built-in HttpClient; exchange rate data can easily be obtained by running the following script:

Request

using var client = new HttpClient();
client.DefaultRequestHeaders.Add("apikey", "YOUR-API-KEY");

var url = "https://api.currencyapi.com/v3/latest";
var json = await client.GetStringAsync(url);
Console.WriteLine(json);

Since USD is set as a default base currency, all exchange rates are relative to USD. If you would like to change this, simply add the desired base_currency parameter to your request:

Changing the base currency

...
var url = "https://api.currencyapi.com/v3/latest?base_currency=CAD";
...

Also, it is possible to limit the number of currencies that are returned by introducing the currencies parameter to your request.

Limiting the number of currencies returned

...
var url = "https://api.currencyapi.com/v3/latest?base_currency=EUR&currencies=USD,AED,CHF";
...

This will of course not have an impact on the data retrieved, but it will make the response easier to handle and easier to read.

JSON response

    {
        "meta":{
            "last_updated_at":"2023-08-03T23:59:59Z",
            "base_currency":"USD"
        },
        "data":{
            "BIF": {
                "code": "BIF",
                "value": 2825.50500246
            },
            "BMD": {
                "code": "BMD",
                "value": 1
            },
            "BNB": {
                "code": "BNB",
                "value": 0.0041301484
            },
            "BND": {
                "code": "BND",
                "value": 1.3399901826
            },
            "BOB": {
                "code": "BOB",
                "value": 6.9088110813
            },
            "...": "..."
    }
}

The values in the JSON response are exchange rates. Since we intend to build a currency converter, we still have to multiply the exchange rate with the amount that we would like to convert, to end up with the desired result.

Converter Endpoint

If you do not wish to take this small extra step, currencyapi.com provides an extra /convert endpoint that was specifically designed for this task. However, it is not available on the free plan (it is available from the Small plan up).