API 연동방법

개발자되고싶은데·2026년 2월 23일

공공데이터 API를 Spring Boot에서 연동하는 방법을 설명해 드릴게요!


📌 공공데이터 API 연동 (Spring Boot + Java)

1. 의존성 추가 (build.gradle or pom.xml)

Gradle:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
}

2. application.yml 설정

public-api:
  url: https://apis.data.go.kr/서비스경로
  service-key: 발급받은_인증키_여기에_입력

3. RestTemplate 빈 등록

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

4. 서비스 코드 작성

@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();
    }
}

5. 컨트롤러 작성

@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);
    }
}

6. JSON 응답을 객체로 파싱하고 싶다면

// 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 인코딩 설정

0개의 댓글