REST
REST API
스프링 MVC HTTP 요청-처리 어노테이션
어노테이션 | HTTP Method | 용도 |
---|---|---|
GetMapping | HTTP GET 요청 | 리소스 데이터 읽기 |
PostMapping | HTTP POST 요청 | 리소스 생성하기 |
PutMapping | HTTP PUT 요청 | 리소스 변경하기 |
PatchMapping | HTTP PATCH 요청 | 리소스 변경하기 |
DeleteMapping | HTTP DELETE 요청 | 리소스 삭제하기 |
RequestMapping | 다목적 요청 처리 |
RestController 컨트롤러 구현
기존 API의 문제점
HATEOAS (Hyper As The Engine Of Application State)
HAL
{
"_embedded" : {
"tacos" : [ {
"createdAt" : "2023-02-21T11:39:34.633+00:00",
"name" : "Carnivore",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/tacos/2"
},
"taco" : {
"href" : "http://localhost:8080/api/tacos/2"
},
"ingredients" : {
"href" : "http://localhost:8080/api/tacos/2/ingredients"
}
}
},
...
]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/tacos"
}
}
HATEOAS 활용 하이퍼미디어 생성방법
1) HATEOAS 의존성 추가 (build.gradle 또는 pom.xml)
2) 리스트 내 각 리소스의 하이퍼미디어 생성을 위한 리소스 어셈블러 생성
3) 리소스를 반환하도록 컨트롤러 클래스의 메소드 수정
HATEOAS에성 제공하는 클래스 및 속성
분류 | 스프링 2.2 이전 | 스프링 2.2 이후 |
---|---|---|
단일 리소스 | Resource | EntityModel |
다중 리소스 | Resources | CollectionModel |
리소스 Link 관리 | ResourceSupport | RepresentationalModel |
객체 →리소스로 변환 | ResourceAssemblerSupport | RepresentationModelAssemblerSupport |
curl localhost:8080/ingredients ← 실행 후 터미널 입력
{
"_embedded" : {
"ingredients" : [ {
"name" : "Flour Tortilla",
"type" : "WRAP",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/ingredients/FLTO"
},
"ingredient" : {
"href" : "http://localhost:8080/api/ingredients/FLTO"
}
}
},
...
]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/ingredients"
},
"profile" : {
"href" : "http://localhost:8080/api/profile/ingredients"
}
}
}
@RestResource(rel="tacos", path="tacos") ← 경로와 관계이름을 tacos로 설정
public class Taco {
...
}