REST APIs란?
우선, API란 application programming interface의 약자로, application 또는 기기간의 연결과 통신 규칙을 의미하는데, REST APIs는 REST 디자인(Representational State Transfer architectural style) 원칙을 전제로 한 API 통신 규칙을 의미한다.
HTTP의 주요 저자 중 한 명인 Roy Fielding 박사는 2000년에 자신의 박사학위 논문에서 REST를 발표했는데, REST는 개발자들에게 상대적으로 높은 유연성과 자율성을 보장했다. 이러한 REST의 특성이 REST APIs를 마이크로서비스 설계에 있어 보편적인 통신 방법으로 부상하게 만들었다.
REST design principles
REST는 아래 세 가지 요소로 구성되어 있고,
- resource(자원) - URI(uniform resorce identifier, 동일 자원은 하나의 URI로 표현)
- verb(행위) - HTTP Method
- representation(표현)
6가지 디자인 원칙이 존재한다.
1. Uniform interface. All API requests for the same resource should look the same, no matter where the request comes from. The REST API should ensure that the same piece of data, such as the name or email address of a user, belongs to only one uniform resource identifier (URI). Resources shouldn’t be too large but should contain every piece of information that the client might need.
2. Client-server decoupling. In REST API design, client and server applications must be completely independent of each other. The only information the client application should know is the URI of the requested resource; it can't interact with the server application in any other ways. Similarly, a server application shouldn't modify the client application other than passing it to the requested data via HTTP.
3. Statelessness. REST APIs are stateless, meaning that each request needs to include all the information necessary for processing it. In other words, REST APIs do not require any server-side sessions. Server applications aren’t allowed to store any data related to a client request.
4. Cacheability. When possible, resources should be cacheable on the client or server side. Server responses also need to contain information about whether caching is allowed for the delivered resource. The goal is to improve performance on the client side, while increasing scalability on the server side.
5. Layered system architecture. In REST APIs, the calls and responses go through different layers. As a rule of thumb, don’t assume that the client and server applications connect directly to each other. There may be a number of different intermediaries in the communication loop. REST APIs need to be designed so that neither the client nor the server can tell whether it communicates with the end application or an intermediary.
6. Code on demand (optional). REST APIs usually send static resources, but in certain cases, responses can also contain executable code (such as Java applets). In these cases, the code should only run on-demand.
- IBM Cloud Learn Hub / What is a REST API?
아래 블로그에 실전에서 꼭 필요한 REST APIs 작성 규칙을 상세하게 소개하고 있다. (4. REST API 디자인 가이드)
REST API 제대로 알고 사용하기 : NHN Cloud Meetup
REST API 제대로 알고 사용하기
meetup.toast.com
PUT vs PATCH Methods
흔히, API를 설계할 때, 자원을 수정하는 용도로 사용하는 PUT과 PATCH의 차이점을 알아보자.
PUT Method의
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.
- PUT은 요청한 URI에 자원이 존재하지 않는 경우, payload(request body)에 담긴 자원으로 새로운 자원을 생성한다.
- 자원이 요청한 URI에 자원이 존재하는 경우, 기존에 존재하는 자원을 payload의 자원으로 완전히 교체한다.
- PUT 사용의 좋은 예는 "좋아요" 또는 추천 등의 기능이다.
- Like 엔티티는 articleID, userID, type(좋아요/싫어요)를 상태로 가지고 있다.
- 유저가 좋아요를 누르면 payload에 담아 보낸 articleID, userID를 사용해 식별가능한 데이터가 있는지 확인한다.
- 데이터가 있으면, body에 담긴 type 정보로 수정하고
- 데이터가 없으면, payload에 담긴 정보들로 새로운 엔티티를 만들어 데이터베이스에 저장한다.
PATCH Method
This specification defines the new HTTP/1.1 [RFC2616] method, PATCH, which is used to apply
partial modifications to a resource.
- PATCH는 요청한 URI 자원이 존재하는 경우에만 작동하며, 자원의 일부분을 수정하기 위한 방법이므로, PUT과 같이 전체 entity 정보를 모두 body에 실어 보낼 필요가 없다.
- PATCH 사용의 예로, 게시글 수정의 경우를 생각할 수 있다.
- service에서 url에 포함된 articleID로 게시글 자원을 찾은 뒤, 전달받은 body의 내용을 해당 엔티티에 전달하면, 엔티티 안에서 자신의 상태를 변경한다.
두 방식의 차이점을 간단히 정리해보자면,
PUT Method를 사용하려면, client는 해당 자원의 상태를 모두 알고 있어야 한다.
- 요청 경로에 자원이 존재하면 이를 payload의 정보로 일괄 교체하기 때문이다.
- 또, 자원이 존재하지 않는다면, payload의 정보만으로 새로운 엔티티를 생성해야 하기 때문이다.
- 만약, payload의 정보가 불완전한 상태라면, 일부 entity field 값이 null로 변경될 수 있다.
PATCH Method의 경우, 해당 자원의 원하는 일부분만을 변경하기 때문에, payload에 자원의 모든 상태를 다 담아 보낼 필요가 없다.
- 자원을 생성/교체할 필요 없이, 일부만 수정하려고 하는 경우, PUT 방식보다 PATCH 방식이 더욱 적절하다.
자원을 수정하는 HTTP 메서드 - PUT vs PATCH
들어가며 웹 API를 설계할 때, 최대한 Http 표준을 따라서 용도에 맞는 Http Method를 사용해야 한다는 것은 아마 많은 개발자들이 인지하고 있을 것이다. 이번 글에서는 Http Method…
tecoble.techcourse.co.kr
'항해99_10기 > 105일의 TIL & WIL' 카테고리의 다른 글
| [3주차] [20221130] MongoDB 스키마 설계 (0) | 2022.11.30 |
|---|---|
| [3주차] [20221129] 에러 핸들링 (0) | 2022.11.29 |
| [2주차 WIL] 2022.11.21 ~ 2022.1126 회고 (0) | 2022.11.27 |
| [3주차] [20221127] for, for in, for of (0) | 2022.11.27 |
| [3주차][20221125] 동기, 비동기 vs 블로킹, 논블록킹 (0) | 2022.11.25 |