Getting Started with Refit in .NET
Recap of Refit
Refit is the automatic type-safe REST library for .NET Core, Xamarin and .NET.
It lets you define your API calls using C# interfaces in simple three steps.
public interface IGitHubApi
{
[Get("/users/{user}")]
Task<User> GetUser(string user);
}
string url = "https://api.github.com";
var gitHubApi = RestService.For<IGitHubApi>(url);
var octocat = await gitHubApi.GetUser("octocat");
services.AddRefitClient<IGitHubApi>()
.ConfigureHttpClient(c => c.BaseAddress = new Uri(url));
That is not the target for todayβs newsletter, if you are not aware about how to use Refit in .NET then check this article I wrote earlier :
Using Refit to Consume APIs in .NET Core
π What Are Query Attributes and How to Add Them?
When you pass parameters in the query string of a URL, the parameters are appended to the URL after a question mark (?), and each parameter is specified as a key-value pair. Multiple parameters are separated by an ampersand (&). The general syntax is as follows:
http://example.com/path/to/resource?parameter1=value1
We can achieve similar in refit like this :
[Post("/api/student/details")]
Task<GetStudentDetailResponse> GetStudentDetailAsync(
[Query] int studentId,
GetStudentDetailCommand command,
CancellationToken cancellationToken = default);
Parameter with [Query] would be passed as a query string and the one in command would be passed in body.
If you wish to add multiple parameters then add them and just add [Query] before that.
π How to Properly Set the Content Type Header
Content headers are essential, we need to set them with each request. Let me show you how would I add that.
I prefer to make a delegating handler for it, here you can read about it :
HTTP Message Handlers in ASP.NET Web API
public class AddDefaultContentHeader : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
request.Headers.Add("Accept", "application/json");
return await base.SendAsync(request, cancellationToken);
}
}
services.AddRefitClient<IStudentRefitApi>(refitSettings)
.ConfigureHttpClient(configureClient)
.AddHttpMessageHandler<AddDefaultContentHeader>();
π How to Add Bearer Token in Headers
Similarly I can create a delegating handler for adding bearer token.
public sealed class AddBearerTokenHeader : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
string token = "som-token";
string bearerToken = $"Bearer {token}";
request.Headers.Add("Authorization", bearerToken);
return await base.SendAsync(request, cancellationToken);
}
}
We can register it similarly as we did with content header. Add this handler only with your secure APIs which need token for successful call.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place