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!
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 returns 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; }
}