Building a custom API Gateway with YARP
17 Oct 2023Whenever you are designing an architecture with microservices, you might encounter in how to implement an API Gateway
, since you need a way to communicate and consume multiple services, generally through APIs. A possible solution is to have a single entry point for all your clients and implement an API Gateway
, which will handle all the requests and route those to appropiate microservices.
There are different ways to implement an API Gateway or pay for built-in services in cloud hostings.
In this post I will pick the easiest way that I found to create one for a microservice architecture using .NET
and YARP
. Here is a general overview of a microservice architecture.
YARP
YARP
(which stands for “Yet Another Reverse Proxy”) is an open-source project that Microsoft built for improving routing through internal services using a built-in reverse proxy server. This become very popular and was implemented for several Azure products as App Service.
- To get started, you need to create an ASP.NET core empty project. I chose .NET 7.0 for this post.
- Install YARP nuget package or add the project reference
.csproj
.
- Add the YARP middleware to your
Program.cs
.
-
To add the YARP configuration you will use
appsettings.json
file. YARP uses routes and clusters, regularilly insideReverseProxy
object defined in builder configuration section. You can find more information about different configuration settings here. -
In this example, I am using
Products
andEmployee
microservices. So I will have routes likeemployee-route
andproduct-route
and clusters asproduct-cluster
andemployee-cluster
pointing to destinations. Open yourappsettings.json
and apply the following configuration.
- In scenarios that you need to allow CORS to specific origins you can add a cors policy described in this Microsoft Doc. Here is a configuration example:
- Then add this CORs policy inside
Routes
as followed:
- Finally if you want to get more information about YARP logging for future debugging or production information, you can add the YARP log level (
Information
,Warning
orError
) insideLogging
object as followed:
- Run the application with
dotnet run
and use Postman or curl to test the endpoints defined in your paths e.g.http://localhost:5212/p/v1/
.Check all possible configurations and transformations in the YARP documentation.