Building a Centralized API Proxy with YARP in .NET 8 Using Minimal APIs

Leandro Veiga - Sep 2 - - Dev Community

In today's microservices-oriented architecture, managing multiple APIs can become a complex and time-consuming task. Whether you're dealing with authentication, routing, or load balancing, having a centralized API proxy can streamline these processes and enhance the overall efficiency of your system. In this blog post, we'll walk through the steps of creating a proxy API using YARP (Yet Another Reverse Proxy) in .NET 8 with Minimal APIs.

What is YARP?

YARP, short for Yet Another Reverse Proxy, is an open-source library by Microsoft that allows developers to create powerful and customizable reverse proxies. Built on top of .NET, YARP provides an easy-to-use framework for routing and managing API traffic. With YARP, you can implement load balancing, failover, and various other routing strategies without reinventing the wheel.

Why Use a Centralized API Proxy?

Before diving into the code, let's explore why you might want to centralize your API management:

  1. Simplified Routing: Centralize routing logic to direct client requests to the appropriate services.
  2. Security: Implement consistent authentication and authorization across all your APIs.
  3. Load Balancing: Distribute requests evenly across multiple instances of your services to ensure reliability.
  4. Monitoring and Logging: Centralize monitoring and logging to gain better insights into API usage and performance.

Setting Up the Project

To get started, you'll need to have .NET 8 installed on your machine. If you haven't already, you can download the latest version from the official .NET website.

Next, create a new ASP.NET Core project using the Minimal API template:

dotnet new web -n CentralizedProxyApi
Enter fullscreen mode Exit fullscreen mode

Once your project is set up, add the YARP library:

dotnet add package Yarp.ReverseProxy
Enter fullscreen mode Exit fullscreen mode

Configuring YARP with Minimal APIs

Now, let's configure YARP to route incoming requests to different APIs using Minimal APIs. Open the Program.cs file and add the following code:

using Yarp.ReverseProxy.Configuration;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddReverseProxy()
    .LoadFromMemory(GetRoutes(), GetClusters());

var app = builder.Build();

app.MapReverseProxy();

app.Run();

static IEnumerable<RouteConfig> GetRoutes()
{
    return new[]
    {
        new RouteConfig
        {
            RouteId = "route1",
            ClusterId = "cluster1",
            Match = new RouteMatch
            {
                Path = "/api/service1/{**catch-all}"
            }
        },
        new RouteConfig
        {
            RouteId = "route2",
            ClusterId = "cluster2",
            Match = new RouteMatch
            {
                Path = "/api/service2/{**catch-all}"
            }
        }
    };
}

static IEnumerable<ClusterConfig> GetClusters()
{
    return new[]
    {
        new ClusterConfig
        {
            ClusterId = "cluster1",
            Destinations = new Dictionary<string, DestinationConfig>
            {
                { "destination1", new DestinationConfig { Address = "https://service1.example.com/" } }
            }
        },
        new ClusterConfig
        {
            ClusterId = "cluster2",
            Destinations = new Dictionary<string, DestinationConfig>
            {
                { "destination2", new DestinationConfig { Address = "https://service2.example.com/" } }
            }
        }
    };
}
Enter fullscreen mode Exit fullscreen mode

Explaining the Code

  • AddReverseProxy(): Registers YARP services in the dependency injection container.
  • GetRoutes(): Defines the routes for the proxy. Each route maps to a specific path and is associated with a cluster.
  • GetClusters(): Defines the clusters, which represent the destination APIs. Each cluster contains one or more destinations (API endpoints).
  • MapReverseProxy(): This maps incoming requests to the configured routes and forwards them to the appropriate destination.

Testing Your Proxy

With the basic configuration in place, you can now run your application:

dotnet run
Enter fullscreen mode Exit fullscreen mode

You should be able to send requests to your proxy at http://localhost:5000/api/service1 or http://localhost:5000/api/service2, and YARP will forward them to the respective API endpoints.

Advanced Scenarios

YARP is highly customizable, allowing you to implement advanced routing strategies, add middleware for logging and authentication, and even configure load balancing algorithms. For more information, you can refer to the official YARP documentation.

Conclusion

By using YARP with .NET 8 and Minimal APIs, you can create a robust and flexible proxy API that simplifies the management of multiple APIs in your architecture. Whether you're dealing with microservices or simply want to centralize API management, YARP provides the tools you need to build a scalable and maintainable solution.

Happy coding!

. . .
Terabox Video Player