Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

Microservices · Lesson 7

API Gateway Pattern

What an API Gateway Provides

An API gateway is the controlled entry point between external clients and internal services. It can route requests, enforce authentication, apply rate limits, and present a client-friendly API shape. It should coordinate edge concerns without becoming the place for every business rule.

Modeling a Route

A route maps a public path to a service target and can carry policy metadata. Keeping routing data explicit makes reviews and operational changes safer.

public record GatewayRoute(String publicPath, String serviceName, boolean requiresAuthentication) {
    public boolean accepts(String requestPath, boolean authenticated) {
        return requestPath.startsWith(publicPath)
                && (!requiresAuthentication || authenticated);
    }

    public static void main(String[] arguments) {
        GatewayRoute route = new GatewayRoute("/courses", "course-service", true);
        System.out.println(route.accepts("/courses/core-java", true));
    }
}

Gateway Responsibilities

ResponsibilityGateway fitExample
RoutingStrong/courses to course service
AuthenticationStrongVerify access token
Rate limitingStrongLimit public clients
Business workflowUsually noEnrollment rules belong in a service
Data ownershipNoServices own their data

Common Mistake and Practices

Common Mistake: Turning the gateway into a distributed monolith with database queries and business workflows. It becomes a bottleneck and makes independent service deployment meaningless.

  • Keep gateway policies focused.
  • Set upstream timeouts.
  • Return consistent edge errors.
  • Monitor route latency and failures.
  • Version routes deliberately.

Real-World Use Case

A gateway exposes one /api host for web and mobile clients, routing course reads and quiz requests to separate services. It enforces authentication and rate limits while each service owns its domain logic.

Quiz Check

Quick Knowledge Test

Loading quiz questions...