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

✨ [Feat] OPEN API 사용 구현 #171

Open
wants to merge 1 commit into
base: jinny
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,9 @@ dependencies {
testImplementation 'org.springframework.security:spring-security-test'

// JWT
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.2'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.2'
implementation 'io.jsonwebtoken:jjwt-api:0.12.3'
implementation 'io.jsonwebtoken:jjwt-impl:0.12.3'
implementation 'io.jsonwebtoken:jjwt-jackson:0.12.3'

// OAuth2 login
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public boolean isValid(String token) {

public Jws<Claims> getClaims(String token) {
try {
return Jwts.parser()
return Jwts.parserBuilder()
.setSigningKey(secret) // 서명 키 설정
.build() // JwtParser 객체 생성
.parseClaimsJws(token); // 토큰 파싱
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.example.umc7th.global.openApi;

import org.springframework.web.reactive.function.client.WebClient;

public interface OpenApiWebClient {
// 한국 관광정보를 가져올 수 있는 WebClient를 반환하는 메소드 정의
WebClient getTourWebClient(String language);
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.example.umc7th.global.openApi;


import com.example.umc7th.global.openApi.exception.OpenApiErrorCode;
import com.example.umc7th.global.openApi.exception.OpenApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.DefaultUriBuilderFactory;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;

@Component
@Slf4j
public class OpenApiWebClientImpl implements OpenApiWebClient {

@Override
public WebClient getTourWebClient(String language) {
if (language.equals("korean")) {
return getWebClient("https://apis.data.go.kr/B551011/KorService1");
}
else if (language.equals("english")) {
return getWebClient("https://apis.data.go.kr/B551011/EngService1");
}
else {
throw new OpenApiException(OpenApiErrorCode.UNSUPPORTED_LANGUAGE);
}
}

// 영문 API를 추가한 경우
// @Override
// public WebClient getEnglishTourWebClient() {
// return getWebClient("https://apis.data.go.kr/B551011/EngService1");
// }

private WebClient getWebClient(String baseUrl) {
HttpClient httpClient = HttpClient.create()
.responseTimeout(Duration.ofMillis(20000));

// Uri를 build하는 factory 생성 (baseUrl을 WebClient 대신 여기에 포함하도록)
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(baseUrl);
// Uri factory에 인코딩 모드를 NONE으로 바꾸어 인코딩하지 않도록해줍니다.
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);

return WebClient.builder()
.uriBuilderFactory(factory)
.clientConnector(new ReactorClientHttpConnector(httpClient))
.filter((request, next) -> {
log.info("Web Client Request: "+ request.url());
return next.exchange(request);
})
.build();
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.umc7th.global.openApi.controller;

import com.example.umc7th.global.apiPayload.CustomResponse;
import com.example.umc7th.global.openApi.dto.OpenApiResponseDTO;
import com.example.umc7th.global.openApi.service.OpenApiQueryService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class OpenApiController {

private final OpenApiQueryService openApiQueryService;

@GetMapping("/searchStay")
public CustomResponse<OpenApiResponseDTO.SearchStayResponseListDTO> controller(@RequestParam(name = "arrange", defaultValue = "A") String arrange,
@RequestParam(name = "page", defaultValue = "1") int page,
@RequestParam(name = "offset", defaultValue = "10") int offset) {
return CustomResponse.onSuccess(openApiQueryService.searchStay(arrange, page, offset));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.example.umc7th.global.openApi.dto;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.List;

public class OpenApiResponseDTO {

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public static class SearchStayResponseDTO {
private String addr1;
private String title;
private String tel;
private String contentid;
private String contenttypeid;
private String createdtime;
private String firstimage;
private String firstimage2;
private String mapx;
private String mapy;
}

@Builder
@NoArgsConstructor
@AllArgsConstructor
@Getter
public static class SearchStayResponseListDTO {
private List<SearchStayResponseDTO> item;

public static SearchStayResponseListDTO from(List<SearchStayResponseDTO> list) {
return SearchStayResponseListDTO.builder()
.item(list)
.build();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.example.umc7th.global.openApi.exception;

import com.example.umc7th.global.apiPayload.code.BaseErrorCode;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;

@AllArgsConstructor
@Getter
public enum OpenApiErrorCode implements BaseErrorCode {
UNSUPPORTED_LANGUAGE(HttpStatus.BAD_REQUEST, "COMMON400", "지원하지 않는 언어입니다."),
;
private final HttpStatus status;
private final String code;
private final String message;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.example.umc7th.global.openApi.exception;

import com.example.umc7th.global.apiPayload.code.BaseErrorCode;
import lombok.Getter;

@Getter
public class OpenApiException extends RuntimeException {
// 예외에서 발생한 에러의 상세 내용
private final OpenApiErrorCode code;

// 생성자
public OpenApiException(OpenApiErrorCode code) {
this.code = code;
}
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.umc7th.global.openApi.service;

import com.example.umc7th.global.openApi.dto.OpenApiResponseDTO;


public interface OpenApiQueryService {

OpenApiResponseDTO.SearchStayResponseListDTO searchStay(String arrange, int page, int offset);

OpenApiResponseDTO.SearchStayResponseListDTO toSearchStayResponseListDTO(String response);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package com.example.umc7th.global.openApi.service;

import com.example.umc7th.global.openApi.OpenApiWebClient;
import com.example.umc7th.global.openApi.dto.OpenApiResponseDTO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class OpenApiQueryServiceImpl implements OpenApiQueryService {

// WebClient를 가져오기 위한 빈 주입
private final OpenApiWebClient openApiWebClient;

@Value("${openapi.tour.serviceKey}")
private String serviceKey; // 인증 키

@Override
public OpenApiResponseDTO.SearchStayResponseListDTO searchStay(String arrange, int page, int offset) {
// Web Client 가져오기
WebClient webClient = openApiWebClient.getTourWebClient("korean");
Mono<OpenApiResponseDTO.SearchStayResponseListDTO> mono = webClient.get() // get method 사용
// UriBuilder를 이용하여 Endpoint와 Query Param 설정
.uri(uri -> uri
.path("/searchStay1")
.queryParam("numOfRows", offset)
.queryParam("pageNo", page)
.queryParam("MobileOS", "ETC")
.queryParam("MobileApp", "AppTest")
.queryParam("_type", "json")
.queryParam("arrange", arrange)
.queryParam("serviceKey", serviceKey)
.build())
// 응답을 가져오기 위한 method (.onStatus()를 이용해서 Http 상태코드에 따라 다르게 처리해줄 수 있음)
.retrieve()
// 응답에서 body만 String 타입으로 가져오기 (ResponseEntity<Object> 중 Object만 String 형식으로 가져오기)
.bodyToMono(String.class)
// String 값을 메소드로 매핑하여 OpenApiResponseDTO.SearchStayResponseListDTO로 변경하기
.map(this::toSearchStayResponseListDTO)
// 에러가 발생한 경우 log를 찍도록
.doOnError(e -> log.error("Open Api 에러 발생: " + e.getMessage()))
// 성공한 경우에도 log를 찍도록
.doOnSuccess(s -> log.info("관광 정보를 가져오는데 성공했습니다."))
;

// block()을 사용해서 응답을 바로 가져오도록
return mono.block();
}
@Override
public OpenApiResponseDTO.SearchStayResponseListDTO toSearchStayResponseListDTO(String response) {
ObjectMapper objectMapper = new ObjectMapper();
try {
// item으로 담을 list 선언
List<OpenApiResponseDTO.SearchStayResponseDTO> list = new ArrayList<>();
// JsonNode 형식으로 응답을 읽고 item이 담긴 배열만 읽고 싶기에 item이 있는 배열까지 들어가기
JsonNode jsonNode = objectMapper.readTree(response).path("response").path("body").path("items").path("item");
// item 하나씩 처리
for (JsonNode node : jsonNode) {
// item 하나씩 읽어서 OpenApiResponseDTO.SearchStayResponseDTO로 변경해서 List에 추가
list.add(objectMapper.convertValue(node, OpenApiResponseDTO.SearchStayResponseDTO.class));
}
// 응답을 만들어서 반환
return OpenApiResponseDTO.SearchStayResponseListDTO.from(list);
} catch (Exception e) {
// 에러 처리
e.fillInStackTrace();
}
return OpenApiResponseDTO.SearchStayResponseListDTO.from(null);
}

}
6 changes: 6 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,16 @@ spring:
token-uri: https://kauth.kakao.com/oauth/token
user-info-uri: https://kapi.kakao.com/v2/user/me
user-name-attribute: id


springdoc:
swagger-ui:
path: /

openapi:
tour:
serviceKey: ${SERVICE_KEY}

Jwt:
secret: ${JWT_SECRET}
token:
Expand Down