개발 공부/Spring
[SpringBoot] REST API - PUT
journey
2022. 2. 16. 00:44
728x90
05. PUT API
- 리소스가 존재한다면 수정(갱신) 없다면 생성.
- 연산을 여러 번 적용하더라도 결과가 달라지지 않는 성질. 동일한 요청을 한 번 보내는 것과 여러 번 연속으로 보내는 것이 같은 효과를 지니고, 서버의 상태도 동일하게 남는다. → 해당 HTTP 메서드가 멱등성을 가졌다.
@RestController : Rest API 설정어노테이션
- @RequestMapping : 리소스를 설정 (method로 구분 가능)
- @PostMapping : Post Resource 설정
- @RequestBody : Request Body 부분 Parsing
- @PathVariable : URL Path Variable Parsing
JSON 디자인
{
"name" : "짱구",
"age" : 20,
"car_list" : [
{
"name" : "BMW",
"car_number" : "05가 0909"
},
{
"name" : "Benz",
"car_number" : "10나 8080"
}
]
}
코드
- PutRequestDto.java
package com.example.put.dto;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import java.util.List;
@JsonNaming(value= PropertyNamingStrategy.SnakeCaseStrategy.class) // 해당 클래스에 일관적으로 제이슨 룰 적용. JsonProperty는 각각에 적용
public class PutRequestDto {
private String name;
private int age;
private List<CarDto> carList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<CarDto> getCarList() {
return carList;
}
public void setCarList(List<CarDto> carList) {
this.carList = carList;
}
@Override
public String toString() {
return "PutRequestDto{" +
"name='" + name + '\'' +
", age=" + age +
", carList=" + carList +
'}';
}
}
- CarDto.java
package com.example.put.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
public class CarDto {
private String name;
@JsonProperty("car_number") // 특정 변수로 제이슨 룰 적용.
private String carNumber;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCarNumber() {
return carNumber;
}
public void setCarNumber(String carNumber) {
this.carNumber = carNumber;
}
@Override
public String toString() {
return "CarDto{" +
"name='" + name + '\'' +
", carNumber='" + carNumber + '\'' +
'}';
}
}
- PutApiController.java
package com.example.put.controller;
import com.example.put.dto.PutRequestDto;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class PutApiController {
@PutMapping("/put/{userId}")
public PutRequestDto put(@RequestBody PutRequestDto requestDto, @PathVariable Long userId) { //@PathVariable(name="userId") Long id
System.out.println(userId);
System.out.println(requestDto);
// Object 그대로 Response하면 오브젝트매퍼를 통해서 제이슨 형태로 응답해준다. Talent API에서 응답된거 확인할 수 있다.
return requestDto;
}
}
- API 결과
- Console 결과