How to use Refit to consume APIs in ASP.NET Core ?

Using Refit to consume APIs in an ASP.NET Core application is a great way to simplify HTTP requests with a clean, strongly-typed interface. Here’s a step-by-step guide on how to set it up:

### Step 1: Install Refit
First, you need to install the Refit NuGet package. You can do this using the Package Manager Console or by modifying your `.csproj` file.
**Using Package Manager Console:**
Install-Package Refit

**Using .NET CLI:**
dotnet add package Refit

### Step 2: Define Your API Interface
Create an interface that defines the endpoints you want to call. Use Refit attributes to specify HTTP methods and route templates.

using Refit;
using System.Collections.Generic;
using System.Threading.Tasks;
public interface IMyApi
{
    [Get("/users")]
    Task<List<User>> GetUsersAsync();
    [Get("/users/{id}")]
    Task<User> GetUserAsync(int id);
    [Post("/users")]
    Task<User> CreateUserAsync([Body] User user);
}
```
### Step 3: Register the API Client in `Startup.cs`
In your `Startup.cs` file, register the Refit client in the Dependency Injection (DI) container.

using Microsoft.Extensions.DependencyInjection;
using Refit;
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        // Register Refit client
        services.AddRefitClient<IMyApi>()
                .ConfigureHttpClient(c => c.BaseAddress = new Uri("https://api.example.com"));
    }
    // Other configurations (Configure method)...
}
```
### Step 4: Inject the API Client into Your Services or Controllers
Now you can inject `IMyApi` wherever you need to consume the API.

using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
    private readonly IMyApi _myApi;
    public UsersController(IMyApi myApi)
    {
        _myApi = myApi;
    }
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var users = await _myApi.GetUsersAsync();
        return Ok(users);
    }
    [HttpGet("{id}")]
    public async Task<IActionResult> Get(int id)
    {
        var user = await _myApi.GetUserAsync(id);
        return user != null ? Ok(user) : NotFound();
    }
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] User user)
    {
        var createdUser = await _myApi.CreateUserAsync(user);
        return CreatedAtAction(nameof(Get), new { id = createdUser.Id }, createdUser);
    }
}
```
### Step 5: Define Your Models
Ensure you have your models defined that match the expected request and response structures from the API.

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}
```
### Step 6: Configure Error Handling (Optional)
You can create a custom exception handler or middleware to manage errors that may arise during API calls.
### Step 7: Run Your Application
Now, you can run your application, and it should successfully communicate with the API using the Refit client you’ve set up.
### Conclusion
By following these steps, you can effectively use Refit in your ASP.NET Core application to consume APIs in a clean and maintainable way. This approach helps keep your HTTP calls organized and leverages the power of interfaces for better testing and code readability. 

Post a Comment

0 Comments