Skip to main content

Welcome to a Grasp lesson

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

Lesson 52

URL-Based Routing in API Gateway

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

Introduction

Welcome back! In our previous lesson, we set up our API Gateway as the single entry point for our microservices. We configured it to proxy requests based on their paths, for example, forwarding http://localhost:8080/api/v1/auth/register to the auth-service on port 8081.

This works, but it has a design flaw: our public-facing URLs expose internal details like the API version (/v1/). A core principle of the API Gateway pattern is to provide a stable, clean interface to clients, abstracting away the underlying implementation details of your microservices. If we decide to release v2 of our auth API, the client shouldn't have to change its request URLs.

Today, we'll evolve our routing configuration to address this. You will learn how to use Gateway Filters to modify requests on the fly, allowing us to define clean public URLs (like /auth/register) that map to our versioned internal service endpoints. We will also explore an alternative, programmatic way to define routes using Java and learn how to inspect our gateway's configuration at runtime for easier debugging.


1. Decoupling Public and Private URLs with Filters

In Spring Cloud Gateway, a Filter allows you to intercept and modify the HTTP request or response. Filters are applied to routes and run in a chain. This concept is very similar to middleware in Node.js frameworks like Express.js, where you can define functions that process the request object before it reaches the final route handler.

We will use a specific filter, RewritePath, to transform the incoming request path before it's sent to the downstream service.

MERN Stack Comparison

In Express.js, you might write custom middleware to achieve this:

app.use('/auth', (req, res, next) => {
  // e.g., req.url is '/register'
  req.url = '/api/v1/auth' + req.url; // now it's '/api/v1/auth/register'
  // Hand off to another router or reverse proxy
  next();
});

The RewritePath Gateway Filter provides a declarative, out-of-the-box way to do the same thing.

Your Task: Update the Gateway Configuration

Let's modify our gateway-service/src/main/resources/application.yml file to use RewritePath.

  1. Change the Path Predicates: Update the Path predicates to match the clean, public URLs we want to expose.
  2. Add the Filter: Add a filters section to each route definition and use the RewritePath filter.

Your updated application.yml should look like this:

