Rest API 개념 및 구현 by Spring Boot

Song_Song·2021년 9월 25일
1

REST API(Representationl State Transfer)

REST : URI라는 자원을 통해서 HTTP METHOD(GET, POST, PUT, DELETE...)를 사용하여 데이터를 얻고, 변경하고 삭제하는 등의 행위

멱등(Idempotent)

여러 번 실행해도 한 번 실행한 것과 동일한 성질

HTTP 메소드 중, GET, PUT, DELETE는 Idempotent하지만 POST는 Idempotent하지 않다.

PUT vs PATCH

UPDATE는 뭘 사용해야 할까?

PUT : 리소스의 전체를 변경할 때 사용 (partial modifications), 변경하는 데이터만 요청하면 된다. (멱등성o)
PATCH : 리소스의 부분을 변경할 때 사용, 변경하지 않는 데이터도 함께 전송해야 한다. (멱등성x)

리소스의 부분 수정인 PATCH 혹은 POST를 사용하면 된다. 뭘 사용할 지 모르겠다면 POST를 사용하면 된다. POST가 가장 REST 스타일을 잘 따르는 것이다.

HTTP의 PUT 메서드 정의

The PUT method requests that the state of the target resource be
created or replaced with the state defined by the representation
enclosed in the request message payload(= Request Body).
없다면 생성하고 있으면 교체한다는 뜻

Spring boot를 사용한 REST API

@RequestMapping을 사용하여 모든 HTTP 메소드를 처리하던 이전 방식과는 다르게, 최신 방식은 @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping 등을 사용한다.

URI 엔드포인트는 동일하게 사용하되, 어노테이션만 다르게 설정하여 REST API를 처리한다.
또한 메소드 이름 또한 readPerson, deletePerson 과 같이 명확하게 사용하면 REST 스타일에 가깝게 코딩할 수 있다.

@RestController // Rest API를 처리하는 Controller 임을 의미
@RequiredArgsConstructor
@RequestMapping("/api")
public class PersonController {

    private final PersonService personService;
    // POST
    @PostMapping(value = "/person", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) 
    public Person createPerson(@RequestBody Person person){
        Person createdPerson = personService.createPerson(person);
        return createdPerson;
    }
    // GET  
    @GetMapping("/person/{name}")
    public Person readPerson(@PathVariable("name") String name) {
    	Person readOnePerson = personService.readOnePerson(name);
    	return readOnePerson;
    }
    //  전체를 받아올 때 -> URI에 s 붙여 사용
    @GetMapping("/persons")	
    public List<Person> readPersons() {
    	List<Person> readAllPerson = personService.readAllPerson();
    	return readAllPerson;
    }
    // DELETE
    @DeleteMapping("/person/{id}")
    public String deletePerson(@PathVariable("id") int id) {
    	int row = personService.deletePerson(id);
   	
    	return row + "개의 로우가 삭제되었습니다.";
    }
    // PATCH (Partial Modify)
    @PatchMapping("/person")
    public Person patchPerson(@RequestParam("column") String column, @RequestParam("tobe") String tobe, @RequestParam("id") int id) {
    	Person modifiedPerson = personService.patchPersonCompany(column,tobe , id);
   	
    	return modifiedPerson;
    }
    // PUT (create and replace)
    @PutMapping("/person")
    public Person putPerson(@RequestBody Person person) {
    	Person putPerson = personService.putPerson(person);
 	   	
    	return putPerson;
    }
}

REST API의 특징을 잘 정리해놓은 블로그 : https://gmlwjd9405.github.io/2018/09/21/rest-and-restful.html

profile
성장을 위한 정리 블로그

0개의 댓글