[Practice] Open API 연동 시 API 프로퍼티 활용

2021. 4. 20. 00:20Spring/Practice

1. 문제

  • Open API 연동 문제에서 활용한 API 키를 프로퍼티로 설정하여 호출하는 API

 

 

 

2. 풀이

- application.yml

...

### 네이버 API
naver-app:
  client-id: [클라이언트 Id]
  client-secret: [클라이언트 Secret]

- NaverAppProperties.java

package com.example.jpa.sample.common.properties;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties("naver-app")
@Component
@Data
public class NaverAppProperties {

    private String clientId;
    private String clientSecret;
}

- ApiExtraNaverController.java

package com.example.jpa.sample.extra.controller;

import com.example.jpa.sample.common.model.ResponseResult;
import com.example.jpa.sample.common.properties.NaverAppProperties;
import com.example.jpa.sample.extra.model.NaverTranslateInput;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RequiredArgsConstructor
@RestController
public class ApiExtraNaverController {

    private final NaverAppProperties naverAppProperties;

    @GetMapping("/api/extra/naver/translate")
    public ResponseEntity<?> translate(@RequestBody NaverTranslateInput naverTranslateInput) {

        String clientId = naverAppProperties.getClientId();
        String clientSecret = naverAppProperties.getClientSecret();

        String url = "https://openapi.naver.com/v1/papago/n2mt";

        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
        parameters.add("source", "ko");
        parameters.add("target", "en");
        parameters.add("text", naverTranslateInput.getText());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("X-Naver-Client-Id", clientId);
        headers.add("X-Naver-Client-Secret", clientSecret);

        HttpEntity formEntity = new HttpEntity<>(parameters, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, formEntity, String.class);

        return ResponseResult.success(responseEntity.getBody());
    }
}
728x90

'Spring > Practice' 카테고리의 다른 글

[Practice] 메일 전송 (2)  (0) 2021.04.20
[Practice] 메일 전송 (1)  (0) 2021.04.20
[Practice] 인터셉터 활용 (2)  (0) 2021.04.20
[Practice] 인터셉터 활용 (1)  (0) 2021.04.19