C# Example API Call (Get)

An API, or Application Programming Interface, is a library of related programme code available for programmers to use. People and organisations can provide a service, which is available to use via an API. In the case of the example below, weather data is made available via an HTTP Get request, which returns the data in JSON format. This API returns a five-day forecast, for a specific area, at three hourly intervals. Full details of this API can be found on the Rapid API website here, as well as the API's own website here.

A sample of the weather data returned can be seen below, which covers two time periods on a particular day. It should be noted that the data is returned in one long JSON string, rather than nicely formatted, as shown here.

{
  "data": [
    {
      "wind_cdir": "SSE",
      "rh": 77,
      "pod": "d",
      "timestamp_utc": "2021-07-10T18:00:00",
      "pres": 1004.16,
      "solar_rad": 230.854,
      "ozone": 343.75,
      "weather": {
        "icon": "c02d",
        "code": 802,
        "description": "Scattered clouds"
      },
      "wind_gust_spd": 3.51483,
      "timestamp_local": "2021-07-10T19:00:00",
      "snow_depth": 0,
      "clouds": 65,
      "ts": 1625940000,
      "wind_spd": 1.72796,
      "pop": 0,
      "wind_cdir_full": "south-southeast",
      "slp": 1014.86,
      "dni": 642.37,
      "dewpt": 13.1,
      "snow": 0,
      "uv": 1.02432,
      "wind_dir": 159,
      "clouds_hi": 0,
      "precip": 0,
      "vis": 24.128,
      "dhi": 73.33,
      "app_temp": 17.1,
      "datetime": "2021-07-10:18",
      "temp": 17.1,
      "ghi": 279.27,
      "clouds_mid": 34,
      "clouds_low": 51
    },
    {
      "wind_cdir": "S",
      "rh": 82,
      "pod": "n",
      "timestamp_utc": "2021-07-10T21:00:00",
      "pres": 1004.96,
      "solar_rad": 0,
      "ozone": 328.25,
      "weather": {
        "icon": "c04n",
        "code": 804,
        "description": "Overcast clouds"
      },
      "wind_gust_spd": 2.98049,
      "timestamp_local": "2021-07-10T22:00:00",
      "snow_depth": 0,
      "clouds": 96,
      "ts": 1625950800,
      "wind_spd": 1.18709,
      "pop": 0,
      "wind_cdir_full": "south",
      "slp": 1015.7,
      "dni": 0,
      "dewpt": 12.9,
      "snow": 0,
      "uv": 0,
      "wind_dir": 172,
      "clouds_hi": 65,
      "precip": 0,
      "vis": 24.128,
      "dhi": 0,
      "app_temp": 15.8,
      "datetime": "2021-07-10:21",
      "temp": 15.8,
      "ghi": 0,
      "clouds_mid": 80,
      "clouds_low": 62
    },
  "city_name": "Bath",
  "lon": -2.36,
  "timezone": "Europe/London",
  "lat": 51.38,
  "country_code": "GB",
  "state_code": "ENG"
}

In order for this to work, the package 'Newtonsoft.Json' needs to be added to the project. This can be done in a couple of different ways, depending on what Integrated Development Environment (IDE) is being used. Visual Studio incorporates NuGet Package Manager, which allows for packages to be searched for and installed. For IDEs that don't have a built-in package manager, PowerShell can be used. The following command can be used to install the above-mentioned package. Before running this command, it is necessary to navigate to the folder where the project resides.

dotnet add package Newtonsoft.Json

Once added, a ‘using‘ statement for the ‘Newtonsoft.Json.Linq’ namespace needs to be included.

using System;
using System.Net.Http;
using Newtonsoft.Json.Linq;

namespace DemoAPICallGet
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            
            try
            {

                // Client for HTTP request and response.
                var client = new HttpClient();

                // API request.
                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Get,
                    RequestUri = new Uri(
                        "https://weatherbit-v1-mashape.p.rapidapi.com/forecast/" +
                        "3hourly?lat=51.38488&lon=-2.36197"),
                    Headers =
                    {
                        { "x-rapidapi-key", "API-KEY-GOES-HERE" },
                        { "x-rapidapi-host", "weatherbit-v1-mashape.p.rapidapi.com" },
                    },
                };

                // API response.
                using (var response = await client.SendAsync(request))
                {

                    // Throw an error if there is not a successful response.
                    response.EnsureSuccessStatusCode();

                    // Assign the body of the response to a variable and parse the JSON.
                    var json = await response.Content.ReadAsStringAsync();
                    dynamic weather = JObject.Parse(json);

                    // Display the city name.
                    Console.WriteLine(weather.city_name);

                    // Display the information for each day and time period.
                    foreach (var dayTime in weather.data)
                    {

                        // Display as: 'Date Time - Temperature - Weather Description'.
                        Console.WriteLine((DateTime)dayTime.timestamp_local + " - " +
                            (int)Math.Round((double)dayTime.temp) + "\u00b0C - " +
                            dayTime.weather.description);

                    }

                }

            }
            catch (Exception e)
            {

                // Display generic API call unsuccessful message.
                Console.WriteLine("API call unsuccessful.");

                // Display actual error.
                Console.Write(e.Message);

            }
        }
    }
}

