Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 51

Implementing an API Gateway with Spring Cloud Gateway

This lesson is built with resources from youtube.com, labs64.io and 1 more site.

Introduction

Welcome back! In our last session, we successfully refactored our monolith into two distinct microservices: auth-service and blog-service, running on ports 8081 and 8082, respectively. This was a crucial step towards building a scalable, distributed system.

However, this refactoring introduced a new challenge: a client application (like our Next.js frontend) now needs to know the address of every single microservice. This is brittle, complex to manage, and poses a security risk.

Today, we will solve this by introducing an API Gateway. This gateway will act as a single, unified entry point—a front door—for all incoming requests. Its job is to inspect each request and intelligently route it to the correct downstream service. We will use Spring Cloud Gateway to build this component, a modern, non-blocking gateway designed for exactly this purpose.

MERN Stack Comparison

In the Node.js world, you might achieve this using a reverse proxy like Nginx or by creating a dedicated "Backend for Frontend" (BFF) Express application. The BFF would receive all client requests and then make server-to-server calls to the appropriate microservices. Spring Cloud Gateway fulfills this same role, providing a robust, configurable, and highly-performant solution right within the Spring ecosystem.


Why Do We Need an API Gateway?

An API Gateway is a standard pattern in microservice architectures. It sits between your clients and your backend services, providing a single point of entry and control.

Spring Cloud Gateway Request Flow in Microservices
This diagram shows the core idea. All client requests go to the API Gateway, which then routes them to the appropriate microservice (Service 1, 2, or 3). It abstracts the complexity of the backend system from the client.

The primary benefits are:

  1. Single Entry Point: Clients only need to know one address—the gateway's. This simplifies client-side configuration and deployment.
  2. Routing: The gateway acts as a smart traffic controller, directing requests based on paths, headers, or other attributes.
  3. Centralized Cross-Cutting Concerns: Functionality like authentication, rate limiting, logging, and caching can be handled at the gateway level instead of being duplicated in every microservice. We'll explore these features in later lessons.

To get a solid conceptual overview, let's start with a short video.

Building an API Gateway in Java with Spring Cloud Gateway

This video, 'Building an API Gateway in Java with Spring Cloud Gateway' by Dan Vega, provides an excellent explanation of what an API Gateway is and what problems it solves in a distributed system.

Watch the first 6 minutes and 39 seconds (00:00:00 - 06:39). Pay close attention to the explanation of cross-cutting concerns and the diagram illustrating the request lifecycle within the gateway.


Core Concepts of Spring Cloud Gateway

Spring Cloud Gateway's functionality is built on three key concepts that you'll define in your configuration. Let's use the clear definitions from the "Spring Cloud Gateway Routing for Microservices" article.

Spring Cloud Gateway Routing for Microservices

To understand how we'll configure our gateway, let's read the 'Anatomy of a Gateway Route' section from this article on labs64.io. It clearly breaks down the components we'll be using.

Read the section titled 'Anatomy of a Gateway Route'. Focus on the definitions of id, uri, predicates, and filters.

In short:

  • Route: The main building block. It contains a destination (uri) and the conditions to get there.
  • Predicate: The condition itself. It's a rule that evaluates an incoming request (e.g., "does the path start with /api/auth/?"). If the predicate is true, the route is matched.
  • Filter: An action to modify the request or response. We'll explore these more in the next lesson.

Here's how they work together internally:

Spring Cloud Gateway Request Flow Diagram
This official diagram shows the internal flow. A request comes in, the `Gateway Handler Mapping` uses your configured **predicates** to find a matching **route**, and the request is then processed by a chain of **filters** before being sent to the proxy service's **URI**.

Your Task: Build and Configure the Gateway

Let's put theory into practice. We will create a new Spring Boot service for our gateway and configure it to route requests to our auth-service and blog-service.

1. Create the Gateway Project

First, we need a new project.

  1. Go to Spring Initializr.
  2. Create a new project with the following details:
    • Project: Maven
    • Group: com.blog (or your chosen group ID)
    • Artifact: gateway-service
    • Dependencies: Search for and add Gateway.
  3. Generate the project, download it, and open it in your IDE alongside your other two services.

2. Configure the Gateway

We'll use the declarative YAML configuration, which is the most common approach for defining static routes.

  1. Open the src/main/resources/application.yml file in your gateway-service project.
  2. First, let's set the port for the gateway itself. We'll use 8080, the default HTTP port.
    server:
      port: 8080
    
  3. Now, let's define the routes. We need to add a section for spring.cloud.gateway. We will create two routes, one for each of our downstream services.

