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 OK is 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, and 502 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:

BuildingAPI System
Reception deskAPI gateway
Visitor badgeTrusted user headers
Office roomsServices
Locked side doorsPrivate 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:

  1. Why exposing services directly creates security risks.
  2. How a gateway routes requests.
  3. How a gateway performs authentication once.
  4. How a gateway adds and removes headers.
  5. 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 401 with WWW-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 leaks X-Internal-Cost: 3 and X-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 adds X-Request-Id: req-0001, and then req-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-ios gets two calls (the limit is 2 on purpose, so that you can see it trip). The third call gets 429 Too Many Requests with Retry-After: 60.
  • The payment service is down. The gateway catches the failure and returns 502 Bad Gateway as 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

SymptomCauseFix
Data leaks even though the gateway checks tokensThe service is also reachable directlyRemove its public address, and allow only the gateway
A user reads the orders of another userThe gateway copied X-User-Id from the clientDrop the header of the client, and set your own
/api/ordersecret reaches the order serviceThe route matches with a plain StartsWithMatch the exact prefix, or the prefix plus /
Clients see X-Service-HostThere is no header transform on the way outStrip internal headers at the gateway
The gateway changes for every new featureBusiness logic moved into the gatewayKeep 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-Id of the gateway.
  • 502 Bad Gateway when a service fails, and 429 Too Many Requests when 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.