Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Routing and Request Transformation in API Gateways in Spring Cloud Microservices
Next article icon

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

Last Updated : 04 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">     <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.


Next Article
Routing and Request Transformation in API Gateways in Spring Cloud Microservices

A

AmiyaRanjanRout
Improve
Article Tags :
  • Java
  • Advance Java
  • Java-Spring-Boot
  • Java-Spring-Cloud
  • Java Microservices
Practice Tags :
  • Java

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 smal
    5 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 smal
    13 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
    3 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
    10 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 e
    6 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 microserv
    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 s
    4 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
    9 min read
  • Why Use Spring Cloud 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 smal
    9 min read
  • Deploy Java Microservices on Amazon ECS using AWS Fargate
    In recent, Microservices architecture has gained huge popularity. It provides an effective way to develop and deploy applications. The Architecture of Microservices works on dividing a Monolithic big application into smaller sub-applications as independent services that can be easily developed, depl
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences