Home Java javaTutorial Building a Simple API Gateway with Spring Cloud Gateway

Building a Simple API Gateway with Spring Cloud Gateway

Nov 03, 2024 pm 12:14 PM

In modern microservices architectures, an API Gateway is essential. It provides a single entry point for multiple services, allowing us to manage routing, security, rate limiting, load balancing, and more. In this article, we’ll explore how to set up a basic API Gateway using Spring Cloud Gateway and direct requests to different endpoints based on paths. We'll also demonstrate how to use filters to manipulate paths dynamically.

Let’s dive into the code!

Building a Simple API Gateway with Spring Cloud Gateway

Oh no !!

Prerequisites

To follow along, you’ll need:

  • Java 11 or higher
  • Spring Boot (3.0 or later recommended)
  • Reactive Spring Cloud Gateway

Project Setup

Create a new Spring Boot project and include the Spring Cloud Gateway dependency. You can do this easily by setting up a new project on Spring Initializr, selecting Spring Boot and Reactive Spring Cloud Gateway under dependencies.

Here's the pom.xml snippet:

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
Copy after login
Copy after login

Building the API Gateway

Let’s configure our Gateway to handle requests for three different paths:

  1. /get/country/{name} – To fetch details about a country.
  2. /get/language/{name} – To get information based on language.
  3. /get/subregion/{name} – To retrieve data for specific subregions.

"We’ll use the REST Countries API to simulate the other microservices we have in our architecture."


Setting Up the Routes

I've created a folder called router near the application's main file. Inside it, we’ll create a file called Routes.java where we define our routes, configure each path, and apply filters to dynamically direct requests.

package dev.mspilari.api_gateway.router;

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 Routes {

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("country_route", p -> p
                        .path("/get/country/{name}")
                        .filters(f -> f.setPath("/v3.1/name/{name}"))
                        .uri("https://restcountries.com"))

                .route("language_route", p -> p
                        .path("/get/language/{name}")
                        .filters(f -> f.setPath("/v3.1/lang/{name}"))
                        .uri("https://restcountries.com"))

                .route("subregion_route", p -> p
                        .path("/get/subregion/{name}")
                        .filters(f -> f.setPath("/v3.1/subregion/{name}"))
                        .uri("https://restcountries.com"))
                .build();
    }
}
Copy after login
Copy after login

Explanation of the Code

  • Route Definitions: we define each route using the route method, which takes an identifier (e.g., country_route) and a lambda that defines the path.

  • Path Matching: .path("/get/country/{name}") is used to match the incoming URL pattern. {name} is a variable that can be dynamically replaced by any value, such as a country name like “Brazil”.

  • Filters: we use SetPath to modify the outgoing request path. For example, .setPath("/v3.1/name/{name}") rewrites /get/country/{name} to /v3.1/name/{name}, the endpoint required by the REST Countries API.

  • URI: we set the uri to https://restcountries.com, which serves as the base URL. Spring Cloud Gateway will send the modified path to this URI.


Running the Gateway

Start your Spring Boot application. Now, you can make requests to the Gateway, and it will forward them to the correct endpoint.

Try the following commands in your terminal to test the routes:

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-contract-stub-runner</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
Copy after login
Copy after login

Each request will be routed by the Gateway to the respective REST Countries API endpoint, based on the path and parameter.


Verifying the Response

If everything is configured correctly, you should see responses that match what you'd get from directly calling the REST Countries API.

For example:

package dev.mspilari.api_gateway.router;

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 Routes {

    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("country_route", p -> p
                        .path("/get/country/{name}")
                        .filters(f -> f.setPath("/v3.1/name/{name}"))
                        .uri("https://restcountries.com"))

                .route("language_route", p -> p
                        .path("/get/language/{name}")
                        .filters(f -> f.setPath("/v3.1/lang/{name}"))
                        .uri("https://restcountries.com"))

                .route("subregion_route", p -> p
                        .path("/get/subregion/{name}")
                        .filters(f -> f.setPath("/v3.1/subregion/{name}"))
                        .uri("https://restcountries.com"))
                .build();
    }
}
Copy after login
Copy after login

Benefits of Using Spring Cloud Gateway

  1. Single Entry Point: all requests pass through the Gateway, simplifying client interactions and API management.
  2. Flexible Routing: Routes can be easily customized with path parameters and filters.
  3. Dynamic Path Rewriting: The Gateway allows us to adjust request paths dynamically, making it easy to integrate with external APIs without changing the client-side code.

Next Steps

This setup covers the basics of routing with Spring Cloud Gateway. In the next posts, we'll explore additional features, like:

  • Authentication and Authorization – secure routes by integrating with OAuth or JWT.
  • Rate Limiting and Circuit Breakers – add resilience with built-in filters.
  • Load Balancing – distribute requests across multiple instances for better performance.
  • Logging and Observability – gain insights into application behavior and performance, and monitor traffic patterns through distributed tracing and centralized logging.

? Reference

  • Spring Cloud Gateway
  • Building a gateway

? Talk to me

  • LinkedIn
  • Github
  • Portfolio

The above is the detailed content of Building a Simple API Gateway with Spring Cloud Gateway. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles