Home > Software engineering >  API GET request in C#
API GET request in C#

Time:06-27

I have a task where I have to write a program which displays you the sunrise and sunset time at your location on a WPF GUI (C#). To make this work, I need to use the Sunrise Sunset API from https://sunrise-sunset.org/api

The description says: "Ours is a very simple REST api, you only have to do a GET request to https//api.sunrise-sunset.org/json."

Because of the fact that I am a beginner and I've never used an API before, I don't know how to make a GET Request.

So my questions are: What even is a GET Request and how can I make one to use the sunrise-sunset API?

Cheers!

CodePudding user response:

What even is a GET Request?

So, the Hypertext Transfer Protocol (HTTP) is a thing, it's the thing that allows us to browse the internet, it defines how the actual content of a website (and many more things) are transferred. So, say, Alice wants to access some content that's located at http://www.example.org, she'd enter that address into her browser and BAM! like magic she can see the page, but how? Because of HTTP.

HTTP works with verbs (also called methods), those verbs are POST, GET, PUT, PATCH, and DELETE, but the two that make up a majority of traffic are GET and POST (probably in that order), but what does that mean? It's basically a way of conveying intent, GET means I intend to GET some resource, be it some HTML, JavaScript and CSS (a website) or some JSON data, or some XML data, or anything really (you can read more on what each verb means here). We call a HTTP request with the GET verb a GET request.

But how does that work? So, under the hood, HTTP is a text based protocol, and the first thing in that text is always the verb followed by a location specifier, followed by the HTTP version to use. So the first line of our GET request to the sunrise-sunset API is

GET /json HTTP/1.1

After which come the HTTP headers. HTTP headers are basically just metadata about the request, there is one which is mandatory though, and many websites can also just say "hey, you know what, we need a authorization header as part of your request", but let's just focus on the mandatory one, it's the Host header, so

Host: api.sunrise-sunset.org

Knowing this, we could technically just open a TCP Socket to the IP address associated with api.sunrise-sunset.org, send our text, and we'd get a response (some oversimplification here), but that's dumb, we want to automate this process, so we'll write some code for it.

But first lets take a look at what comes back, specifically the status code. HTTP defines a handful of status codes, you can see the entire list here. Each individual status code conveys something about our request, I won't go into too much detail, but I'll take a look at 200 OK and 404 Not Found

200 OK means that everything went fine. Our request was properly processed and did what we told it to do. In our case we'll also get the data we requested back.

404 Not Found means that whatever we requested wasn't found on the server. This means we'll have to look at our request and change something. You can test this out in your browser by going to a page that doesn't exist, so https://api.sunrise-sunset.org/banana

The response from a HTTP request is also in a text format, starting with the HTTP version, followed by the status code, followed by response headers and finally the body (or content) with the data we care about. In our case, the entire answer is

HTTP/1.1 200 OK
Server: nginx
Date: Mon, 27 Jun 2022 06:15:50 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Access-Control-Allow-Origin: *

{"results":{"sunrise":"5:58:19 AM","sunset":"6:07:51 PM","solar_noon":"12:03:05 PM","day_length":"12:09:32","civil_twilight_begin":"5:36:57 AM","civil_twilight_end":"6:29:14 PM","nautical_twilight_begin":"5:10:45 AM","nautical_twilight_end":"6:55:25 PM","astronomical_twilight_begin":"4:44:26 AM","astronomical_twilight_end":"7:21:44 PM"},"status":"OK"}

Now let's write some code.

But how?

Googling C# http comes up with the documentation for the HttpClient class, neat.
And it even has an example, extra neat.

So let's copy and paste that example, modifying the request URL, and we get this

using HttpClient client = new HttpClient();

HttpResponseMessage response = await client.GetAsync("https//api.sunrise-sunset.org/json");
response.EnsureSuccessStatusCode();
string requestBody = await response.Content.ReadAsStringAsync();

Console.WriteLine(requestBody);

Now we should see the JSON data on our console, yay!

But that alone really isn't very helpful, we'll want to parse (deserialize) our JSON into an object so we can work with it like any old regular object. Microsoft themselves have a great article about it here

CodePudding user response:

According to the API document, you should specify the geographic coordinate by lat and lng in the API Uri. In the following example, I set them lat=36.7201600&lng=-4.4203400.

Then, using HttpClient.GetStringAsync method, I send a GET request to the Uri. It return the response body as a string.

Next, I deserialize the string to my DTO object (here SunriseSunsetDto). and then get sunrise and sunset properties.

Here is the methods:

   public string GetSunrise()
    {
        HttpClient client = new HttpClient();
        var responce = client.GetStringAsync("https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400").Result;
        var Sunrise = JsonSerializer.Deserialize<SunriseSunsetDto>(responce.ToString()).Results.Sunrise;
        return Sunrise;
    }
    public string GetSunset()
    {
        HttpClient client = new HttpClient();
        var responce = client.GetStringAsync("https://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400").Result;
        var Sunset = JsonSerializer.Deserialize<SunriseSunsetDto>(responce.ToString()).Results.Sunset;
        return Sunset;
    }

And here is the SunriseSunsetDto class:

public class SunriseSunsetDto
{
    public Results Results { get; set; }
    public string Status { get; set; }
}
public class Results
{
    [JsonPropertyName("sunrise")]
    public string Sunrise { get; set; }
    [JsonPropertyName("sunset")]
    public string Sunset { get; set; }
    [JsonPropertyName("solar_noon")]
    public string SolarNoon { get; set; }
    [JsonPropertyName("day_length")]
    public string DayLength { get; set; }
    [JsonPropertyName("civil_twilight_begin")]
    public string CivilTwilightBegin { get; set; }
    [JsonPropertyName("civil_twilight_end")]
    public string CivilTwilightEnd { get; set; }
    [JsonPropertyName("nautical_twilight_begin")]
    public string NauticalTwilightBegin { get; set; }
    [JsonPropertyName("nautical_twilight_end")]
    public string NauticalTwilightEnd { get; set; }
    [JsonPropertyName("astronomical_twilight_begin")]
    public string AstronomicalTwilightBegin { get; set; }
    [JsonPropertyName("astronomical_twilight_end")]
    public string AstronomicalTwilightEnd { get; set; }
}
  • Related