Making faster API calls using the Refit Rest library
Refit is a rest library written in C# and available as a NuGet package. It is designed to make faster HTTP calls with less code. It has a specific syntax that we have to follow in our services/classes to make API calls. In this article, we will learn how we can use Refit to make API calls. For that, we will create a simple API project with some API calls. Then we will create a Blazor Web Assembly project that will call APIs using the Refit library.
Web API project with APIs
First of, all I will create an ASP.NET Core Web API project.
On the next screen, give your app a name and then select a .NET version (I am using .NET 6 in this article). Also, don’t forget to check the OpenAPI checkbox, it will add swagger to API.
When the project is created, Add a class Person in your models’ folder with the following properties.
Create a controller PersonsController and add the following code
Run the application, if everything is ok, your browser will look like following
CORS (Cross-Origin Resource Sharing)
To make API calls from any other API or project, we must tell our Web API by allowing CORS. Go to your Program.cs (If you are using a lower version, go to a startup.cs file) and add the following code.
Creating frontend project
API is ok and working fine. Now, I will create a Blazor Web Assembly Project as a frontend app and will consume APIs in it using Refit.
Create a new Blazor Web Assembly project.
Run the project to check if it is working fine and then install Refit Packages from Nuget
Then in the models folder, create a Person model with the same properties as in your Web API project.
Create a service class that will make API calls using Refit. Add the below code in it.
Refit has its syntax. On every method, the [Get] attribute with the same method name (API name) will be added. This attribute will tell the method to call that API. For example in the API project we have /Persons API that will return us all Persons. So in [Get(“/Persons”)], we added it with the same name. Similarly, with all other methods, we provided the same API name to call that API. It is important to use the same name.
Now in your Program.cs file, we have to tell the application to use IPersonApiService to call APIs using Refit. For that, add the following code to your Program.cs file.
Then in your razor page Index.razor, add the following code
Run both projects at the same time because the Frontend project will call the API project to get/post data. API project also must be running. After the successful running of both projects. The browser will look like following
We are calling methods from IPersonApiService class which is calling APIs using Refit and sending us a response that is displaying on the page. Add, Update and Delete buttons are also using APIs to perform specific operations.
If you want to get code download it from GitHub.
Originally published here