API Gateway with example

API Gateway with example

An API Gateway is a server that acts as an API front-end, 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 serves as a reverse proxy to accept all application programming interface (API) calls, aggregate the various services required to fulfill them, and return the appropriate result.

API Gateway with example

Key Responsibilities:

  • 1. Routing: Directs incoming requests to the appropriate microservice.
  • 2. Aggregation: Combines responses from multiple services into one response.
  • 3. Security: Handles authentication, authorization, and other security protocols.
  • 4. Rate Limiting: Controls the number of requests that users can make to the API.

Example using Spring Cloud Gateway

In this example, we’ll create an API Gateway using Spring Cloud Gateway that routes requests to two different microservices: `UserService` and `OrderService`.

Step 1: Set up Eureka Server
```java
// UserServiceApplication.java
@SpringBootApplication
@RestController
@RequestMapping("/users")
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }

    @GetMapping("/{id}")
    public User getUserById(@PathVariable String id) {
        return new User(id, "John Doe", "john.doe@example.com");
    }
}

// User.java
public class User {
    private String id;
    private String name;
    private String email;

    // Constructors, Getters, and Setters
}
```

Step 2: Set up Eureka Client
```java
// OrderServiceApplication.java
@SpringBootApplication
@RestController
@RequestMapping("/orders")
public class OrderServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }

    @GetMapping("/{orderId}")
    public Order getOrderById(@PathVariable String orderId) {
        return new Order(orderId, "Product 1", 123.45);
    }
}

// Order.java
public class Order {
    private String orderId;
    private String productName;
    private double amount;

    // Constructors, Getters, and Setters
}
```

API Gateway
```java
// ApiGatewayApplication.java
@SpringBootApplication
public class ApiGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }
}

// application.yml
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: http://localhost:8081
          predicates:
            - Path=/users/
        - id: order-service
          uri: http://localhost:8082
          predicates:
            - Path=/orders/
server:
  port: 8080
```

Explanation:

  • 1. UserService:
    • Provides an endpoint `/users/{id}` to get user details.
    • Runs on port 8081.
  • 2. OrderService:
    • Provides an endpoint `/orders/{orderId}` to get order details.
    • Runs on port 8082.
  • 3. API Gateway:
    • Runs on port 8080.
    • Routes requests to the UserService and OrderService based on the URL path.
    • For example, a request to `/users/1` is routed to `http://localhost:8081/users/1`, and a request to `/orders/1` is routed to `http://localhost:8082/orders/1`.

Advantages:

  • Simplified Client Architecture: Clients make a single call to the API Gateway, which then routes to the appropriate microservice.
  • Centralized Cross-Cutting Concerns: Security, rate limiting, and logging can be handled in one place.
  • Reduced Client Complexity: Clients are insulated from the complexities of the microservices architecture.

Disadvantages:

  • Single Point of Failure: The API Gateway itself becomes a potential bottleneck and single point of failure.
  • Latency: Adding an extra hop for all client requests can introduce latency.
  • Complexity: Requires additional infrastructure and configuration.