Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

카카오 주소 변환 API 호출 및 DTO 변환 #48

Merged
merged 4 commits into from
Apr 22, 2024

Conversation

Doyeon04
Copy link
Contributor

@Doyeon04 Doyeon04 commented Apr 22, 2024

💡 작업 내용

  • 카카오 주소 변환 API 호출
  • API 응답 값 DTO 변환
  • 카카오 API 호출 시 필요한 query 키워드 추가

💡 자세한 설명

Kakao Rest API 호출

  • Kakao Rest API 를 호출하기 위해 RestTemplate를 사용했습니다.
    *RestTemplate: HTTP 서버와 쉽게 통신 가능한 자바 라이브러로 응답을 JSON으로 쉽게 변환 가능
    private ResponseEntity<String> callKakaoAPI(String query) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization", "KakaoAK " + apiKey);
        HttpEntity<Object> httpEntity = new HttpEntity<>(httpHeaders);
        URI targetUrl = UriComponentsBuilder.fromUriString(apiUrl).queryParam("query", query)
                .build().encode(UTF_8).toUri();

        return restTemplate.exchange(targetUrl, HttpMethod.GET, httpEntity,
                String.class);
    }

HTTP 요청 헤더에는 apiKey를 포함한 Authorization 헤더를 설정 한 후 HttpEntity에 포함합니다.
주어진 쿼리를 쿼리 매개변수로하여 API의 URL을 생성하고, 이를 이용하여 RestTemplate의 exchange 메서드를 호출하여 GET 요청을 보냅니다.

JSON으로 파싱 및 DTO 변환

    public AddressInfoResponse fetchAddressInfo(String query, Tag tag) {
        try {

            ResponseEntity<String> response = callKakaoAPI(query);
            if (response.getStatusCode() != HttpStatus.OK) {
                log.error("Kakao API call failed status : {}", response.getStatusCode());
                throw new RuntimeException("Kakao API fail exception");
            }

            JSONObject jsonObject = new JSONObject(response.getBody());
            JSONArray documents = jsonObject.getJSONArray("documents");

            if (documents.isEmpty()) { // API 호출 후 응답값이 없는 경우 추후 처리 필요
                log.warn("No address information found for query: {}", query);
                return null;
            }

            JSONObject document = documents.getJSONObject(0);
            return makeAddressDto(document, tag);
        } catch (JSONException e) {
            log.error("Error parsing JSON from Kakao API : {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

반환된 ResponseEntity를 JSONObject를 통해 JSON으로 파싱하고 DB 삽입을 위한 DTO에 매핑합니다.

추후 고민 및 처리 사항

  • 몇몇 주소 query의 Kakao API 응답이 빈 배열로 오는 경우 처리
  • 카카오 API 호출 실패 시, JSON 파싱 실패 시 등의 예외 처리
  • API 호출 URL들 별도 클래스 분리

📗 참고 자료

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

🚩 후속 작업

  • 예외 처리 및 패키지/클래스 리팩토링

✅ 셀프 체크리스트

  • PR 제목을 형식에 맞게 작성했나요?
  • 브랜치 전략에 맞는 브랜치에 PR을 올리고 있나요?
  • 이슈는 close 했나요?
  • Reviewers, Labels, Projects를 등록했나요?
  • 작업 도중 문서 수정이 필요한 경우 잘 수정했나요?
  • 테스트는 잘 통과했나요?
  • 불필요한 코드는 제거했나요?

closes #47

@Doyeon04 Doyeon04 added the feature 구현, 개선 사항 관련 label Apr 22, 2024
@Doyeon04 Doyeon04 self-assigned this Apr 22, 2024
@Doyeon04 Doyeon04 linked an issue Apr 22, 2024 that may be closed by this pull request
@Doyeon04 Doyeon04 merged commit a8122da into main Apr 22, 2024
1 check passed
@Doyeon04 Doyeon04 deleted the feat/47-kakao-address-api branch April 22, 2024 13:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature 구현, 개선 사항 관련
Projects
None yet
Development

Successfully merging this pull request may close these issues.

카카오 주소 변환 API 호출 및 데이터 추출
2 participants