Add the following configuration to your application.yml:

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      routes:
        - id: auth_service_route
          uri: http://localhost:8081
          predicates:
            - Path=/api/v1/auth/**

        - id: blog_service_route
          uri: http://localhost:8082
          predicates:
            - Path=/api/v1/posts/**

Let's break this down:

  • auth_service_route:
    • id: A unique name for this rule.
    • uri: The destination. We're pointing directly to our auth-service.
    • predicates: A list of conditions. Here, we use the Path predicate. It will match any request whose path starts with /api/v1/auth/.
  • blog_service_route:
    • Similarly, this rule matches any path starting with /api/v1/posts/ and forwards the request to our blog-service running on port 8082.

To see this configuration being built step-by-step, you can refer back to the Dan Vega video.

Building an API Gateway in Java with Spring Cloud Gateway

The following segment of the video demonstrates exactly what we just did: configuring routes in application.yml using id, uri, and Path predicates.

Watch from 09:23 to 15:30. The video creates a route for a 'posts' service. Notice how the structure matches what we've just implemented for our auth-service and blog-service.


Running and Verifying the Full System

Now for the moment of truth. Let's run all three of our services:

  1. auth-service (on port 8081)
  2. blog-service (on port 8082)
  3. gateway-service (on port 8080)

Once all three are running, open Postman. All your requests should now be directed to the gateway on port 8080.

  1. Test the Auth Route: Send a POST request to http://localhost:8080/api/v1/auth/register with a new user's JSON body.

    • Expected Result: You should get a 201 Created response. The gateway should have forwarded your request to the auth-service, which processed it. You can verify this by checking the users table in your blog_auth_db.
  2. Test the Blog Route: Send a POST request to http://localhost:8080/api/v1/posts with a JSON body to create a new post (remember you'll need the authorId field).

    • Expected Result: You should get a 201 Created response. The gateway forwarded this request to the blog-service. Verify by checking the posts table in your blog_content_db.

If both requests succeed, your gateway is working perfectly!


Debugging Task

You are testing your new setup. A request to POST http://localhost:8080/api/v1/auth/login returns a 404 Not Found from the gateway. However, if you bypass the gateway and send the same request directly to POST http://localhost:8081/api/v1/auth/login, it works correctly and returns a JWT.

Question: Based on our configuration, what is the most likely cause of this 404 error at the gateway level? How would you diagnose and fix it?

Click for the answer The most likely cause is a misconfiguration in the `Path` predicate for the `auth_service_route` in the gateway's `application.yml`.

Diagnosis: The gateway returns 404 because no route predicate matched the incoming request path /api/v1/auth/login.

Common Mistakes:

  1. Typo in the pattern: The predicate might be Path=/api/v1/authentication/** instead of Path=/api/v1/auth/**.
  2. Incorrect wildcard: Using a single asterisk (*) instead of a double asterisk (**). A path like /api/v1/auth/* would match /api/v1/auth/login but not /api/v1/auth/some/other/path. The double asterisk ** matches any number of path segments.
  3. Missing a path segment: The predicate might be Path=/api/auth/**, missing the /v1/ segment.

Fix: You would carefully inspect the Path predicate for the auth_service_route in your application.yml and ensure it exactly matches the path pattern of your incoming requests, which is Path=/api/v1/auth/**.


Conclusion

Excellent work! You have now set up the front door to your entire microservices architecture. You created a Spring Cloud Gateway service and configured it with declarative routes that direct traffic to the correct downstream services based on URL paths. This abstracts the internal complexity of our system from the outside world.

Key Takeaways:

  • An API Gateway is a crucial component in a microservices architecture that acts as a single entry point.
  • Spring Cloud Gateway allows you to define routing rules declaratively in application.yml.
  • A Route consists of a destination uri and predicates (conditions) that must be met for the route to be activated.
  • The Path predicate is a powerful tool for routing requests based on their URL.

Preview of the Next Lesson:
Our current routing is a direct 1-to-1 proxy, which means our client-facing URLs still contain internal details like /api/v1/. In the next lesson, we will make our gateway even smarter by using Gateway Filters. We'll learn to configure routing rules that not only match paths but also modify them, allowing us to create cleaner, more user-friendly public URLs (e.g., /auth/login) that map to our internal service endpoints.