Creating microservices in .Net core using ocelot apigateway
Tags: dotnet, microservices, docker, kubernetes
Published: 2022-11-06 11:53:45

This is the second part where we are going to build the microservices. So, we will have an ocelot apigateway and two microservices are Products and Orders. Let's start with the microservices.

First create a new project from CLI. dotnet new webapi -n Products is the command to create a new web api project.

> dotnet new webapi -o Products

![Products](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g3ensaxjdv7mfdqhxcwa.png)

This is our first microservice called products. Now create new controller named ProductsController.cs.

```
using Microsoft.AspNetCore.Mvc;

namespace apigateway.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public List<string> Get()
    {
        List<string> products = new List<string>();
        products.Add("Samsung products");
        products.Add("Apple products");
        products.Add("Google products");
        products.Add("Microsoft products");
        return products;
    }
}
```
This get method will return the list of products.Products microservice is running on a http://localhost:8001. When you hit the http://localhost:8001/api/products. It will return the following response.


![Product response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ftv54avqr28oiqe6ltah.png)

Now we have one microservice up and running. Create second microservice called Orders. For creating the second microservice follow the same steps.

> dotnet new webapi -o Orders


![Orders](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6alq3o5bhe1ujii0zdpu.png)


This is our second microservice called orders. Now create new controller named OrdersController.cs.

```
using Microsoft.AspNetCore.Mvc;

namespace apigateway.Controllers;

[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
    [HttpGet]
    public List<string> Get()
    {
        List<string> orders = new List<string>();
        orders.Add("Order 1");
        orders.Add("Order 2");
        orders.Add("Order 3");
        orders.Add("Order 4");
        return orders;
    }
}
```

Orders microservice is running on a http://localhost:8002. When you hit http://localhost:8002/api/orders. It will return the following response.


![Order response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ew7v80f7rmp90659mr0j.png)

This microservices are just for the implementing microservices architecture. Using this microservices you will get knowledge
of microservices architecture with an apigateway.

Now here is the main step. We have to implement an apigateway. Follow the same steps for creating project. We need to create one more project for an apigateway. 

> dotnet new webapi -o Apigateway

After creating project you have to install nuget package Ocelot. Now install that package.


![Ocelot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/alyl93h0wsiuavx38uqk.png)

After installing the package. We have to update program.cs . 

```
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Configuration.SetBasePath(builder.Environment.ContentRootPath).AddJsonFile("Ocelot.json", optional: false, reloadOnChange: true).AddEnvironmentVariables();
builder.Services.AddOcelot(builder.Configuration);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
await app.UseOcelot();
app.Run();
```

Here we added some lines of code for ocelot. builder.Configuration.SetBasePath will sets the FileProvider for file-based providers to a PhysicalFileProvider with the base path. For that we have to create Ocelot.json.

Ocelot.json
```
{
    "Routes": [
        {
            "DownstreamPathTemplate": "/api/products",
            "DownstreamScheme": "http",
            "DownstreamHostAndPorts": [
                {
                    "Host": "localhost",
                    "Port": 8001
                }
            ],
            "UpstreamPathTemplate": "/products",
            "UpstreamHttpMethod": [
                "Get"
            ]
        },
        {
            "DownstreamPathTemplate": "/api/orders",
            "DownstreamScheme": "http",
            "DownstreamHostAndPorts": [
                {
                    "Host": "localhost",
                    "Port": 8002
                }
            ],
            "UpstreamPathTemplate": "/orders",
            "UpstreamHttpMethod": [
                "Get"
            ]
        }
    ]
}
```

**DownstreamPathTemplate** : The endpoint of a microservice.
**DownstreamScheme** : The scheme of a microservice.
**DownstreamHostAndPorts** : Here you need to define the host and port of the microservice.
**UpstreamPathTemplate** : The path at which the client will request the Ocelot Apigateway.
**UpstreamHttpMethod** : The Http method to the apigateway. The method should match with the endpoint method.

Apigateway is running on a http://localhost:8888. Apigateway will act as a single entry point for our all microservices. Lets test whether an apigateway working right or not.


![postman response for products](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ms0dc6p3lswhqt7jrmk1.png)


![postman response for orders](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jeqnxnflfp39wmiffx88.png)

In next article we are going to [dockerize the microservices and apigateway](https://dev.to/siddharth151199/creating-docker-image-of-microservices-and-apigateway-3ild).