Once the data has been retrieved, it is assigned to a variable called 'json', which is then parsed, so that the individual elements can be accessed. Firstly, the city name is displayed, followed by the weather data for each day and time period. The 'timestamp_local', which contains the date and time period, is cast, or converted, to a 'datetime' to improve its display. Similarly, the 'temp', which contains the temperature in Celsius, is cast to a 'double', before rounding to the nearest whole number and then casting to an 'int', or integer, to display.

Sample output to the console can be seen below.

Bath
10/07/2021 19:00:00 - 16°C - Overcast clouds
10/07/2021 22:00:00 - 15°C - Overcast clouds
11/07/2021 01:00:00 - 14°C - Overcast clouds
11/07/2021 04:00:00 - 13°C - Overcast clouds
11/07/2021 07:00:00 - 13°C - Overcast clouds
11/07/2021 10:00:00 - 16°C - Overcast clouds
11/07/2021 13:00:00 - 17°C - Overcast clouds
11/07/2021 16:00:00 - 16°C - Light shower rain
11/07/2021 19:00:00 - 15°C - Overcast clouds
11/07/2021 22:00:00 - 14°C - Light shower rain
12/07/2021 01:00:00 - 14°C - Light rain
12/07/2021 04:00:00 - 14°C - Light rain
12/07/2021 07:00:00 - 14°C - Light shower rain
12/07/2021 10:00:00 - 14°C - Light shower rain
12/07/2021 13:00:00 - 16°C - Overcast clouds
12/07/2021 16:00:00 - 18°C - Overcast clouds
12/07/2021 19:00:00 - 18°C - Overcast clouds
12/07/2021 22:00:00 - 16°C - Overcast clouds
13/07/2021 01:00:00 - 15°C - Overcast clouds
13/07/2021 04:00:00 - 15°C - Overcast clouds
13/07/2021 07:00:00 - 16°C - Overcast clouds
13/07/2021 10:00:00 - 18°C - Scattered clouds
13/07/2021 13:00:00 - 21°C - Overcast clouds
13/07/2021 16:00:00 - 22°C - Scattered clouds
13/07/2021 19:00:00 - 20°C - Few clouds
13/07/2021 22:00:00 - 16°C - Few clouds
14/07/2021 01:00:00 - 14°C - Few clouds
14/07/2021 04:00:00 - 13°C - Overcast clouds
14/07/2021 07:00:00 - 16°C - Overcast clouds
14/07/2021 10:00:00 - 19°C - Overcast clouds
14/07/2021 13:00:00 - 22°C - Overcast clouds
14/07/2021 16:00:00 - 23°C - Overcast clouds
14/07/2021 19:00:00 - 21°C - Overcast clouds
14/07/2021 22:00:00 - 17°C - Few clouds
15/07/2021 01:00:00 - 15°C - Scattered clouds
15/07/2021 04:00:00 - 16°C - Overcast clouds
15/07/2021 07:00:00 - 16°C - Overcast clouds
15/07/2021 10:00:00 - 19°C - Broken clouds
15/07/2021 13:00:00 - 20°C - Broken clouds
15/07/2021 16:00:00 - 21°C - Scattered clouds