웹 개론 을 복습하기 위해 REST API에 대해 다시 한 번 정리하고 HTTP Method에 대해 자세히 설명하겠다.
REST API란 REST 특징을 지키면서 API(application programming interface)를 제공하는 것이며, HTTP 프로토콜의 장점을 살릴 수 있는 네트워크 기반 아키텍처이다.
REST의 특징은 다음과 같다.
- Uniform Interface
- Client-Server
- Stateless
- Cacheable
- Layered System
- Code on Demand(optional)
HTTP Method
HTTP Method | 동작 | URL 형태 |
GET | 조회(Read) | /api/board |
POST | 생성(Create) | /api/board |
PUT | 수정(Update) | /api/board/{1} |
DELETE | 삭제(Delete) | /api/board/{1} |
GET API
@RestController // Controller로서 동작하기 위한 어노테이션
@RequestMapping("/api/get") //요청에 대해 어떤 Controller, 어떤 메소드를 처리할 지 매핑하는 어노테이션
public class GetController{
@GetMapping(path="/hello")
public String getHello(){
return "get Hello";
}
@RequestMapping(path="/hi",method=RequestMethod.GET)
public String hi(){
return "hi";
}
}
@RequestMapping
RequestMapping은 예전에 주로 사용했다.
value(path)만 지정하면 get,post,put,delete 요청에 응답한다.
@RequestMapping(path="/hi",method=RequestMethod.GET) 처럼 포커싱을 해줘야 한다.
Path Variable 지정
@GetMapping("/경로/{PathVariable}")
@PathVariable
URL 경로에 변수를 넣어주는 것
URL 정의 부분과 Method 내의 Parameter 부분에 정의해 사용
@RestController
@RequestMapping("/api/get")
public class GetController{
//생략
@GetMapping("/path-variable/{name}")
public String pathVariable(@PathVariable String name){
System.out.println("PathVariable : "+name);
return name;
}
}
Query Parameter 지정
?로 시작, &로 구분
사용 예) http://localhost:8080/api/get/query?name=arin&email=abc@gmail.com
@RequestParam을 여러개 지정하는 경우 개수가 많아질수록 코드를 작성하는데 어려움을 겪는다.
이때 Dto를 사용해 어려움을 해결할 수 있다.
Dto를 사용하면 @RequestParam 어노테이션을 사용하지 않고 객체 내부의 변수와 쿼리 셋의 파라미터명을 비교해 매칭할 수 있다.
UserRequestDto
public class UserRequest {
private String name;
private String email;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString(){
return "UserRequest{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
GetController - dto
@GetMapping("/query-param03")
public String queryParam03(UserRequest userRequest) {
System.out.println(userRequest.getName());
System.out.println(userRequest.getEmail());
System.out.println(userRequest.getAge());
return userRequest.toString();
}
'개발 > Spring' 카테고리의 다른 글
[SpringBoot] 인텔리제이로 스프링 부트 시작하기 (0) | 2022.05.16 |
---|---|
Spring Boot Validation (0) | 2022.02.05 |
Spring Boot + JPA 게시물 조회수 기능 (0) | 2022.01.14 |
[Spring Boot] REST API ( HELLO WORLD! ) 구현 (0) | 2021.12.30 |
웹 개론 (0) | 2021.12.27 |