공공데이터 API를 Spring Boot에서 연동하는 방법을 설명해 드릴게요!
build.gradle or pom.xml)Gradle:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}
application.yml 설정public-api:
url: https://apis.data.go.kr/서비스경로
service-key: 발급받은_인증키_여기에_입력
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Service
public class PublicApiService {
@Value("${public-api.url}")
private String apiUrl;
@Value("${public-api.service-key}")
private String serviceKey;
private final RestTemplate restTemplate;
public PublicApiService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String fetchData(String keyword) {
UriComponents uri = UriComponentsBuilder
.fromHttpUrl(apiUrl)
.queryParam("serviceKey", serviceKey)
.queryParam("numOfRows", 10)
.queryParam("pageNo", 1)
.queryParam("keyword", keyword)
.build(false); // 인증키 인코딩 방지
ResponseEntity<String> response = restTemplate.getForEntity(uri.toUriString(), String.class);
return response.getBody();
}
}
@RestController
@RequestMapping("/api")
public class PublicApiController {
private final PublicApiService publicApiService;
public PublicApiController(PublicApiService publicApiService) {
this.publicApiService = publicApiService;
}
@GetMapping("/search")
public ResponseEntity<String> search(@RequestParam String keyword) {
String result = publicApiService.fetchData(keyword);
return ResponseEntity.ok(result);
}
}
// DTO 예시
@JsonIgnoreProperties(ignoreUnknown = true)
public class ApiResponse {
private Response response;
// getter, setter
}
// 파싱
ApiResponse result = restTemplate.getForObject(uri.toUriString(), ApiResponse.class);
| 문제 | 해결방법 |
|---|---|
| 인증키 오류 | .build(false)로 인코딩 방지 |
| XML 응답 | produces = "application/json" 또는 파라미터에 _type=json 추가 |
| SSL 오류 | RestTemplate에 SSL 무시 설정 추가 |
| 한글 깨짐 | UTF-8 인코딩 설정 |