API Gateway
By the Syncfusion DevTutorials team · Last updated
Put one front door in front of your services so auth, limits, routing and header rules happen once, in one place.
An API gateway is a single entry point that sits between clients and your services. Instead of exposing every service directly to the internet, clients send all requests to the gateway. The gateway performs common tasks such as authentication, rate limiting, routing, logging, and header processing before forwarding the request to the correct service. This helps keep security rules in one place, reduces duplicated code, and makes services easier to manage.
Watch One Forgotten Check Leak Every Order
Brew & Bytes has grown into multiple services: the Menu Service, the Order Service and the Payment Service. Each service is exposed directly to the internet and is responsible for checking tokens on its own. Press Run.
Program.cs — no gateway, one check forgotten
Results:
- The menu service is public, so returning
200 OKis expected. - The payment service correctly checks for a token and returns
401 Unauthorized. - The order service forgot to perform the token check. Without any authentication, it returns every order, including customer information and totals.
In simple words: when every service is responsible for its own security checks, one forgotten check can expose sensitive data. A gateway moves those shared checks into a single place.
TL;DR
- An API gateway is the single public entry point for clients.
- Clients call the gateway, not individual services.
- The gateway performs shared tasks such as authentication, authorization, rate limiting, routing, header processing, and logging.
- Services run in a private network and are not publicly accessible.
- The gateway can pass trusted user information to services.
- The gateway often returns
401 Unauthorized,429 Too Many Requests, and502 Bad Gateway. - Business rules belong inside services, not inside the gateway.
A Real-World Example
Think about a large office building. Visitors enter through a reception desk. The receptionist checks their identity, issues a visitor badge, and directs them to the correct room.
Employees inside the building trust the visitor badge because it came from reception. They do not perform the full identity check again. The building also makes sure visitors cannot enter through side doors.
In this example:
| Building | API System |
|---|---|
| Reception desk | API gateway |
| Visitor badge | Trusted user headers |
| Office rooms | Services |
| Locked side doors | Private network |
Clients call only the gateway. The gateway performs shared checks and routes requests to private services.
What You Will Learn
In this lesson, you will learn:
- Why exposing services directly creates security risks.
- How a gateway routes requests.
- How a gateway performs authentication once.
- How a gateway adds and removes headers.
- How a gateway handles failures and rate limits.
A real gateway is usually its own application or service. In these examples, everything runs in a single program. The "services" are simple classes that the gateway calls directly. The concepts are exactly the same as a real distributed system.
Routing: Only the Gateway Is Public
The gateway maintains a route table. The route table determines which service should receive each request.
Program.cs — gateway route table
For example, /api/menu goes to the Menu Service, and /api/orders goes to the Order Service. If the gateway does not recognize a route, it returns: 404 Not Found
Check the Token Once
Now the gateway checks the bearer token for every request. The service has no token code at all.
Without a gateway, each service carries its own copy of the check, and one copy is missing. With a gateway, the check lives in one place.
Program.cs — check the token once
- No token: the gateway answers
401withWWW-Authenticate: Bearer. The order service never runs. - Token for customer 7: the gateway sets
X-User-Id: customer-7, and the service returns only order 101. - The last request is a trick. It has the token of customer 8 and it sends
X-User-Id: customer-7, hoping to read the orders of Asha. The gateway ignores the header of the client and sets its own, so the reply is order 102 of customer 8.
A service may trust X-User-Id only because nobody except the gateway can reach it. The gateway must always remove that header from the incoming request, and it must write its own value.
Header Transforms
Services often add headers for their own team: how long a query took, or which machine answered. Customers should not see these headers. The gateway is the right place to clean them up, and to add a request id that ties logs together.
Program.cs — add and strip headers
- Before (
/no-transforms/...): the reply leaksX-Internal-Cost: 3andX-Service-Host: orders-pod-2.internal. Now an attacker knows the names of your machines. - After (
/api/...): both internal headers are gone, and the gateway addsX-Request-Id: req-0001, and thenreq-0002. A real gateway uses a random id. This demo counts, so that the output never changes.
When a Service Fails, and When a Caller Is Greedy
The gateway sees every request, so it is also the place to protect the services. It limits how often each caller may call, and it gives a clear error when a service is down.
Program.cs — 502 and 429 at the gateway
- The key
app-iosgets two calls (the limit is2on purpose, so that you can see it trip). The third call gets429 Too Many RequestswithRetry-After: 60. - The payment service is down. The gateway catches the failure and returns
502 Bad Gatewayas Problem Details. The client gets a clean, standard error, not a crash or a hang.
Two rules for every gateway. First, put no business logic in it: it must not work out prices, totals or who owns an order. Those rules belong in the services. Second, services must not be reachable directly from the internet. If they are, attackers simply skip the gateway and all its checks.
A Real Gateway in .NET: YARP
In .NET, the common choice is YARP (Yet Another Reverse Proxy), a library from Microsoft. You list routes (which paths to match) and clusters (where the services live). This needs the Yarp.ReverseProxy NuGet package, so it is read-only here.
// Program.cs (read-only: needs the Yarp.ReverseProxy package)
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapReverseProxy();
app.Run();
{
"ReverseProxy": {
"Routes": {
"menu": { "ClusterId": "menu", "Match": { "Path": "/api/menu/{**rest}" } },
"orders": { "ClusterId": "orders", "AuthorizationPolicy": "default",
"Match": { "Path": "/api/orders/{**rest}" } }
},
"Clusters": {
"menu": { "Destinations": { "d1": { "Address": "http://menu-svc:8080/" } } },
"orders": { "Destinations": { "d1": { "Address": "http://orders-svc:8080/" } } }
}
}
}
Other well-known gateways are Azure API Management, AWS API Gateway, Kong and NGINX. They all do the same jobs that you just built by hand.
Where You See This
- Microservice apps put a gateway in front, so that the phone app needs only one address.
- Cloud platforms offer managed gateways (Azure API Management, AWS API Gateway) with keys, limits and logs built in.
- Kubernetes clusters use an ingress or a gateway to send outside traffic to the right pods.
- Public APIs, such as payment or maps APIs, check your key and rate limit you at their gateway, before any service runs.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Data leaks even though the gateway checks tokens | The service is also reachable directly | Remove its public address, and allow only the gateway |
| A user reads the orders of another user | The gateway copied X-User-Id from the client | Drop the header of the client, and set your own |
/api/ordersecret reaches the order service | The route matches with a plain StartsWith | Match the exact prefix, or the prefix plus / |
Clients see X-Service-Host | There is no header transform on the way out | Strip internal headers at the gateway |
| The gateway changes for every new feature | Business logic moved into the gateway | Keep the gateway to shared jobs only |
Exercises
What to Remember
- An API gateway is the single public front door for all your services.
- It does the shared jobs once: auth, rate limits, routing, header transforms, and clean errors.
- Services live on a private network, and they trust the
X-User-Idof the gateway. 502 Bad Gatewaywhen a service fails, and429 Too Many Requestswhen a caller is greedy.- Put no business logic in the gateway. In .NET, YARP gives you routes and clusters out of the box.
Next: GraphQL. You will let clients ask for exactly the fields that they need, in one request, from one endpoint.