API Gateway for Swift Services: How to Unite Microservices into a Single System

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

API Gateway for Swift Services: Building a Bridge Between Microservices

\n\n

Imagine your backend is a huge shopping mall. Inside — dozens of stores (microservices): authorization, product catalog, cart, payments, notifications. The client (iOS app) needs to enter each store separately — this is chaos, slow, and insecure. API Gateway is the main entrance, security, and navigator all in one. It receives requests, checks passes, redirects to the right department, and returns the result.

\n\n

In the Swift world, where Vapor and Hummingbird are gaining momentum, creating your own API Gateway is not a luxury but a necessity for scalable projects. Today we will break down how to write a lightweight gateway in Swift that unites your services into a single ecosystem.

\n\n

Why Do You Need an API Gateway in Swift Architecture?

\n\n

When you have 2-3 microservices, the client can communicate with each directly. But when there are 10+ (a typical scenario for fintech, e-commerce, or SaaS), problems arise:

\n\n
    \n
  • Bloated client code — each service has its own endpoint, error format, authentication protocol
  • \n
  • Vulnerabilities — each service has to handle CORS, rate limiting, JWT verification itself
  • \n
  • Refactoring complexity — renamed a service? Change the code on all clients
  • \n
  • Extra traffic — the client makes 5 requests instead of one to assemble a page
  • \n
\n\n

API Gateway solves these problems by becoming a single entry point. It can aggregate data from multiple microservices into one response, apply security policies, and log all requests. For Swift developers, this is also an opportunity to use the language's strict typing at the gateway level.

\n\n

Choosing the Tool: Vapor + Hummingbird

\n\n

For creating an API Gateway in Swift, Vapor is ideal — the most mature web framework in the ecosystem. It provides middleware, routing, client requests (via Client), and async/await support. An alternative is Hummingbird (lightweight, fast, from Apple), but for the example we'll use Vapor as it's better documented.

\n\n

Our gateway will perform three functions:

\n
    \n
  • Proxying requests to the required microservice
  • \n
  • Authentication via JWT
  • \n
  • Aggregating data from two services into one response
  • \n
\n\n

Step 1. Basic Project Structure

\n\n

Create a new Vapor project:

\n
vapor new APIGateway --template=api\ncd APIGateway
\n\n

Add the JWT dependency to Package.swift:

\n
.package(url: "https://github.com/vapor/jwt.git", from: "4.0.0")
\n\n

And include it in the target:

\n
.target(name: "App", dependencies: [\n    .product(name: "Vapor", package: "vapor"),\n    .product(name: "JWT", package: "jwt")\n])
\n\n

Step 2. Middleware for Authentication

\n\n

Create a middleware that checks the JWT token and passes user information further. This is a classic pattern for an API Gateway in Swift:

\n\n
import Vapor\nimport JWT\n\nstruct JWTAuthenticator: AsyncMiddleware {\n    func respond(to request: Request, chainingTo next: AsyncResponder) async throws -> Response {\n        guard let token = request.headers.bearerAuthorization?.token else {\n            throw Abort(.unauthorized, reason: "Missing Bearer token")\n        }\n        \n        // Verify signature and expiration\n        let payload = try await request.jwt.verify(token, as: UserPayload.self)\n        \n        // Store user in request storage\n        request.storage.set(UserPayloadKey.self, to: payload)\n        \n        return try await next.respond(to: request)\n    }\n}\n\nstruct UserPayload: JWTPayload {\n    var userID: UUID\n    var role: String\n    var exp: ExpirationClaim\n    \n    func verify(using signer: JWTSigner) throws {\n                

Blogs

Book Recommendations