DEV Community

Dhananjay Kumar
Dhananjay Kumar

Posted on

Step by step, use Ocelot as an API Gateway in the .NET Core.

An API Gateway is a front-end server for APIs, handling incoming API requests and routing them to the appropriate backend services. It plays a crucial role in microservice architecture by offering a single entry point to the system.
Some main functionalities of an API Gateway are,

  • Routing
  • Authentication
  • Authorization
  • Request Composition
  • Caching
  • Load Balancing
  • Fault Tolerance
  • Service Discovery

There are many popular choices for API Gateway in.NET Core-based Microservices, such as,

  • Ocelot
  • YARP and others. This blog post explains how Ocelot can be an API Gateway in .NET Core APIs.

Setting up APIs

There are two APIs. The first API has a ProductController with two EndPoints.



  [Route("api/products")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        static List<Product> Products = new List<Product>()
        {
            new Product { Id = 1, Name = "Product 1", Price = 10.0m },
            new Product { Id = 2, Name = "Product 2", Price = 20.0m },
            new Product { Id = 3, Name = "Product 3", Price = 30.0m }
        };
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Product>>> Get()
        {
            var products = await GetProductsAsync();
            await Task.Delay(500);
            return Ok(products);
        }


        [HttpPost]
        public async Task<ActionResult<Product>> Post(Product product)
        {
            Products.Add(product);
            await Task.Delay(500);
            // Return the product along with a 201 Created status code
            return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
        }

        private Task<List<Product>> GetProductsAsync()
        {

            return Task.FromResult(Products);
        }
    }


Enter fullscreen mode Exit fullscreen mode

These EndPoints are available at **http://localhost:5047/api/products **for both GET and POST operations.
The second API has InvoiceController with just one EndPoint.



    [Route("api/invoice")]
    [ApiController]
    public class InvoiceController : ControllerBase
    {
        [HttpGet]
        public async Task<ActionResult<IEnumerable<string>>> Get()
        {
            await Task.Delay(100);
            return new string[] { "Dhananjay", "Nidhish", "Vijay","Nazim","Alpesh" };
        }
    }


Enter fullscreen mode Exit fullscreen mode

The EndPoint is available at http://localhost:5162/api/invoice for the GET operation.

Setting up API Gateway

We are going to set up the API Gateway using Ocelot. For that, let's follow below steps:

  • Create an API project.
  • Do not add any controller to that.

Very first, add the Ocelot package from Nuget to the project.

After adding the Ocelot package, add a file named ocelot.json to the API Gateway project.



{
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5001"
  },
  "Routes": [
    {
      "UpstreamPathTemplate": "/gateway/products",
      "UpstreamHttpMethod": [ "GET" ],
      "DownstreamPathTemplate": "/api/products",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5047
        }
      ]
    },
    {
      "UpstreamPathTemplate": "/gateway/invoice",
      "UpstreamHttpMethod": [ "GET" ],
      "DownstreamPathTemplate": "/api/invoice",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5162
        }
      ]
    }
  ]
}


Enter fullscreen mode Exit fullscreen mode

Let us explore each configuration in the above file.

  • In the GlobalConfiguration section, the BaseUrl is the URL of API Gateway. API clients would interact with this URL. When running the API Gateway project, it should run on this base URL
  • The Routes section contains various routes in the array
  • The Routes have UpStream and DownStream sections.
  • The UpStream section represents the API Gateway
  • The DownStream section represents the APIs.

Above configuration can be depicted in below diagram:

Image description

By the above configuration, when you hit the EndPoint http://localhost:5001/gateway/products , it would be redirected to API EndPoint http://localhost:5047/api/Products

Next in the Program.cs, at the App Gateway startup, add the configuration below.




builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
builder.Services.AddOcelot(builder.Configuration);

app.UseOcelot();


Enter fullscreen mode Exit fullscreen mode

Now run the API Gateway application, and you should be able to navigate the Private APIs. Besides GET, Ocelot also supports other HTTP Verbs. A route for POST operations can be added as shown below.



{
  "UpstreamPathTemplate": "/gateway/products",
  "UpstreamHttpMethod": [ "POST" ],
  "DownstreamPathTemplate": "/api/products",
  "DownstreamScheme": "http",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 5047
    }
  ]
},


Enter fullscreen mode Exit fullscreen mode

Using basic configurations, you should be able to read the HttpContext object, headers, and request objects in the private API.
 
I hope you find this blog post helpful. Thanks for reading it.

Top comments (1)

Collapse
 
pankaj_anjikar_38f8fa2893 profile image
Pankaj Anjikar • Edited

Simpe, short, easy to undersand !!