Make a GET request

PHOTO EMBED

Sun Mar 24 2024 15:51:56 GMT+0000 (Coordinated Universal Time)

Saved by @aguest #c#

using System;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

class Program
{
  	// Async main method
    static async Task Main(string[] args)
    {
      	// Call the API and create a `Todo` object named "todo"
        Todo todo = await GetTodoAsync();

      	// Log the object's properties to the console
        Console.WriteLine($"Todo ID: {todo.Id}");
        Console.WriteLine($"Todo Title: {todo.Title}");
        Console.WriteLine($"Todo Completed: {todo.Completed}");
    }

	// Async method to get a `Todo` object
    static async Task<Todo> GetTodoAsync()
    {
      	// Create the HTTP client
        using (HttpClient client = new HttpClient())
        {
          	// Make the async GET request and save the response in "response"
            HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/todos/1");

          	// If we got a 200 status code
            if (response.IsSuccessStatusCode)
            {
              	// Serialize the HTTP content of the response into a C# string object named "json"
                string json = await response.Content.ReadAsStringAsync();

              	// Deserialize the "json" string into a `Todo` object named "todo"
                Todo todo = JsonSerializer.Deserialize<Todo>(json);
                return todo;
            }
            else
            {
              	// Throw an exception with a custom message that prints the bad status code
                throw new HttpRequestException($"Failed to get todo. Status code: {response.StatusCode}");
            }
        }
    }
}


// A class that represents each object in the JSON response
class Todo
{
    [JsonPropertyName("userId")]  // The field's name in the JSON response
    public int UserId { get; set; }  // How we'll refer to that property in the C# code (userId becomes UserId)

    [JsonPropertyName("id")]
    public int Id { get; set; }

    [JsonPropertyName("title")]
    public string Title { get; set; }

    [JsonPropertyName("completed")]
    public bool Completed { get; set; }
}


content_copyCOPY