Notice
Recent Posts
Recent Comments
Link
관리 메뉴

look-forest

API 구현 2 - HATEOAS 적용 본문

Spring/Spring 기반 REST API 개발

API 구현 2 - HATEOAS 적용

studyHub 2024. 10. 26. 18:30

REST API의 리소스 모델로 응답하기

RepresentationModel 

REST API의 리소스 모델

Spring HATEOAS에서 RepresentationModel은 REST API에서 리소스를 표현하고 하이퍼미디어를 추가하는 기본 클래스. 이 클래스는 서버가 리소스의 상태와 함께 하이퍼링크를 포함해, 클라이언트가 어떤 행동을 수행할 수 있는지 명시적으로 알려줄 수 있도록 도와줘, 이를 통해 클라이언트는 서버의 응답에 포함된 링크를 통해 상태 전이를 수행할 수 있게 된다.

public class EntityModel<T> extends RepresentationModel<EntityModel<T>> {

 

  • RepresentationModel은 기본적으로 단순한 리소스 표현을 다루며, EntityModel, CollectionModel, PagedModel 등의 클래스가 이를 확장하여 더 구체적인 리소스 모델을 제공
  • EntityModel은 단일 객체에 링크를 추가하기 좋고, CollectionModel은 여러 리소스 목록에 링크 추가할 때 유용

Location URI 만들기

  • HATEOS가 제공하는 linkTo(), methodOn() 사용
  • 201 Create의 경우 응답의 Location 헤더가 생성 요청된 리소스의 URI (3xx면 redirect URL)

 

 

@PostMapping
public ResponseEntity<?> createEvent(@RequestBody @Valid EventDto eventDto, Errors errors,
                                     @CurrentUser Account currentUser) {
    if (errors.hasErrors()) {
        return badRequest(errors);
    }
    eventValidator.validate(eventDto, errors);
    if (errors.hasErrors()) {
        return badRequest(errors);
    }

    Event event = modelMapper.map(eventDto, Event.class);
    event.update();
    event.setManager(accountRepository.findByEmail(currentUser.getEmail())
            .orElseThrow(NoSuchElementException::new));
    Event newEvent = this.eventRepository.save(event);
    WebMvcLinkBuilder selfLinkBuilder = linkTo(EventController.class).slash(newEvent.getId());
    URI createdUri = selfLinkBuilder.toUri();

    EventResource eventResource = new EventResource(event);
    eventResource.add(linkTo(EventController.class).withRel("query-events"));
    eventResource.add(selfLinkBuilder.withRel("update-event"));
    eventResource.add(Link.of("/docs/index.html#resources-events-create").withRel("profile"));
    return ResponseEntity.created(createdUri).body(eventResource);
}

인덱스 핸들러 만들기

사이트 진입 후 클릭 만으로 이용할 수 있는 것처럼, API 시작점인 인덱스 API를 만들어 다른 리소스에 대한 링크 제공.

이 인덱스 API를 에러 응답에 활용할 수 있다. 에러 응답 시 인덱스로 이동하는 것이다.

에러 응답 시
응답에 Error를 ErrorResource로 넣는데
ErrorResource에 index 링크가 있다.

 


목록 조회 API - 페이징

스프링 데이터 JPA가 제공하는 Pageable을 이용해 페이징, 정렬한다.

 

추가로,  PagedResourceAssembler를 이용해 

Page도 리소스로 변경시키면서,  Page<Event>에 안에 들어있는 Event 들도 리소스로 변경!

page를 PageResource로 변경하면 페이지 관련 링크가 생기고, PagedResourceAssembler를 이용해 content인 event도 리소스로 변경할 수 있다.

 

그 결과 event, page 모두 리소스화 되어 링크가 생긴다

 

 


참고 자료 & 이미지 출처
스프링 기반 REST API 개발 (백기선 님)

 

'Spring > Spring 기반 REST API 개발' 카테고리의 다른 글

CORS(Cross-Origin Resource Sharing) 설정  (0) 2025.01.12
HATEOAS와 Self-Descriptive Message 적용  (2) 2024.10.25
API 구현 예시와 팁  (0) 2024.10.22
REST API와 HATEOAS  (0) 2024.10.21