The Wayback Machine - https://web.archive.org/web/20240916045703/https://www.geeksforgeeks.org/java-spring-boot-microservices-develop-api-gateway-using-spring-cloud-gateway/
Open In App

Java Spring Boot Microservices – Develop API Gateway Using Spring Cloud Gateway

Last Updated : 01 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix is the most famous example of an API gateway. To know more about API Gateway refer to this article What is API Gateway Pattern?

Why Implement API Gateway in Microservices?

An API gateway simplifies the communication between a client and a service, whether that be between a user’s web browser and a server, or between a frontend application and the backend application that it relies on. The main purpose of integrating the API gateway in microservice communication is, API Gateway acts as a single entry point to access services. We will see the whole implementation in the example below. As of now please refer to the below image to get an idea of how the API gateway works.

API-Gateway-in-Microservices

What is Spring Cloud Gateway?

Spring Cloud Gateway provides a library for making API gateways on top of Spring and Java. It provides a flexible way of routing requests based on a number of criteria, as well as focuses on cross-cutting problems like security, resiliency, and monitoring. Some of the important features of Spring Cloud Gateway are:

  • It is Built on Spring Framework 5, Project Reactor, and Spring Boot 2.0
  • You can integrate Circuit Breaker with Spring Cloud Gateway
  • You can integrate Spring Cloud DiscoveryClient
  • Predicates and filters are specific to routes
  • Path Rewriting
  • It is able to match routes on any request attribute, etc.

Note: Please refer to this article to know more about Spring Cloud Gateway.

How to Include Spring Cloud Gateway:

For Maven:

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

For Gradle:

implementation("org.springframework.cloud:spring-cloud-starter-gateway")

Note: If you include the starter, but you do not want the gateway to be enabled, set

spring.cloud.gateway.enabled=false

Developing API Gateway Using Spring Cloud Gateway

Step 1: Create a New Spring Boot Project in Spring Initializr

To create a new Spring Boot project, please refer to How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA. For this project choose the following things

  • Project: Maven
  • Language: Java
  • Packaging: Jar
  • Java: 17

 Please choose the following dependencies while creating the project.

  • Gateway (SPRING CLOUD ROUTING)

Refer to the below image

Below is the complete pom.xml file. Please cross-verify if you have missed some dependencies

XML




<?xml version="1.0" encoding="UTF-8"?>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.1.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gfg</groupId>
    <artifactId>spring-cloud-gateway</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Spring Cloud Gateway</name>
    <description>Spring Cloud Gateway</description>
    <properties>
        <java.version>17</java.version>
        <spring-cloud.version>2022.0.3</spring-cloud.version>
    </properties>
    <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>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
  
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  
</project>


Step 2: Make Changes in Your application.yaml file

Now make the following changes in your application.yaml file.

