TIL

[TIL 2024/09/11] HTTP Interface

dev_ajrqkq 2024. 9. 12. 01:59

프로젝트 수행 중 gemini API를 연동하면서 HTTP 인터페이스를 새로이 알게되었다.

옛날옛적에...약 4년전에 카카오나 네이버로 외부 api 연동할 때는 RestTemplate을 사용했었는데 ......

 

HTTP 인터페이스는 Spring6 에서 새롭게 추가 되었다고 한다.

 

HTTP Interface를 호출하면 요청될 구현체 생성

@Bean
public RestClient geminiRestClient(@Value("${gemini.api.url}") String baseUrl,
    @Value("${gemini.api.key}") String apiKey) {
    return RestClient.builder()
        .baseUrl(baseUrl)
        .defaultHeader("x-goog-api-key", apiKey)
        .defaultHeader("Content-Type", "application/json")
        .build();
}

@Bean
public AiInterface geminiInterface(@Qualifier("geminiRestClient") RestClient client) {
    RestClientAdapter adapter = RestClientAdapter.create(client);
    HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
    return factory.createClient(AiInterface.class);
}

(1) RestClient 객체를 생성하고 기본 URL 및 apiKey를 설정한다.

=>RestClient는 Http 요청을 보내는 역할

(2) RestClientAdaptor는 RestClient의 기능을 확장하는 역할

(3) RestClientAdaptor로 HttpServiceProxyFactory 생성 => Http 서비스의 프록시 객체를 생성한다.

(4) AiInterface는 HttpServiceProxyFactory 를 통해 프록시가 생성되고, 이 프록시 객체가 빈으로 등록된다.

(5) 프록시 객체는 AiInterface를 구현하는 클래스처럼 동작하며, 해당 인터페이스의 메서드를 호출하면 자동으로 HTTP 요청을 보내고 결과를 받아온다.

 

@HttpExchange("/v1beta/models")
public interface AiInterface {

    @PostExchange("{model}:generateContent")
    AiResponse getCompletion(
        @PathVariable String model,
        @RequestBody AiRequest request
    );
}

@HttpExchange : URL 경로를 지정한다.

@PostExchange : Post 요청 처리

 

요청 예시

public static final String GEMINI_PRO = "gemini-pro";

private final AiInterface aiInterface;

private AiResponse getCompletion(AiRequest request) {
    return aiInterface.getCompletion(GEMINI_PRO, request);
}

AiInterface의 getCompletion 호출 시 

https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent

AiRequest body를 들고

요청된다!

 

 

 

REST Clients :: Spring Framework

WebClient is a non-blocking, reactive client to perform HTTP requests. It was introduced in 5.0 and offers an alternative to the RestTemplate, with support for synchronous, asynchronous, and streaming scenarios. WebClient supports the following: Non-blocki

docs.spring.io