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.
- Change the Path Predicates: Update the
Pathpredicates to match the clean, public URLs we want to expose. - Add the Filter: Add a
filterssection to each route definition and use theRewritePathfilter.
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 itsegment.
- It matches the incoming path, which starts with
- 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:
- Client sends
POST /auth/registerto the gateway (http://localhost:8080). - The
auth_service_routeis matched because the path starts with/auth/. - The
RewritePathfilter is applied.- The regex matches
/auth/register. - The
segmentcapture group containsregister.
- The regex matches
- The path is rewritten to
/api/v1/auth/register. - The gateway sends the request with the new path to
http://localhost:8081/api/v1/auth/register.
Verify your changes:
- Restart the
gateway-service. - In Postman, send a
POSTrequest to the new, cleaner URL:http://localhost:8080/auth/register. - Send another
POSTrequest tohttp://localhost:8080/poststo create a post. - Both requests should succeed. The old URLs with
/api/v1will now result in a404 Not Foundat 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.
- Create a new package
com.blog.gatewayservice.config. - 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:
- Comment out the entire
routesblock in yourapplication.yml.# spring: # cloud: # gateway: # routes: # - id: ... - Restart the
gateway-service. - 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
-
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.
-
Expose the Endpoint: By default, actuator endpoints are not exposed over HTTP for security reasons. Let's expose the
gatewayandhealthendpoints inapplication.yml.management: endpoints: web: exposure: include: gateway,health endpoint: gateway: enabled: trueMake sure this
managementblock is at the root level of your YAML, not nested underspring. -
Inspect the Routes: Restart your
gateway-service. Now, open your browser or Postman and make aGETrequest tohttp://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
@BeaninGatewayConfig.javaand uncomment theroutesblock inapplication.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:
- The
notifications-serviceworks perfectly when they callhttp://localhost:8083/api/v1/notify/emaildirectly. - The
GET /actuator/gateway/routesendpoint shows theirnotifications_routeis 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 aRouteLocatorbean (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.