server:
port: 8085
spring:
application:
name: API-GATEWAY-SERVICE
cloud:
gateway:
routes:
- id: DEMO-SERVICE
uri: http://localhost:9090
predicates:
- Path=/demo/**

Here,

  • id: You can give any id as of now.
  • uri: Here you have to provide the port in which your microservice is running
  • predicates (- Path): Here we have provided the path “/demo/**”, which means any request starting with path “/demo/**” rout it to DEMO-SERVICE.

Step 3: Develop the DEMO-SERVICE

To create a new service, please refer to How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA. For this project choose the following things

  • Project: Maven
  • Language: Java
  • Packaging: Jar
  • Java: 17

 Please choose the following dependencies while creating the project.

  • Spring Web

In this MIcrosevice we have created a simple REST API in our controller class.

Java




package com.gfg.demo.controller;
  
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
  
@RestController
@RequestMapping("/demo")
public class DemoController {
  
    @GetMapping("/gfg")
    public ResponseEntity<String> getAnonymous() {
        return ResponseEntity.ok("Welcome to GeeksforGeeks");
    }
  
}


Now make the following changes in your application.properties file.

server.port=9090

Now run your application and test it out.

Step 4: Testing in Postman

Now let’s test our API. Hit the following URL

http://localhost:9090/demo/gfg

And you are going to get a response like this

Now we can get the same response by using our API gateway port which is 8085. Now hit the following URL

http://localhost:8085/demo/gfg

And you are going to get a response like this

So this is how the API gateway works. If you have hundreds of microservices then you don’t need to remember the port of all microservices. You can just configure them in your API Gateway and you can access all your API by using only one port.



Similar Reads

Java Spring Boot Microservices – Integration of Eureka and Spring Cloud Gateway
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
5 min read
API Composition and Aggregation with Spring Cloud Gateway in Java Microservices
API Composition and Aggregation is the critical pattern in the microservices architecture. It can enable combining the data from multiple microservices into a single response which is essential for reducing the number of client-side requests and improving the overall efficiency of the data retrieval. This article will guide you to demonstrate how t
9 min read
Java Spring Boot Microservices - Integration of Eureka, Feign & Spring Cloud Load Balancer
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
13 min read
Java Spring Boot Microservices - Client Side Load Balancing with Spring Cloud LoadBalancer
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices. Basically, there are two ways to load balanc
12 min read
API Gateway Security Best Practices in Java Microservices
An API Gateway acts as a front-end for receiving API requests, enforcing throttling and security policies, passing requests to the back-end service, and then passing the response back to the requester. It sits between external clients and microservices, providing a unified entry point for multiple services. Security Best PracticesBelow are the diff
4 min read
API Gateway Authentication and Authorization in Spring Boot
In modern web applications, securing the communication between the clients and backend services is crucial. The API Gateway can serves as the reverse proxy and managing the client requests, and routing them to the appropriate the backend services. It enhance the security, we can implement the authentication and authorization mechanisms using the JS
12 min read
Implementing CORS Handling in Spring Boot API Gateway
Cross-Origin Resource Sharing (CORS) is a mechanism that allows resources on a web server to be requested from a domain other than the one from which the resource originated. In a microservices architecture using Spring Boot API Gateway, handling CORS is essential to ensure that client applications can interact with services behind the gateway with
6 min read
Routing and Request Transformation in API Gateways in Spring Cloud Microservices
API gateways play a crucial role in modern microservices architectures by serving as the centralized entry point for client requests. They can handle the routing requests to the appropriate microservices and it can often involve the request transformation to adapt the client requests to the specific requirements of downstream services. In this arti
10 min read
Spring Boot – Using Spring Boot with Apache Camel
Apache Camel and Spring Boot are two powerful frameworks that can be seamlessly integrated to build robust, scalable, and efficient applications. Apache Camel is an open-source integration framework that provides an extensive range of components and connectors, enabling developers to integrate different systems, APIs, and applications. It simplifie
5 min read
Spring Cloud Gateway with Spring WebFlux
Spring Cloud Gateway is the library that allows you to build API gateways on top of Spring WebFlux. It provides a simple and effective way to route requests, apply filters, and manage cross-cutting concerns reactively. This article will guide you through demonstrating how to set up Spring Cloud Gateway with a simple microservice and route requests
5 min read
Java Spring Boot Microservices Sample Project
Microservices are more popular nowadays. They can be written in any language. In this article, let us see Spring Boot Microservices. in this article let us see a base project "currency-exchange-sample-service" which has a business logic and which can be invoked in another project "currency-conversion-sample-service". Both are Maven projects and let
9 min read
Java Spring Boot Microservices - Developing Service Discovery
In Microservices, Service Discovery helps us by providing a database of available service instances so that services can be discovered, registered, and de-registered based on usage. For a detailed explanation of Service Discovery please refer to this article Service Discovery and Service Registry in Microservices. In this article, we are going to d
3 min read
Best Way to Master Java Spring Boot Microservices – A Complete Roadmap
The World is Moving Towards Microservices Architecture. Yes, it's true but why? Microservices are becoming more popular day by day. To know Why the World is Moving Towards Microservices Architecture you must refer to this article. This will give you a complete idea of why big organizations like Google, Meta, Twitter, etc. are using Microservices no
6 min read
Java Spring Boot Microservices Example - Step by Step Guide
Microservices is an architectural approach to build a collection of logic, data layers, and loosely coupled applications. Every microservices deals with one business function end-to-end independently from other microservices. Microservices present simple and understandable APIs to communicate with each other through lightweight common protocols suc
6 min read
Spring Boot Microservices Communication using FeignClient with Example
FeignClient also known as Spring Cloud OpenFeign is a Declarative REST Client in Spring Boot Web Application. But what do you mean by Declarative REST Client? It means we need to specify the client specification as an Interface and Spring Boot will take care of the implementation for us. Writing web services with the help of FeignClient is very eas
15 min read
Spring Boot Microservices Communication using RestTemplate with Example
RestTemplate is a synchronous REST client which performs HTTP requests using a simple template-style API. We can also state that RestTemplate class is a synchronous client and is designed to call REST services. Apart from that, RestTemplate class plays a major role whenever we talk about Spring Boot Microservices Communication. The basic syntax of
14 min read
Spring Boot Microservices Communication using WebClient with Example
WebClient is an interface illustrating the main entry point for performing web requests. It is also known as the reactive web client which is introduced in Spring 5. This new client is a reactive, non-blocking solution that works over the HTTP/1.1 protocol. We can also say that it is a replacement for the classic RestTemplate. It is a part of sprin
15 min read
Spring Boot Microservices - Load Balancing using Netflix’s Ribbon
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
13 min read
Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Boot – Handling Background Tasks with Spring Boot
Efficiently handling background tasks with Spring Boot is important for providing a smooth user experience and optimizing resource utilization. Background tasks refer to operations that are performed asynchronously or in the background, allowing the main application to continue processing other requests. In a Spring Boot application, background tas
5 min read
Spring Boot – Setting Up a Spring Boot Project with Gradle
Spring Boot is a Java framework designed to simplify the development of stand-alone, production-ready Spring applications with minimal setup and configuration. It simplifies the setup and development of new Spring applications, reducing boilerplate code. In this article, we will guide you through setting up a Spring Boot project using Gradle, a wid
4 min read
Introduction to Messaging Queues in Spring Boot Microservices
In Microservices architecture, communication between the services is essential for achieving loose coupling and scalability. Messaging queues provide a reliable and asynchronous communication mechanism that can enable the seamless interaction between the microservices. Spring boot is a popular framework that can used for building microservices in J
8 min read
Load Balancing in Spring Boot Microservices
Load balancing is an important concept in distributed systems, especially in microservice environments. As enterprises increasingly adopt cloud-native technologies, application models require complex load-balancing strategies to efficiently deliver requests to customers This ensures high availability, fault tolerance, and resource efficiency in dyn
5 min read
Implementing a Basic Circuit Breaker with Hystrix in Spring Boot Microservices
The Circuit breaker is a design pattern used in software development to improve system resilience by preventing cascading failures. It monitors failures and opens the circuit when a certain threshold is reached, preventing further calls to the failing service. This prevents the system from being overwhelmed and allows it to recover. Hystrix is the
4 min read
Microservices Communication with Apache Kafka in Spring Boot
Apache Kafka is a distributed streaming platform and can be widely used to create real-time data pipelines and streaming applications. It can publish and subscribe to records in progress, save these records in an error-free manner, and handle floating records as they arrive. Combined with Spring Boot, Kafka can provide a powerful solution for micro
6 min read
How to Share DTO Across Spring Boot Microservices?
A Data Transfer Object(DTO) is an object that encapsulates data and transports it from one subsystem of an application to another. The Services layer in an N-Tier application often uses DTOs to transport data between itself and the UI Microservices have gained popularity over time. They are lighter, more modular, and easier to install and scale. Ho
4 min read
Implementing Round Robin Load Balancing in Spring Boot Microservices
Round Robin Load Balancing is a method of distributing client requests across multiple servers in a sequential manner. It ensures that each server handles an equal number of requests over time. This approach can be particularly useful for evenly distributing the load and avoiding overburdening a single server, which can lead to better performance a
7 min read
7 Major Reasons to Choose Spring Boot For Microservices Development
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
6 min read
Secure Service Registration with Eureka and Spring Boot Microservices
In microservice architecture, service registration and discovery can plays the crucial role. Eureka is a part of the Spring Cloud Netflix project and it provides the mechanism to register and discover the services. It ensure the secure communication between the services. It is important to secure the Eureka server and client. This article, guides y
4 min read
Debugging Eureka Issues in Spring Boot Microservices
Debugging Eureka issues in Spring Boot microservices involves several steps and checks to ensure proper registration, discovery, and communication between services. Debugging the Eureka issues can typically involve checking the following: Eureka Server and Client Configurations.Network connectivity between the Eureka Server and Clients of the appli
4 min read