server:
  port: 8080

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      routes:
        - id: auth_service_route
          uri: http://localhost:8081
          predicates:
            - Path=/auth/**
          filters:
            - RewritePath=/auth/(?<segment>.*), /api/v1/auth/$\{segment}

        - id: blog_service_route
          uri: http://localhost:8082
          predicates:
            - Path=/posts/**
          filters:
            - RewritePath=/posts/(?<segment>.*), /api/v1/posts/$\{segment}

Let's break down the RewritePath filter:
RewritePath=/auth/(?<segment>.*), /api/v1/auth/$\{segment}

  • This filter takes two arguments, separated by a comma.
  • Argument 1 (Regex): /auth/(?<segment>.*) is a regular expression.
    • It matches the incoming path, which starts with /auth/.
    • (?<segment>.*) is a named capture group. It captures everything after /auth/ and names it segment.
  • Argument 2 (Replacement): /api/v1/auth/$\{segment} is the replacement string.
    • It constructs the new path that will be sent to the downstream service.
    • $\{segment} is a placeholder that gets replaced by the value captured by our named group.

Example Flow:

  1. Client sends POST /auth/register to the gateway (http://localhost:8080).
  2. The auth_service_route is matched because the path starts with /auth/.
  3. The RewritePath filter is applied.
    • The regex matches /auth/register.
    • The segment capture group contains register.
  4. The path is rewritten to /api/v1/auth/register.
  5. The gateway sends the request with the new path to http://localhost:8081/api/v1/auth/register.

Verify your changes:

  1. Restart the gateway-service.
  2. In Postman, send a POST request to the new, cleaner URL: http://localhost:8080/auth/register.
  3. Send another POST request to http://localhost:8080/posts to create a post.
  4. Both requests should succeed. The old URLs with /api/v1 will now result in a 404 Not Found at the gateway, as no predicate matches them anymore.

2. Alternative: Programmatic Route Configuration

While YAML configuration is great for static routes, sometimes you need to define routes programmatically. This is useful for dynamic scenarios, like loading route definitions from a database or implementing more complex logic. Spring Cloud Gateway allows this by defining a RouteLocator bean.

Let's implement the exact same routing logic using Java.

  1. Create a new package com.blog.gatewayservice.config.
  2. Inside, create a new class GatewayConfig.
package com.blog.gatewayservice.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("auth_service_route_java", r -> r.path("/auth/**")
                        .filters(f -> f.rewritePath("/auth/(?<segment>.*)", "/api/v1/auth/${segment}"))
                        .uri("http://localhost:8081"))
                
                .route("blog_service_route_java", r -> r.path("/posts/**")
                        .filters(f -> f.rewritePath("/posts/(?<segment>.*)", "/api/v1/posts/${segment}"))
                        .uri("http://localhost:8082"))
                
                .build();
    }
}

This code defines a bean that uses a fluent API to build routes. Each route() call defines one route with its ID, predicate (path), filters (rewritePath), and destination URI. It's the programmatic equivalent of our YAML configuration.

To activate this configuration:

  1. Comment out the entire routes block in your application.yml.
    
    
    
    # spring:
    #   cloud:
    #     gateway:
    #       routes:
    #         - id: ...
    
  2. Restart the gateway-service.
  3. Test the same endpoints in Postman (http://localhost:8080/auth/register, etc.). They should still work exactly as before, proving that the Java configuration is now active.

The following video demonstrates both YAML configuration (with a simpler PrefixPath filter) and the Java fluent API.

Building an API Gateway in Java with Spring Cloud Gateway

This video from Dan Vega, 'Building an API Gateway in Java with Spring Cloud Gateway', demonstrates the concepts we've just implemented. He uses PrefixPath in YAML and then shows how to define the same routes programmatically.

First, watch from 09:14 to 13:31 to see how he uses a PrefixPath filter in YAML, which is a simpler alternative to RewritePath. Then, watch from 18:01 to 19:44 to see him implement the routes using the Java fluent API, just as we did.


3. Runtime Inspection with Spring Boot Actuator

How can you be sure which routes are active in your gateway at any given time? This is crucial for debugging. Spring Boot Actuator provides endpoints to monitor and interact with your application. For the gateway, it provides a /gateway endpoint.

Your Task: Enable and Use the Gateway Actuator

  1. Add the Dependency: Make sure you have the actuator dependency in your gateway-service/pom.xml. If not, add it:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    

    Your IDE should prompt you to reload your Maven project.

  2. Expose the Endpoint: By default, actuator endpoints are not exposed over HTTP for security reasons. Let's expose the gateway and health endpoints in application.yml.

    management:
      endpoints:
        web:
          exposure:
            include: gateway,health
      endpoint:
        gateway:
          enabled: true
    

    Make sure this management block is at the root level of your YAML, not nested under spring.

  3. Inspect the Routes: Restart your gateway-service. Now, open your browser or Postman and make a GET request to http://localhost:8080/actuator/gateway/routes.

You'll see a JSON response listing all active routes. You can see the route ID, the predicate, the filters applied, and the destination URI.

Experiment:

  • With the Java config active, observe the route IDs (auth_service_route_java, etc.).
  • Now, comment out the @Bean in GatewayConfig.java and uncomment the routes block in application.yml.
  • Restart the service and hit the actuator endpoint again. You will see the routes from your YAML file are now active (auth_service_route).

This is an invaluable tool for debugging your gateway's behavior in a live environment.

Actuator API :: Spring Cloud Gateway

For more details on the power of the gateway actuator, you can refer to the official Spring Cloud Gateway documentation.

Quickly read the first section to understand how to enable the endpoint, and the section titled 'Retrieving the Routes Defined in the Gateway' to see the structure of the JSON response you just observed.


Debugging Task

You are helping a new team member who has added a route for a new notifications-service running on port 8083. They used the Java RouteLocator bean to add the route.

// In GatewayConfig.java
.route("notifications_route", r -> r.path("/notifications/**")
    .filters(f -> f.rewritePath("/notifications/(?<segment>.*)", "/api/v1/notify/${segment}"))
    .uri("http://localhost:8083"))

They send a POST request to http://localhost:8080/notifications/email, but the gateway returns a 404 Not Found. They are confused because:

  1. The notifications-service works perfectly when they call http://localhost:8083/api/v1/notify/email directly.
  2. The GET /actuator/gateway/routes endpoint shows their notifications_route is active and correctly configured.

Question: What is the most likely cause of this 404 error, even though the actuator shows the route is loaded correctly?

Click for the answer

The most likely cause is a typo in the replacement string of the RewritePath filter.

The incorrect filter:
.filters(f -> f.rewritePath("/notifications/(?<segment>.*)", "/api/v1/notify/${segment}"))

The downstream service expects:
/api/v1/notify/email

The filter is actually generating:
/api/v1/notify/email -- Wait, the problem description has the correct replacement string. Let me re-think the scenario for a better debugging puzzle. A typo is too simple.

Let's craft a better puzzle. The downstream service endpoint is /api/v1/notifications/email. The developer configured the rewrite as /api/v1/notify/email.

New Answer:
The most likely cause is a mismatch between the path the gateway is rewriting to and the actual path the notifications-service expects.

The developer's filter:
.filters(f -> f.rewritePath("/notifications/(?<segment>.*)", "/api/v1/notify/${segment}"))

This filter rewrites a request for /notifications/email to /api/v1/notify/email.

The problem: The downstream notifications-service does not have an endpoint at /api/v1/notify/email. Its actual endpoint is likely at /api/v1/notifications/email. The developer made a typo (notify instead of notifications) in the replacement part of the filter.

Why this is a tricky bug: The actuator correctly shows the route is loaded with its predicate and filter as configured. The actuator doesn't validate if the rewritten path will actually match an endpoint on the downstream service. The gateway successfully forwards the request to http://localhost:8083/api/v1/notify/email, but the notifications-service itself returns a 404 because it has no handler for that specific path. The gateway then bubbles this 404 up to the client. This highlights that you must debug the entire request chain, not just the gateway's configuration.


Conclusion

Fantastic work! You have significantly improved the design of our API Gateway. You've moved beyond simple proxying to create a clean, stable public API that decouples clients from the implementation details of our backend services.

Key Takeaways:

  • Gateway Filters (like RewritePath) are powerful tools for modifying requests and responses, similar to middleware in Node.js.
  • You can decouple public URLs from internal service URLs, which is a key responsibility of an API Gateway.
  • Routes can be configured both declaratively in application.yml (for static routes) and programmatically via a RouteLocator bean (for dynamic or complex routes).
  • The Spring Boot Actuator gateway endpoint (/actuator/gateway/routes) is an essential tool for inspecting and debugging your gateway's configuration at runtime.

Preview of the Next Lesson:
So far, our services are independent islands. The gateway routes traffic to them, but they don't talk to each other. In a real microservices system, services often need to collaborate. In our next lesson, we will tackle a fundamental challenge: inter-service communication. You will learn how the blog-service can securely communicate with the auth-service to validate a user's identity before allowing them to create a post.