close
close
How to use FastEndpoints in ASP.NET Core
How to use FastEndpoints in ASP.NET Core

FastEndpoints is a free and open source REST API development framework for .NET Core that helps you build lightweight and fast APIs. In this article, we will explore 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) provide a lot of functionality but require writing a lot of boilerplate code and cannot compete with minimal APIs in terms of performance. Minimal APIs are lightweight and fast but support only a minimal set of features.

A third option is to use a third-party library to create APIs, such as FastEndpoints, which combines the benefits of controllers and minimal APIs. While minimal APIs are slightly faster than FastEndpoints, they provide several features that minimal APIs don’t support, including model binding, rate limiting, and caching. Additionally, if you use FastEndpoints instead of minimal APIs, you can leverage Swagger or OpenAPI to document your APIs.

Introducing FastEndpoints

FastEndpoints is an implementation of the Request-Endpoint-Response (REPR) design pattern and 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 a clear separation between the input request, the logic at the endpoint, and the output response.

In the following sections, we’ll explore how we can use FastEndpoints to create fast and lightweight APIs in ASP.NET Core. Our implementation includes an endpoint class, a request data transfer object (DTO) class, and a response DTO class.

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

Follow the steps below to create an ASP.NET Core Web API project in Visual Studio 2022.

  1. Start 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, select the Place solution and project in the same directory check box, depending on your preference.
  6. Click Next.
  7. In the next Additional Information window that appears, select .NET 8.0 (Long Term Support) as the framework version and uncheck the Use Controllers box since we will be using minimal APIs in this project.
  8. In the Additional Information window, leave the Authentication Type set to None (the default) and make sure that the Enable OpenAPI support, Configure for HTTPS, and Enable Docker checkboxes remain unchecked. We won’t be using any of these features here.
  9. Click “Create”.

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

Install the FastEndpoints NuGet package

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

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

PM> Install-Package FastEndpoints

Registering 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 the FastEndpoints library excludes at runtime endpoints that are in any of the assembly names that are part of the exclusion list. You can see how this was implemented here.

If your endpoint is in one of these assembly names, the FastEndpoints library will throw an exception during the registration process at runtime. To avoid this exception, rename your project to a name that is not on the exclusion list or manually specify an assembly name 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 create our first endpoint using the FastEndpoints library. This endpoint will process an HTTP POST request and send the response back to the client.

Creating a requirement 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; }
    }
}

Creating 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; }
    }
}

Creating 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. Now let’s create a new C# class named MyFirstEndpoint and assign the following code to it.

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 above code listing, the custom endpoint class should override the Configure and HandleAsync methods. Configure is used to configure how your custom endpoint should listen for incoming requests. HandleAsync contains the necessary logic to process the request and send back the response.

Complete Program.cs file

For your information, please find below the full source code of the Program.cs file.

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();

Running 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 when calling 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 on-par performance with minimal APIs and a structured approach to processing HTTP requests and responses. In future posts here, I will show how we can implement security, versioning, validation, dependency injection, caching, and rate limiting using FastEndpoints.