Sunday, July 7, 2024

Methods to use Refit to eat APIs in ASP.NET Core


Refit is an open-source library for .NET, .NET Core, and Xamarin that makes consuming REST APIs less complicated and simpler by enabling you to outline the API endpoints as C# interfaces, thereby eliminating the necessity to create HTTP requests and parse HTTP responses manually.

On this article we are going to delve into the Refit library for .NET and see first-hand the way it simplifies the event of APIs. To make use of the code examples offered on this article, it’s best to have Visible Studio 2022 put in in your system. In the event you donā€™t have already got a replica, you may obtain Visible Studio 2022 right here.

In sections beneath, we are going to implement two functions, a Contact API and a shopper utility for consuming the Contact API. The Contact API utility will comprise the next varieties:

  • Contact: This represents the mannequin class.
  • IContactRepository: This represents the interface for the contact repository.
  • ContactRepository: This represents the contact repository class that incorporates strategies to return contact knowledge.
  • ContactsController: This represents the API controller used to show Contact API endpoints to API purchasers.

The shopper utility will use Refit to eat the Contact API and show the information retrieved on the console window.

What’s Refit? Why is it helpful?

Refit is a type-safe, quick, REST library for .NET, .NET Core, and Xamarin that turns your REST API into an interface, making it simpler to eat RESTful net providers. Refit mechanically transforms HTTP calls into C# interfaces utilizing attributes to explain REST operations, thereby simplifying the method of connecting with APIs utilizing minimal code.

To eat APIs utilizing Refit, you want an interface that may work together along with your API. Refit acts as a wrapper across the strategies of this interface and handles HTTP requests and responses elegantly. Refit will mechanically generate the required boilerplate code so that you can entry your APIs.

In the event youā€™re utilizing Refit for the primary time, it’s essential to first configure the HTTP shopper occasion by specifying the bottom deal with, HTTP headers, serialization, and deserialization info, and so forth. The next code snippet reveals how we will configure the HTTP shopper occasion to connect with an endpoint in ASP.NET Core.

string baseAddress = "http://localhost:59904/";
HttpClient _client = new HttpClient();
_client.BaseAddress = new Uri($"{BaseUrl}");
_client.DefaultRequestHeaders.Settle for.Clear();
_client.DefaultRequestHeaders.Settle for.Add(new MediaTypeWithQualityHeaderValue("utility/json"));
string url = BaseUrl + "api/authors";
var response = await _client.GetAuthors(url);
if (response.IsSuccessStatusCode)
{Ā 
Ā Ā Ā  var outcome = await response.Content material.ReadAsStringAsync();
Ā Ā Ā  var knowledge = JsonSerializer.Deserialize<Checklist<Creator>>(outcome);
}

In the event youā€™re already utilizing Refit, you needn’t be bothered with the boilerplate code, as a result of Refit can deal with all of those duties with only a few traces of C# code.

string baseAddress = "http://localhost:59904/";
var endpoint = RestService.For<IAuthorService>(baseAddress);
var contacts = await endpoint.GetAuthors();

As you may see from the previous code snippets, Refit can save us lots of effort and time by eliminating the necessity to write the boilerplate code.

Within the subsequent sections, weā€™ll implement a easy net API in ASP.NET Core. After we create our API, weā€™ll implement a Refit shopper to eat it.

Create an ASP.NET Core Internet API undertaking in Visible Studio 2022

To create an ASP.NET Core 8 Internet API undertaking in Visible Studio 2022, comply with the steps outlined beneath.

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on ā€œCreate new undertaking.ā€
  3. Within the ā€œCreate new undertakingā€ window, choose ā€œASP.NET Core Internet APIā€ from the checklist of templates displayed.
  4. Click on Subsequent.
  5. Within the ā€œConfigure your new undertakingā€ window, specify the title and site for the brand new undertaking. Optionally examine the ā€œPlace answer and undertaking in the identical listingā€ examine field, relying in your preferences.
  6. Click on Subsequent.
  7. Within the ā€œExtra Infoā€ window proven subsequent, choose ā€œ.NET 8.0 (Lengthy Time period Assist)ā€ because the framework model and be sure that the ā€œUse controllersā€ field is checked. We shall be utilizing controllers on this undertaking.
  8. Elsewhere within the ā€œExtra Infoā€ window, depart the ā€œAuthentication Sortā€ set to ā€œNoneā€ (the default) and make sure the examine packing containers ā€œAllow Open API Assist,ā€ ā€œConfigure for HTTPS,ā€ and ā€œAllow Dockerā€ stay unchecked. We gainedā€™t be utilizing any of these options right here.
  9. Click on Create.

