Refit

pic

Хочу познайомити вас з дуже корисною бібліотекою для .NET, що дозволяє викликати API - Refit.

Я буду викликати REST Countries API.

Використаю цей кінцевий пункт https://restcountries.com/v3.1/alpha/{code} для отримання інформації про країну за кодом.

Я використовував chatgpt для перетворення JSON-відповіді в C# класи.
Нижче ви можете знайти результат:

public class Country  
{  
 public Name Name { get; set; }  
 public List Tld { get; set; }  
 public string Cca2 { get; set; }  
 public string Ccn3 { get; set; }  
 public string Cca3 { get; set; }  
 public string Cioc { get; set; }  
 public bool Independent { get; set; }  
 public string Status { get; set; }  
 public bool UnMember { get; set; }  
 public Dictionary Currencies { get; set; }  
 public Idd Idd { get; set; }  
 public List Capital { get; set; }  
 public List AltSpellings { get; set; }  
 public string Region { get; set; }  
 public string Subregion { get; set; }  
 public Dictionary Languages { get; set; }  
 public Dictionary Translations { get; set; }  
 public List Latlng { get; set; }  
 public bool Landlocked { get; set; }  
 public List Borders { get; set; }  
 public double Area { get; set; }  
 public Demonyms Demonyms { get; set; }  
 public string Flag { get; set; }  
 public Maps Maps { get; set; }  
 public long Population { get; set; }  
 public Dictionary Gini { get; set; }  
 public string Fifa { get; set; }  
 public Car Car { get; set; }  
 public List Timezones { get; set; }  
 public List Continents { get; set; }  
 public Flags Flags { get; set; }  
 public CoatOfArms CoatOfArms { get; set; }  
 public string StartOfWeek { get; set; }  
 public CapitalInfo CapitalInfo { get; set; }  
 public PostalCode PostalCode { get; set; }  
}  

public class Name  
{  
 public string Common { get; set; }  
 public string Official { get; set; }  
 public Dictionary NativeName { get; set; }  
}  

public class NativeName  
{  
 public string Official { get; set; }  
 public string Common { get; set; }  
}  

public class Currency  
{  
 public string Name { get; set; }  
 public string Symbol { get; set; }  
}  

public class Idd  
{  
 public string Root { get; set; }  
 public List Suffixes { get; set; }  
}  

public class Translation  
{  
 public string Official { get; set; }  
 public string Common { get; set; }  
}  

public class Demonyms  
{  
 public Gender Eng { get; set; }  
 public Gender Fra { get; set; }  
}  

public class Gender  
{  
 public string F { get; set; }  
 public string M { get; set; }  
}  

public class Maps  
{  
 public string GoogleMaps { get; set; }  
 public string OpenStreetMaps { get; set; }  
}  

public class Car  
{  
 public List Signs { get; set; }  
 public string Side { get; set; }  
}  

public class Flags  
{  
 public string Png { get; set; }  
 public string Svg { get; set; }  
 public string Alt { get; set; }  
}  

public class CoatOfArms  
{  
 public string Png { get; set; }  
 public string Svg { get; set; }  
}  

public class CapitalInfo  
{  
 public List Latlng { get; set; }  
}  

public class PostalCode  
{  
 public string Format { get; set; }  
 public string Regex { get; set; }  
}

Нам потрібно додати NuGet пакет:

dotnet add package Refit.HttpClientFactory

Я створюю консольний додаток.
Отже, мені потрібно додати ще й наступне:

dotnet add package Microsoft.Extensions.Http

Щоб використовувати Refit, нам потрібно додати інтерфейс API:

using Refit;  

internal interface IRestCountriesApi  
{  
 [Get("/alpha/{code}")]  
 Task GetByCode();  
}

І зареєструвати його:

var sp = new ServiceCollection();  
sp.AddRefitClient()  
 .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://restcountries.com/v3.1"));

Повний код для Program.cs виглядає так:

using Microsoft.Extensions.DependencyInjection;  
using Refit;  

internal class Program  
{  
 private static async Task Main(string[] args)  
 {  
 var services = new ServiceCollection();  
 services.AddRefitClient()  
 .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://restcountries.com/v3.1"));  
 var serviceProvider = services.BuildServiceProvider();  

 var api = serviceProvider.GetRequiredService();  
 var rs = await api.GetByCodeAsync("PL");  

 foreach (var country in rs)  
 {  
 Console.WriteLine($"Name: {country.Name.Common}");  
 Console.WriteLine($"Region: {country.Region}");  
 Console.WriteLine($"Subregion: {country.Subregion}");  
 Console.WriteLine($"Population: {country.Population}");  
 Console.WriteLine($"Area: {country.Area}");  
 Console.WriteLine();  
 }  
 }  
}

І результат:

Name: Poland  
Region: Europe  
Subregion: Central Europe  
Population: 37950802  
Area: 312679

Як бачите, це дуже просто.
Звісно, відкрите питання — чи варто використовувати зовнішні бібліотеки у наших проєктах. На мою думку, ми повинні добре подумати, перш ніж впроваджувати їх у довготривалі проєкти, але в інших випадках ми можемо розглядати такі рішення.

Перекладено з: Refit

Leave a Reply

Your email address will not be published. Required fields are marked *