Introduction
There are many API Gateway tools available, each with advantages and disadvantages. But sometimes, we need something simpler because of very specific business rules, for example. This is why you might want to create your own API Gateway.
To create this minimal API Gateway, we will use a Spring Cloud Gateway utility object calledProxyExchange
. From the official documentation:
You can use it inside a regular Spring web handler as a method parameter. It supports basic downstream HTTP exchanges through methods that mirror the HTTP verbs. With MVC, it also supports forwarding to a local handler through the forward()
method. To use the ProxyExchange
, include the right module in your classpath (either spring-cloud-gateway-mvc
or spring-cloud-gateway-webflux
).
Creating the API Gateway
So, let's create a new Spring Boot application with the Spring Reactive Web dependency and add the dependency below to the project'spom.xml
or build.gradle
file.
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-webflux</artifactId>
<version>4.1.5</version>
</dependency>
The next step is to add a controller that matches any request. See the example below written in Kotlin:
@RestController
class GatewayController {
@RequestMapping("/**")
fun proxy(
): Mono<ResponseEntity<ByteArray>> = Mono.empty()
}
What's the basic job of an API Gateway when working with microservices? Basically, it is to be a unique entry point for all the microservices we want to expose to the external world. To cite a few examples, the external world can be a front-end web application or a mobile application. This way, the consumers don't need to know the addresses of all the microservices. So, the basic job is to act like a reverse proxy.