Weā€™ll use this ASP.NET Core Internet API undertaking to create our API within the sections beneath.

Create the Contact mannequin class

Create a brand new class named Contact within the Internet API undertaking you simply created and enter the code given beneath.

namespace Refit_Demo
{
Ā Ā Ā  public class Contact
Ā Ā Ā  {
Ā Ā Ā Ā Ā Ā Ā  public int Id { get; set; }
Ā Ā Ā Ā Ā Ā Ā  public string FirstName { get; set; }
Ā Ā Ā Ā Ā Ā Ā  public string LastName { get; set; }
Ā Ā Ā Ā Ā Ā Ā  public string Deal with { get; set; }
Ā Ā Ā Ā Ā Ā Ā  public string Cellphone { get; set; }
Ā Ā Ā  }
}

Weā€™ll use the Contact class within the subsequent part to work with knowledge.

Create the ContactRepository class

Subsequent, we’ll create a repository class to work with the Contact knowledge. For the sake of simplicity and brevity, we’ll retailer our knowledge in an inventory in reminiscence. You’ll be able to be happy to alter this implementation to retailer the info in a database as per your necessities. The ContactRepository class implements the IContactRepository. This interface incorporates the declaration of two strategies, specifically, the GetContact and the GetContacts strategies. Whereas the previous returns one contact document based mostly on the id handed to it as a parameter, the latter returns all contacts.

The next code itemizing illustrates each the IContactRepository interface and the ContactRepository class.

public interface IContactRepository
{
Ā Ā Ā  public Contact GetContact(int id);
Ā Ā Ā  public Checklist<Contact> GetContacts();
}
public class ContactRepository: IContactRepository
{
Ā Ā Ā  non-public readonly Checklist<Contact> contacts = new Checklist<Contact>();
Ā Ā Ā  public ContactRepository()
Ā Ā Ā  {
Ā Ā Ā Ā Ā Ā Ā  contacts = new Checklist<Contact>()
Ā Ā Ā Ā Ā Ā Ā  {
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  new Contact()
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  { Id =1, FirstName = "Keaton", LastName = "Underwood",
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  Deal with = "12/3 ABC Street, Chicago, USA",
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  Cellphone = "1234567890"},
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  new Contact(){ Id = 2, FirstName = "John", LastName = "Smith",
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  Deal with = "12/3 ABC Street, New York, USA",
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  Cellphone = "0987654321"}
Ā Ā Ā Ā Ā Ā Ā  };
Ā Ā Ā  }
Ā Ā Ā  public Contact GetContact(int id)
Ā Ā Ā  {
Ā Ā Ā Ā Ā Ā Ā  return contacts.SingleOrDefault(c => c.Id == id);
Ā Ā Ā  }
Ā Ā Ā  public Checklist<Contact> GetContacts()
Ā Ā Ā  {
Ā Ā Ā Ā Ā Ā Ā  return contacts;
Ā Ā Ā  }
}

You’ll be able to register an occasion of sort IContactRepository with the providers assortment within the Program.cs utilizing the next piece of code.

builder.Companies.AddScoped<IContactRepository, ContactRepository>();

It will allow you to make use of dependency injection to create an occasion of sort IContactRepository within the utility.

Create the API controller

Allow us to now create the controller class for our Contacts API. To do that, create a brand new API controller named ContactsController and substitute the generated code with the next code.

utilizing Microsoft.AspNetCore.Mvc;
namespace Refit_Demo.Controllers
{
Ā Ā Ā  [Route("api/[controller]")]
Ā Ā Ā  [ApiController]
Ā Ā Ā  public class ContactsController : ControllerBase
Ā Ā Ā  {
Ā Ā Ā Ā Ā Ā Ā  non-public readonly IContactRepository _contactRepository;
Ā Ā Ā Ā Ā Ā Ā  public ContactsController(IContactRepository contactRepository)
Ā Ā Ā Ā Ā Ā Ā  {
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  _contactRepository = contactRepository;
Ā Ā Ā Ā Ā Ā Ā  }
Ā Ā Ā Ā Ā Ā Ā  [HttpGet]
Ā Ā Ā Ā Ā Ā Ā  public async Process<Checklist<Contact>> Get()
Ā Ā Ā Ā Ā Ā Ā  {
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  return await _contactRepository.GetContacts();
Ā Ā Ā Ā Ā Ā Ā  }
Ā Ā Ā Ā Ā Ā Ā  [HttpGet("{id}")]
Ā Ā Ā Ā Ā Ā Ā  public async Process<Contact> Get(int id)
Ā Ā Ā Ā Ā Ā Ā  {
Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā  return await _contactRepository.GetContact(id);
Ā Ā Ā Ā Ā Ā Ā  }
Ā Ā Ā  }
}

Be aware how we now have used constructor injection to create an occasion of sort IContactRepository within the previous code itemizing.

Within the subsequent sections, weā€™ll create a console utility undertaking and construct the Refit shopper that may eat our contacts API.

Create a .NET Core console utility undertaking in Visible Studio

Comply with the steps outlined beneath to create a brand new .NET Core console utility undertaking in Visible Studio.

  1. Launch the Visible Studio IDE.
  2. Click on on ā€œCreate new undertaking.ā€
  3. Within the ā€œCreate new undertakingā€ window, choose ā€œConsole App (.NET Core)ā€ from the checklist of templates displayed.
  4. Click on Subsequent.
  5. Within the ā€œConfigure your new undertakingā€ window, specify the title and site for the brand new undertaking.
  6. Click on Subsequent.
  7. Within the ā€œExtra infoā€ window proven subsequent, select ā€œ.NET 8.0 (Lengthy Time period Assist)ā€ because the framework model you wish to use.
  8. Click on Create.

Weā€™ll use this .NET Core console utility undertaking to create our Refit API shopper.

Set up the Refit NuGet package deal

To put in Refit into your undertaking, choose the undertaking within the Answer Explorer window, then right-click and choose ā€œHandle NuGet Packages.ā€

Within the NuGet Package deal Supervisor window, seek for the Refit package deal and set up it. Alternatively, you may set up the package deal(s) through the NuGet Package deal Supervisor console by coming into the instructions proven beneath.

PM> Set up-Package deal Refit

Create the Refit API shopper

Now substitute the generated code within the Program.cs file with the next code itemizing.

utilizing Refit;
string baseAddress = "http://localhost:59904/";
var contactsAPI = RestService.For<IContactService>(baseAddress);
var contacts = await contactsAPI.GetContacts();
foreach (var contact in contacts)
{
Ā Ā Ā  Console.WriteLine($"{contact.Id} | {contact.FirstName} |
Ā Ā Ā  {contact.LastName}");
}
Console.ReadLine();
[Headers("Accept: application/json", "Content-type: application/json")]
public interface IContactService
{
Ā Ā Ā  [Get("/api/contacts")]
Ā Ā Ā  public Process<Contact> GetContact(int id);
Ā Ā Ā  [Get("/api/contacts")]
Ā Ā Ā  public Process<Checklist<Contact>> GetContacts();
}
public class Contact
{
Ā Ā Ā  public int Id { get; set; }
Ā Ā Ā  public string FirstName { get; set; }
Ā Ā Ā  public string LastName { get; set; }
Ā Ā Ā  public string Deal with { get; set; }
Ā Ā Ā  public string Cellphone { get; set; }
}

Execute the applying

Since there are two functions on this instance, it’s best to run each one after the other. First, run the API utility adopted by the API shopper console utility. When each functions have been launched, youā€™ll observe the info retrieved from the Contacts API utility displayed on the console as proven in Determine 1.

refit aspnet core IDG

Determine 1. Your Refit API shopper in motion.

Refit is a good alternative for implementing HTTP REST API purchasers. Refit tremendously simplifies the boilerplate code required to connect with and work with REST APIs in your ASP.NET Core functions. One essential level to notice is that once youā€™re utilizing Refit, all requests have to be asynchronous. Refit doesn’t help synchronous community calls.

Copyright Ā© 2024 IDG Communications, Inc.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay Connected

0FansLike
3,912FollowersFollow
0SubscribersSubscribe
- Advertisement -spot_img

Latest Articles