API Gateway — Explained with Examples
An API Gateway is a server that acts as a single entry point for client requests, routing them to appropriate microservices while handling cross-cutting concerns.
API Gateway sits between clients and backend services. Instead of clients calling multiple services directly, they send all requests to the gateway, which forwards them to the right destination.
Why You Need an API Gateway
In a microservices architecture, a client might need data from the user service, order service, and product service. Without a gateway, the client makes three calls. With a gateway, one call aggregates everything.
Client → API Gateway
├── /users → User Service
├── /orders → Order Service
├── /products → Product Service
└── /search → Search ServiceCommon Gateway Responsibilities
- Routing — forward requests to the correct service
- Authentication — validate JWT or API keys before forwarding
- Rate Limiting — prevent abuse by throttling requests
- Caching — return cached responses for repeated queries
- Logging — central request/response logging
- Transformation — convert protocols or data formats
Example: Express Gateway
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const gateway = express();
// Authentication middleware
gateway.use((req, res, next) => {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: 'Unauthorized' });
next();
});
// Route to microservices
gateway.use('/api/users', createProxyMiddleware({
target: 'http://user-service:3001',
changeOrigin: true
}));
gateway.use('/api/orders', createProxyMiddleware({
target: 'http://order-service:3002',
changeOrigin: true
}));
// Rate limiting
const rateLimit = require('express-rate-limit');
gateway.use('/api', rateLimit({
windowMs: 15 * 60 * 1000,
max: 100
}));
gateway.listen(8080);Real-World Analogy
An API Gateway is like a company receptionist. Instead of walking into random offices (microservices), every visitor (client) goes to the front desk. The receptionist checks their ID (authentication), directs them to the right department (routing), limits how many visitors can enter at once (rate limiting), and logs who came and went (logging).
Related Terms
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro