Skip to content

Gateway example

Somkiat Puisungnoen edited this page Oct 18, 2023 · 6 revisions

Working with Gateway

  • Call API from https://jsonplaceholder.typicode.com/posts/{id}

1. Edit file application.properties

post.api.url=https://jsonplaceholder.typicode.com

2. Create file PostGateway.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Optional;

@Component
public class PostGateway {

    private final RestTemplate restTemplate;
    private final String postApiUrl;

    @Autowired
    public PostGateway(final RestTemplate restTemplate,
                       @Value("${post.api.url}") final String postApiUrl) {
        this.restTemplate = restTemplate;
        this.postApiUrl = postApiUrl;
    }

    public Optional<PostResponse> getPostById(int id) {
        String url = String.format("%s/posts/%d", postApiUrl, id);

        try {
            return Optional.ofNullable(
                    restTemplate.getForObject(url, PostResponse.class));
        } catch (RestClientException e) {
            return Optional.empty();
        }
    }

}

3. Create file PostResponse.java

public class PostResponse {
    private int id;
    private int userId;
    private String title;
    private String body;

    // Setter/Getter methods

4. Create bean of RestTemplate

@Bean
public RestTemplate restTemplate() {
    return new RestTemplateBuilder().build();
}