API Gateway In .NET 6.0 Using Ocelot

In this tutorial, we are going to learn how to implement an API Gateway using Ocelot. We will be looking at the below topics,

  1. What is an API Gateway?
  2. Introduction to Ocelot
  3. Create simple services
  4. Implement API Gateway using Ocelot

The source code can be downloaded from GitHub.

What is an API Gateway?

When building microservices based applications, an API Gateway is required to have a central place where authentication, throttling, orchestration, etc. is implemented.

Without an API Gateway in place, we might up end up implementing all these features (authentication, throttling, etc.) in each of the services and hence maintaining them for each service would be discouraging.

API Gateway acts as a security layer since we do not need to expose the microservices directly, instead, consumers requests will be reached at Gateway. Gateway breaks the requests and route them to the respective downstream microservices.

Introduction to Ocelot

Ocelot is an open-source API Gateway, designed for microservice architecture. This is based on .NET Core. Ocelot is a set of middleware designed for features such as routing, caching, security, rate limiting, etc. please refer to the link for more details.

Create Simple Services

We will be creating two simple services for demo purposes.

I have used the below tools for demonstration.

  1. VS 2022 Community Edition (64 bit)– Version 17.4.0 – Preview 2.0
  2. Web API
  3. .NET 6.0
  4. Ocelot
  5. Postman

Let us start two services – one is Student Service and another one is Teacher Service

Student Service looks like below

namespace StudentService.Controllers {
    [Route("api/[controller]")]
    [ApiController]
    public class StudentController: ControllerBase {
        private readonly IStudentRepository _studentRepository;
        public StudentController(IStudentRepository studentRepository) => (_studentRepository) = (studentRepository);
        [HttpGet]
        public IActionResult GetAll() {
                return Ok(_studentRepository.GetAll());
            }
            [HttpGet("{id}")]
        public IActionResult Get(int id) {
            var student = _studentRepository.Get(id);
            if (student is null) return NotFound();
            return Ok(student);
        }
    }
}

Update the launchSettings.json as below for Student Service,

"profiles": {
    "StudentService": {
        "commandName": "Project",
        "dotnetRunMessages": true,
        "launchBrowser": false,
        //"launchUrl": "swagger",
        "applicationUrl": "http://localhost:5001",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        }
    }

The entire source can be downloaded from GitHub.

Teacher Service looks like below,

namespace TeacherService.Controllers {
    [Route("api/[controller]")]
    [ApiController]
    public class TeacherController: ControllerBase {
        private readonly ITeacherRepository _repository;
        public TeacherController(ITeacherRepository repository) => _repository = repository;
        [HttpGet]
        public IActionResult GetAll() {
                return Ok(_repository.GetAll());
            }
            [HttpGet("{Id}")]
        public IActionResult Get(int id) {
            var teacher = _repository.Get(id);
            if (teacher is null) return NotFound();
            return Ok(teacher);
        }
    }
}

Update launchSettings.json for Teacher service as below,

"profiles": {
    "TeacherService": {
        "commandName": "Project",
        "dotnetRunMessages": true,
        "launchBrowser": false,
        //"launchUrl": "swagger",
        "applicationUrl": "http://localhost:5002",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        }
    }

The source code can be downloaded from GitHub.

Implement Gateway using Ocelot

Let us go ahead and create an empty ASP.NET Core project. And then install the Ocelot package.

Install-Package Ocelot

Once the installation is complete, let us go ahead and update launchSettings.json as below

"profiles": {
    "OcelotGateway": {
        "commandName": "Project",
        "dotnetRunMessages": true,
        "launchBrowser": true,
        "launchUrl": "swagger",
        "applicationUrl": "http://localhost:5003",
        "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
        }

We need to create a JSON file – ocelot.json at the root project level in Gateway project

Let us modify the file and define the below two keys

  • GlobalConfiguration
  • Routes - an array of objects.
{
    "GlobalConfiguration": {},
    "Routes": [{}]
}

Now we need to configure our project to use the ocelot.json fine. Please configuration needs to be done in Program.cs file as below,

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

The namespaces which need to be imported are,

using Ocelot.DependencyInjection;
using Ocelot.Middleware;

Now, let us configure the Ocelot.json file.

Inside the GlobalConfiguration key, we need to setup the API Gateway host and port.

"GlobalConfiguration": {
    "BaseUrl": "http://localhost:5003"
}

Now, we are going to configure the Routes key.

"Routes": [{
    "UpstreamPathTemplate": "/gateway/students",
    "UpstreamHttpMethod": ["Get"],
    "DownstreamPathTemplate": "/api/student",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [{
        "Host": "localhost",
        "Port": 5001
    }]
}, {
    "UpstreamPathTemplate": "/gateway/students/{Id}",
    "UpstreamHttpMethod": ["Get"],
    "DownstreamPathTemplate": "/api/student/{Id}",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [{
        "Host": "localhost",
        "Port": 5001
    }]
}, {
    "UpstreamPathTemplate": "/gateway/teachers",
    "UpstreamHttpMethod": ["Get"],
    "DownstreamPathTemplate": "/api/teacher",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [{
        "Host": "localhost",
        "Port": 5002
    }]
}, {
    "UpstreamPathTemplate": "/gateway/teacher/{Id}",
    "UpstreamHttpMethod": ["Get"],
    "DownstreamPathTemplate": "/api/teachers/{Id}",
    "DownstreamScheme": "http",
    "DownstreamHostAndPorts": [{
        "Host": "localhost",
        "Port": 5002
    }]
}]

As a final step, to run all the services simultaneously, right click on Solution and select Properties, update the below highlighted settings.

API Gateway In .NET 6.0 Using Ocelot

Now instead of executing the downstream service, let us go ahead and execute the gateway and see the result.

Execute the below Gateway end point and see whether we are getting the expected result

API Gateway In .NET 6.0 Using Ocelot

Now, let us execute the below endpoint for teachers

API Gateway In .NET 6.0 Using Ocelot

Download the source code from GitHub and try other endpoints.

So far, we have seen how Ocelot can be leveraged to implement API Gateway. Ocelot is an open- source framework for API Gateway. It has many features. I will be explaining a few of its features in my upcoming tutorials. Thank you for reading my article and requesting you to leave comments in the comment box below.