Create a rest client

Posted by ugh82 on Wed, 09 Mar 2022 16:48:50 +0100

Create a rest client

precondition

. NET Core Download

Visual Studio Code

Create application

Create a separate folder and run console commands

dotnet new console --name WebAPIClient

Add a new dependency

Applications can handle JSON responses.

dotnet add package System.Text.Json

Make a web request

First, open Program. In the project directory CS file, and then add the following methods to the Program class:

private static async Task ProcessRepositories()
{
}

You need to add the using instruction at the top of the Main method so that the C# compiler can recognize it Task Type:

using System.Threading.Tasks;
  1. Update the Main method to call the ProcessRepositories method

  2. The ProcessRepositories method returns a task and should not exit the program before this task is completed

    Add the async modifier and change the return type to Task

  3. In the body of the method, add a call to ProcessRepositories. Add the await keyword to the method call:

static async Task Main(string[] args)
{
    await ProcessRepositories();
}

Generated a program that does not perform any operation but has asynchronous function

Improve web requests

  1. First, we need an object that can retrieve data from the Web; Available HttpClient Do this. This object is responsible for processing requests and responses. In Program An instance of this type is initialized in the Program class in the. CS file.

    namespace WebAPIClient
    {
        class Program
        {
            private static readonly HttpClient client = new HttpClient();
    
            static async Task Main(string[] args)
            {
                //...
            }
        }
    }
    
  2. Let's go back to the ProcessRepositories method and populate its first version:

    private static async Task ProcessRepositories()
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
        client.DefaultRequestHeaders.Add("User-Agent", ".NET Foundation Repository Reporter");
    
        var stringTask = client.GetStringAsync("https://api.github.com/orgs/dotnet/repos");
    
        var msg = await stringTask;
        Console.Write(msg);
    }
    
  3. In order for the compilation to proceed smoothly, two new using instructions need to be added at the top of the file:

    using System.Net.Http;
    using System.Net.Http.Headers;
    

Processing JSON results

  1. Convert the corresponding JSON response into a C# object
using System;

namespace WebAPIClient
{
    public class Repository
    {
        public string name { get; set; }
    }
}

Add the above code to the new file "repo.cs". This version of the class represents the simplest path to handle JSON data

  1. Use a serializer to convert JSON to C# objects. Replace the pair in the ProcessRepositories method with the following line GetStringAsync(String) Call to:

    var streamTask = client.GetStreamAsync("https://api.github.com/orgs/dotnet/repos");
    var repositories = await JsonSerializer.DeserializeAsync<List<Repository>>(await streamTask);
    

    Add namespace at the top of the file

    using System.Collections.Generic;
    using System.Text.Json;
    
  2. Displays the name of each repository

    foreach (var repo in repositories)
        Console.WriteLine(repo.name);
    
  3. Compile and run the application. Will print to The name of the repository for. NET Foundation.

Control serialization

  1. Before adding more features, let's deal with the name attribute by using the [JsonPropertyName] attribute. Yes, repo The name field in CS declares the following changes:

    //using System.Text.Json.Serialization;
    [JsonPropertyName("name")]
    public string Name { get; set; }
    

    Change means that changes need to be used in program CS to write the code for each repository Name:

    Console.WriteLine(repo.Name);
    

    Run dotnet run to see the output

  2. The ProcessRepositories method can perform asynchronous work and return a set of repositories. We will use this method to return list < repository >, and move the code used to write the information to the Main method.

    private static async Task<List<Repository>> ProcessRepositories()
    

    Then, after processing the JSON response, only return to the repository:

    var streamTask = client.GetStreamAsync("https://api.github.com/orgs/dotnet/repos");
    var repositories = await JsonSerializer.DeserializeAsync<List<Repository>>(await streamTask);
    return repositories;
    

    The compiler will generate a task < T > object that returns content because you have marked this method async. Then, we will modify the Main method to capture these results and write each repository name to the console. Now, the Main method is as follows:

    public static async Task Main(string[] args)
    {
        var repositories = await ProcessRepositories();
    
        foreach (var repo in repositories)
            Console.WriteLine(repo.Name);
    }
    

Read details

  1. Handle other properties in JSON packets sent by GitHub API

  2. Add some other simple types to the Repository class definition. Add these attributes to this class:

    [JsonPropertyName("description")]
    public string Description { get; set; }
    
    [JsonPropertyName("html_url")]
    public Uri GitHubHomeUrl { get; set; }
    
    [JsonPropertyName("homepage")]
    public Uri Homepage { get; set; }
    
    [JsonPropertyName("watchers")]
    public int Watchers { get; set; }
    

    After adding these elements, update the Main method to display them:

    foreach (var repo in repositories)
    {
        Console.WriteLine(repo.Name);
        Console.WriteLine(repo.Description);
        Console.WriteLine(repo.GitHubHomeUrl);
        Console.WriteLine(repo.Homepage);
        Console.WriteLine(repo.Watchers);
        Console.WriteLine();
    }
    
  3. Let's add information about the last push operation. This information is formatted in the JSON response as follows:

    2016-02-08T21:27:00Z
    

    The format is coordinated universal time (UTC), so you will get one DateTime Value of the value Kind Attribute is Utc . If you prefer dates in time zones, you need to write custom conversion methods. First, define a public attribute, which will save the UTC representation of date and time in the Repository class, and define a LastPush readonly attribute, which returns the date converted to local time:

    [JsonPropertyName("pushed_at")]
    public DateTime LastPushUtc { get; set; }
    
    public DateTime LastPush => LastPushUtc.ToLocalTime();
    

    Add another output statement in the console, and then you can build and run the application again:

    Console.WriteLine(repo.LastPush);
    

This article is composed of one article multi posting platform ArtiPub Automatic publishing