Building Simple API Gateways with Ocelot and ASP.net Core
In the previous article, we've discovered what is an API gateway and the cool things that it brings. This article will demonstrate how to build a simple API gateway that routes incoming HTTP requests to the appropriate downstream services.
Articles in the Series
This article belongs to a series of articles that explains the importance of API gateways and how to build them using ASP.net Core. If you're interested to learn more about API gateways, it might be a good idea to spend some time reading the articles listed below.- Part 1: API Gateway in a Nutshell.
- Part 2: Building Simple API Gateways with Ocelot.
- Part 3: API Response Aggregation using Ocelot
- Part 4: API Defense using Rate Limiting and Ocelot.
- Part 5: Containerizing API Gateways
- Part 6: Containerizing API Gateways using Alpine Base Image
Introducing Ocelot
Download POC from GithubOcelot is an open source framework used for building .NET core API gateways, the project is aimed at people using .NET / .NET Core to build applications designed with microservices or SOA architectures. Ocelot provides an easy way to write a mapping file (ocelot.json) that could be used to route incoming HTTP requests to the appropriate downstream services.
See: GITHUB | Official Website
Battle Plan
In this guide, we'll build an API gateway for an e-commerce website. The e-commerce API will contain three sub-domains that we'll call "Authentication", "Catalog" and "Ledger" contexts. The gateway we'll build in this article will behave like a reverse proxy that routes incoming HTTP requests to the following downstream services:
- Authentication Service - Bounded context in-charge of managing all authentication related things like end-users and access to system.
- Catalog Service - Bounded context in-charge of managing all offered products.
- Ledger Service - Bounded context in-charge of managing all monetary-product transactions in the system.
Setup
If you want to skip the setup phase, you can download a bunch of bash scripts that I wrote to automate the generation of the four ASP.net core projects. Once you've downloaded the scripts, place them in a folder to group the output of the automation process and execute the script named 100_build-api-gateway.sh.
If you are a newbie in ASP.net Core or just keen to learn how the setup works, you can follow the steps below:
-
Generate 4 ASP.net Core Projects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersdotnet new webapi --name Authentication dotnet new webapi --name Ledger dotnet new webapi --name Catalog dotnet new webapi --name Gateway -
Generate Solution and Attach Projects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersdotnet new sln --name GatewayDemo dotnet sln GatewayDemo.sln add Authentication/Authentication.csproj dotnet sln GatewayDemo.sln add Ledger/Ledger.csproj dotnet sln GatewayDemo.sln add Catalog/Catalog.csproj dotnet sln GatewayDemo.sln add Gateway/Gateway.csproj -
Install Ocelot Nuget Package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters# Navigate to the Gateway's directory # to install Ocelot in it. cd Gateway dotnet add package Ocelot --version 10.0.4 -
Generate POCOs and Controllers
You can navigate to a sample project from GITHUB and copy the following models and controllers to your solutions:-
User Model
./Authentication/Models/User.cs Github Link -
User Controller
./Authentication/Controllers/UserController.cs Github Link -
Product Model
./Catalog/Models/Product.cs Github Link -
Project Controller
./Catalog/Controllers/ProductController.cs Github Link -
Transaction Model
./Ledger/Models/Transaction.cs Github Link -
Transaction Contorller
./Ledger/Controllers/TransactionController.cs Github Link
-
-
Configure Service Ports via launchSettings.json
In order to route HTTP requests properly, you have to ensure that each service will be able to run on the following local ports:- Authentication: http://localhost:52792/
- Catalog: http://localhost:52791
- Ledger: http://localhost:52790
- Gateway: http://localhost:52793
-
Start and test individual bounded context services
Test the solutions by running each of them and issuing a GET request against the following URLS:- Authentication: http://localhost:52792/api/user
- Catalog: http://localhost:52791/api/product/
- Ledger: http://localhost:52790/api/transaction
Configuring Ocelot
Now lets focus on the most important detail which is configuring Ocelot. The first thing that we have to do is configure the ocelot.json file and add the code below.
{ | |
"ReRoutes": [ | |
], | |
"GlobalConfiguration": { | |
"BaseUrl": "http://localhost:52793" | |
} | |
} |
Navigate to the Program.cs file of the Gateway project and add the following configurations on the web host builder method. The code below will setup all the middlewares required by ocelot to function.
// Add the following using statements. | |
using Ocelot.Middleware; | |
using Ocelot.DependencyInjection; | |
// Add the code below to the | |
// Program.cs file @ BuildWebHost method | |
.ConfigureAppConfiguration((hostingContext, config) => | |
{ | |
// Informs the app to use the ocelot.json file | |
config.AddJsonFile("ocelot.json"); | |
}) | |
.ConfigureServices(s => | |
{ | |
// Enables injection of service | |
// dependencies of Ocelot. | |
s.AddOcelot(); | |
}) | |
.Configure(app => | |
{ | |
// Includes Ocelot middleware. | |
app.UseOcelot().Wait(); | |
}) |
Setting up your Routes
Now that everything we need in the gateway side is configured, its time to setup routes using the ocelot.json file. Update your ocelot.json file by updating the re-routes section.
"ReRoutes": [ | |
// Authentication | |
{ | |
"DownstreamPathTemplate": "/api/user/", | |
"DownstreamScheme": "http", | |
"DownstreamHostAndPorts": [ | |
{ | |
"Host": "localhost", | |
"Port": 52792 | |
} | |
], | |
"UpstreamPathTemplate": "/api/user/", | |
"UpstreamHttpMethod": [ "Get" ] | |
}, | |
// Catalog Service Route | |
{ | |
"DownstreamPathTemplate": "/api/product/", | |
"DownstreamScheme": "http", | |
"DownstreamHostAndPorts": [ | |
{ | |
"Host": "localhost", | |
"Port": 52791 | |
} | |
], | |
"UpstreamPathTemplate": "/api/product/", | |
"UpstreamHttpMethod": [ "Get" ] | |
}, | |
// Transaction Service Route | |
{ | |
"DownstreamPathTemplate": "/api/transaction/", | |
"DownstreamScheme": "http", | |
"DownstreamHostAndPorts": [ | |
{ | |
"Host": "localhost", | |
"Port": 52790 | |
} | |
], | |
"UpstreamPathTemplate": "/api/transaction/", | |
"UpstreamHttpMethod": [ "Get" ] | |
} | |
], |
- Gateway to Authentication
- Gateway to Catalog
- Gateway to Ledger
Testing the routes out
To test the routes, start all projects and navigate to each link listed below.
- User Endpoint http://localhost:52793/api/user
- Products Endpoint http://localhost:52793/api/product
- Transaction Endpoint http://localhost:52793/api/transaction
Conclusion
In this article, we've learned how to perform basic re-routing of HTTP requests from a gateway to downstream services using Ocelot. Please do note that the article only explained basic re-routing and the power of API gateways starts to shine with request aggregation which is the subject of the next article.
Related Articles
- Part 1: API Gateway in a Nutshell.
- Part 2: Building Simple API Gateways with Ocelot.
- Part 3: API Response Aggregation using Ocelot
- Part 4: API Defense using Rate Limiting and Ocelot.
- Part 5: Containerizing API Gateways
- Part 6: Containerizing API Gateways using Alpine Base Image
- 10 Steps to Setup and Containerize an Express Server
- Microservices: Picking the .NET Framework for your containerized applications.
I think you should make a video how to build it and share such video on youtube. If you use this site https://soclikes.com you can promote your video faster
ReplyDeleteVery informative. I advice you to post this article as a video-review on Youtube so that many interested people can see it. And you can always use the services of https://viplikes.net/buy-youtube-subscribers to increase their number.
ReplyDeleteThanks for sharing excellent information.keep sharing such useful information..You can apply Indian business visa application through Online indian evisa website.
ReplyDeleteVery nice post, I definitely love this website, keep up the good work.. yes. Azerbaijan visa for US citizens can be acquired in a breeze with the convenience of online Azerbaijan Visa application processes. The Azerbaijan government has launched a new online visa system, wherein you can fill an application and receive your Azerbaijan visa entirely online .
ReplyDeleteHello sir, Hope your evening is going well. Do you need an evisa to India? You can find more information about e visa to India on our website about India e visa.
ReplyDeleteHello friends, Indian visa for US citizens, Indian e-Visa is issued for USA citizens under the following 5 categories. More info about Indian visas you can read through our website.
ReplyDeleteperde modelleri
ReplyDeletesms onay
mobil ödeme bozdurma
nft nasıl alınır
ANKARA EVDEN EVE NAKLİYAT
Trafik Sigortası
dedektor
KURMA WEB SİTESİ
Aşk Romanları
Within these pages lies a mesmerizing journey into the realms of exploration, where curiosity knows no bounds and ideas are the currency of discovery. Can i get Bahrain visa on arrival by roadBahrain does extend visa-on-arrival services, even for road entries. Streamlining entry formalities, this eases travel logistics. Nonetheless, verify your passport's validity and adhere to entry prerequisites beforehand. With Bahrain's flexible visa protocols, discovering this lively Gulf destination becomes more convenient, whether arriving by road or other modes of transportation.
ReplyDelete