joydip_kanjilal
Contributor

How to use FastEndpoints in ASP.NET Core

how-to
Jul 11, 20247 mins
C#Development Libraries and FrameworksMicrosoft .NET

Take advantage of the free open-source FastEndpoints library to build fast and lean APIs in your ASP.NET Core applications.

Smart motorway in England, UK with light trails signifying busy traffic at rush hour. The NSL symbols under the gantry sign signify an end to speed restrictions.
Credit: Cal F / Shutterstock

FastEndpoints is a free and open-source REST API development framework for .NET Core that can be used to build lightweight and fast APIs. In this article, we’ll examine this library and learn how to use it to build lightweight APIs in ASP.NET Core applications.

ASP.NET Core supports two built-in approaches to building APIs, traditional controllers and minimal APIs. Traditional controllers (i.e., MVC and API controllers in ASP.NET Core) are feature-rich, but they require writing a lot of boilerplate code and they don’t match minimal APIs in performance. Minimal APIs are lightweight and fast, but they support only a minimal set of features.

A third option is to use a third-party library for building APIs such as FastEndpoints, which combines benefits of both controllers and minimal APIs. While minimal APIs are slightly faster than FastEndpoints, FastEndpoints provides several features that are not supported by minimal APIs including model binding, rate limiting, and caching. Moreover, if you use FastEndpoints in lieu of minimal APIs, you can take advantage of Swagger or OpenAPI to document your APIs.

Introducing FastEndpoints

An implementation of the REPR (Request-Endpoint-Response) design pattern, FastEndpoints is a developer-friendly, minimalist alternative to minimal APIs and traditional MVC and API controllers. The REPR design pattern simplifies API development by organizing your APIs around endpoints instead of controllers. It provides distinct separation between the input request, the logic at the endpoint, and the output response.

In the sections that follow, we’ll examine how we can use FastEndpoints to build fast and lean APIs in ASP.NET Core. Our implementation will include an endpoint class, a request DTO (Data Transfer Object) class, and a response DTO class.

Create an ASP.NET Core Web API project in Visual Studio 2022

To create an ASP.NET Core Web API project in Visual Studio 2022, follow the steps outlined below.

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  6. Click Next.
  7. In the “Additional Information” window shown next, select “.NET 8.0 (Long Term Support)” as the framework version and uncheck the check box that says “Use controllers,” as we’ll be using minimal APIs in this project.
  8. Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes “Enable OpenAPI Support,” “Configure for HTTPS,” and “Enable Docker” remain unchecked. We won’t be using any of those features here.
  9. Click Create.

We’ll use this ASP.NET Core Web API minimal API project to work with the code examples given in the sections below.

Install the FastEndpoints NuGet package

To work with FastEndpoints library, we’ll need to install the FastEndpoints NuGet package in the project. To do this, select the project in the Solution Explorer window, then right-click and select “Manage NuGet Packages.”

In the NuGet Package Manager window, search for the FastEndpoints package and install it. Alternatively, you can install the packages via the NuGet Package Manager console by entering the command shown below.

PM> Install-Package FastEndpoints

Register the FastEndpoints library

To add FastEndpoint services to the ASP.NET Core request processing pipeline, enter the following line of code in the Program.cs file.

builder.Services.AddFastEndpoints();

Note that at runtime, the FastEndpoints library excludes endpoints that are located in any of the assembly names that are part of the exclusion list. You can take a look at how that has been implemented here.

If your endpoint is located in any of those assembly names, the FastEndpoints library will throw an exception at runtime during its registration process. To avoid this exception, rename your project to a name that is not on the exclusion list or specify an assembly name manually as shown in the following code snippet.

builder.Services.AddFastEndpoints(
    o => o.Assemblies = new[]
    {
        typeof(FastEndpoints_Demo.MyFirstRequest).Assembly,
        typeof(FastEndpoints_Demo.MyFirstResponse).Assembly
    });

Next we’ll create our first endpoint using the FastEndpoints library. This endpoint will handle a HTTP POST request and send the response back to the client.

Create a request class

To create a request DTO, create a new C# class named MyFirstRequest and replace the generated code with the following code snippet.

namespace FastEndpoints_Demo
{
    public class MyFirstRequest
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Create a response class

To create a response DTO, create a new C# class named MyFirstResponse and replace the generated code with the following code.

namespace FastEndpoints_Demo
{
    public class MyFirstResponse
    {
        public string Message { get; set; }
    }
}

Create an endpoint class

An endpoint class can be created by extending the Endpoint base class. Your custom endpoint class should use the request and response DTOs to store data. Let’s now create a new C# class named MyFirstEndpoint and give it the following code.

using FastEndpoints;
namespace FastEndpoints_Demo.Endpoints
{
    public class MyFirstEndpoint : Endpoint<MyFirstRequest, MyFirstResponse>
    {
        public override void Configure()
        {
            Post("/api/author/create");
            AllowAnonymous();
        }
        public override async Task HandleAsync(MyFirstRequest request, CancellationToken token)
        {
            await SendAsync(new()
            {
                Message = $"The author name is: {request.FirstName} {request.LastName}"
            });
        }
    }
}

As you can see in the preceding code listing, the custom endpoint class should override the Configure and HandleAsync methods. Configure is used to configure how your custom endpoint should listen to incoming requests. HandleAsync contains the necessary logic for processing the request and sending back the response.

Complete Program.cs file

The following is the complete source code of the Program.cs file for your reference.

using FastEndpoints;
var builder = WebApplication.CreateBuilder();
builder.Services.AddFastEndpoints(
    o => o.Assemblies = new[]
    {
        typeof(FastEndpoints_Demo.MyFirstRequest).Assembly,
        typeof(FastEndpoints_Demo.MyFirstResponse).Assembly
    });
var app = builder.Build();
app.UseFastEndpoints();
app.Run();

Execute the application

Finally, run the application and browse the endpoint using Postman with the following request body.

{
    "FirstName": "Joydip",
    "LastName": "Kanjilal"
}

Figure 1 shows the output you should see upon invoking the endpoint.

FastEndpoints API in ASP.NET Core

Figure 1. FastEndpoints in action. 

IDG

FastEndpoints is a free third-party alternative to ASP.NET Core’s built-in legacy controllers and minimal APIs. FastEndpoints combines performance on a par with minimal APIs and a structured approach to handling HTTP requests and responses. I’ll demonstrate how we can implement security, versioning, validation, dependency injection, caching, and rate limiting with FastEndpoints in future posts here.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author