CodeBlanks Logo Icon CodeBlanks

API gateway

Learn the API gateway pattern.

API gateway

An API gateway is a single entry point that receives client requests and routes them to the appropriate services. The client connects only to the gateway; the gateway calls the back-end services. This means clients do not need to know how many services exist.

Example: the client sends a GET /api/users/1 request to the gateway. The gateway routes this request to the user service. The gateway can also handle authentication, rate limiting and response aggregation. Advantages: a single entry point, central handling of common tasks, client-service decoupling. Disadvantages: an extra network hop, the gateway must be highly available. An API gateway is almost inseparable from microservice systems.

Routing with a gateway

The gateway dispatches requests to services based on the URL path. For example /api/users/* goes to the user service and /api/orders/* goes to the order service. In Express you do this with app.use.

Example: app.use("/api/users", userRouter); app.use("/api/orders", orderRouter);. All requests starting with /api/users go to userRouter. The gateway holds a router per service. The router receives the request and forwards it to the relevant service (usually with fetch). This structure lets the client connect to a single address (the gateway). When service locations change, only the gateway's routing table is updated; the client is unaffected.

Practice Write an API gateway skeleton

Import the express module and create app. Define gateway routing with app.use("/api/users", (req, res) => res.json({ kaynak: "user-service" })). Print "Gateway ready" with console.log.

Starter code

index.js
// Import express and create app
// write here

// Route "/api/users" to user-service
// write here

// Print "Gateway ready"
// write here

Sample solution

index.js
const express = require("express");
const app = express();
app.use("/api/users", (req, res) => res.json({ kaynak: "user-service" }));
console.log("Gateway ready");

Expected output

Gateway ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match each concept to its role

Term Meaning
API gateway Single entry point
user-service Holds user data
rate limit Limits request count
routing Forwards request to service

2 Which path does the gateway route to the user service?

index.js
app.use("/api/users", userRouter)
  • /api/orders
  • /api/payments
  • /api/health
  • /api/users Correct answer

Explanation: /api/users goes to userRouter.

3 Complete the app.use call

Question
app.use("/api/users", ____);
Answer
app.use("/api/users", userRouter);

Explanation: Routing is done with userRouter.

All lessons in Advanced