Dev_Dylan

[Spring] Study Guide _ Consuming a RESTful Web Service 맛보기 본문

Spring

[Spring] Study Guide _ Consuming a RESTful Web Service 맛보기

Dylan_21 2024. 11. 7. 21:09

Point : RestTemplate

RESTful Web Service 사용하기


요약

  • RestTemplate 를 사용해 RESTful 웹 서비스 호출
  • RestTemplategetForObject() 메서드를 사용해 JSON → java 파싱하기.

정리

Guide 순서

  1. API 뿌려줄 파일 다운 및 셋팅
  2. data 파싱을 위한 DTO 생성
  3. RestTemplate 를 통한 서버 호출 및 JSON 파싱

프로젝트를 진행하기 위한 필수!
이 Guide를 진행을 위해 아래 프로젝트를 사용해야 함.
(포트번호 8080으로 json데이터를 뿌려주면 8081에서 json parsing 작업을 위함.)

https://github.com/spring-guides/gs-consuming-rest.git

위 프로젝트를 통해 Server를 올려주기 위함


Data Type 구현

앞의 Guide에서와 같이, 간편하게 Record 타입을 통해 구현.

//////Quote//////////////////////////////////////////////////////////////////////
package com.example.consumingrest;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public record Quote(String type, Value value) { }

//////Value//////////////////////////////////////////////////////////////////////
package com.example.consumingrest;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public record Value(Long id, String quote) { }

JsonIgnoreProperties

서버에서 뿌려준 API의 JSON에 추가되거나, 부족한 부분들을 무시해준다.

// 여기에서는 추가로 구현된 데이터 필드가 무시된다.
@JsonIgnoreProperties({"ignoredField1", "ignoredField2"})
public class MyClass {
    private String field1;
    private String ignoredField1; // 이 필드는 JSON 데이터에서 무시됨
    private String ignoredField2; // 이 필드도 무시됨
}

// 여기에서는 field2라는 필드가 들어와도 무시하고 field1 으로 넣어줌.
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyClass {
    private String field1;
}

RestTemplate

맨 아래 간략한 설명 추가.


최상위 실행 main 클래스 구현.

@SpringBootApplication
public class ConsumingRestApplication {

    private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(ConsumingRestApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Bean
    @Profile("!test")
    public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
        return args -> {
            Quote quote = restTemplate.getForObject(
                    "http://localhost:8080/api/random", Quote.class);
            log.info(quote.toString()); 
            System.out.println(quote.toString()); // 눈에 잘 안띄어서 print 추가
        };
    }
}

RestTemplate를 사용하기 위해 @Bean을 등록해주어야 함.

@Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

random API를 받아서 Quote로 매칭 시켜줌.

getForObject() 를 사용해 Quote로 JSON 파싱을 바로 해줌.

public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
        return args -> {
            Quote quote = restTemplate.getForObject(
                    "http://localhost:8080/api/random", Quote.class);
            log.info(quote.toString()); 
            System.out.println(quote.toString()); // 눈에 잘 안띄어서 print 추가
        };
    }

포트번호 변경

포트번호를 바꿔야함 → JSON 뿌려주는 서버를 8080 으로 켜놓은 상태이기 때문에, 중복으로 켜지지않음.

application.propertiesserver.port=8081 넣어주면 포트변경 끝.

실행하면..

화살표 오른쪽으로 쭉 가보면 log가 떠있는것을 확인 할 수 있음.

RestTemplate

주요 특징

  • 동기적: RestTemplate은 요청이 완료될 때까지 블로킹 방식으로 작동함
  • GET, POST, PUT, DELETE, PATCH HTTP 메서드를 지원함
  • 직관적인 메서드 제공: REST API 호출을 간단하게 처리할 수 있도록 여러 편의 메서드를 제공함.
  • 객체 직렬화/역직렬화: JSON, XML 등을 Java 객체로 변환하거나 그 반대로 변환할 수 있음.
  • 예외 처리: HTTP 상태 코드에 따라 예외를 던집니다. 예를 들어, 4xx나 5xx 응답이 반환되면 HttpClientErrorException 또는 HttpServerErrorException을 발생시킴

주요 메서드

  1. getForObject()
    • HTTP GET 요청을 보내고, 응답을 지정한 객체 타입으로 반환함.
    • String url = "https://api.example.com/resource"; MyObject response = restTemplate.getForObject(url, MyObject.class);
  2. getForEntity()
    • HTTP GET 요청을 보내고, 응답을 ResponseEntity로 반환
      응답 상태 코드, 헤더, 본문을 모두 포함함
    • ResponseEntity<MyObject> response = restTemplate.getForEntity(url, MyObject.class);
  3. postForObject()
    • HTTP POST 요청을 보내고, 응답을 객체로 반환함.
    • MyRequest request = new MyRequest(); MyResponse response = restTemplate.postForObject(url, request, MyResponse.class);
  4. postForEntity()
    • HTTP POST 요청을 보냄
      응답을 ResponseEntity로 반환함.
    • ResponseEntity<MyResponse> response = restTemplate.postForEntity(url, request, MyResponse.class);
  5. put()
    • HTTP PUT 요청 보냄.
      응답은 필요하지 않을 때 사용
    • restTemplate.put(url, request);
  6. delete()
    • HTTP DELETE 요청을 보냅니다.
    • restTemplate.delete(url);

Keyword

  • RestTemplate
  • JsonIgnoreProperties

'Spring' 카테고리의 다른 글

[Spring] Study Guide _ Building a RESTful Web Service 맛보기  (2) 2024.11.03
Comments