티스토리 뷰

1. 명사를 사용하고, 동사는 사용하지 말라

이해하기 쉽게 모든 리소스에 대해 아래 구조를 사용하라

Resource GET
read
POST
create
PUT
update
DELETE
/cars Returns a list of cars Create a new car Bulk update of cars Delete all cars
/cars/711 Returns a specific car Method not allowed (405) Updates a specific car Deletes a specific car

 

동사는 사용하지마라

 

/getAllCars
/createNewCar
/deleteAllRedCars

 

2. GET 메서드와 쿼리 파라미터로 상태를 변경하면 안된다

상태를 변경하려면 GET 메서드 대신 PUT, POST, DELETE 메서드를 사용하라.

상태변경을 위해 GET 메서드를 사용하지마라

GET /users/711?activate or
GET /users/711/activate

 

3. 복수형 명사를 사용하라

단수형과 복수형을 섞어서 사용하지마라. 간단하게 유지하고 모든 자원에 오직 복수형 명사만 사용하라.

 

/cars instead of /car

/users instead of /user

/products instead of /product

/settings instead of /setting

 

4. 관계에 서브리소스를 사용하라

리소스가 또다른 리소스와 관계가 있다면 서브리소스를 사용하라

GET /cars/711/drivers/ Returns a list of drivers for car 711

GET /cars/711/drivers/4 Returns driver #4 for car 711

 

5. 시리얼라이즈 형식에 HTTP 헤더를 사용하라

클라이언트와 서버 둘다 통신에 사용하는 포맷을 알아야한다. 포맷은 HTTP 헤더에 명시되어야한다.

 

Content-Type은 request 포맷을 정의한다.

Accept는 처리가능한 response 포맷리스트를 정의한다.

 

6. HATEOAS를 사용하라

Hypermedia as the Engine of Application State(HATEOAS)는 API를 통해 보다나은 내비게이션을 만들기위해 hypertext link를 사용해야한다는 원칙이다.

 

{
	"id": 711,
	"manufacturer": "bmw",
	"model": "X5",
	"seats": 5,
	"drivers": [{
	  "id": "23",
	  "name": "Stefan Jauker",
	  "links": [{
	   "rel": "self",
	   "href": "/api/v1/drivers/23"
	  }]
	}]
}

 

7. Collections에 대한 필터링, 정렬, 필드선택, 페이징을 제공하라.

Filtering:

모든 필드에 대한 고유한 쿼리 파라미터를 사용하거나 필터링을 위한 쿼리 랭귀지를 사용하라.

 

GET /cars?color=red Returns a list of red cars

GET /cars?seats<=2 Returns a list of cars with a maximum of 2 seats

 

Sorting(정렬):

여러 필드에 대해 오름차순, 내림차순 정렬을 허용하라

 

GET /cars?sort=-manufactorer,+model

manufacturers로 내림차순, model로 오름차순 정렬된 리스트를 반환한다.

 

Field selection:

모바일 클라이언트는 단지 몇가지 속성만 리스트에 표현한다. 리소스의 모든 속성이 필요하지않다. API 소비자에게 필드를 선택할수있는 능력을 부여하라. 또한 네트워크 트래픽을 줄이고, API의 사용속도를 향상시킬것이다.

 

GET /cars?fields=manufacturer,model,id,color

Paging:

limit과 offset을 사용하라. 이는 사용자에게 유연하고 데이터베이스에서 일반적이다. 기본값은 limit=20, offset=0 이다.

 

GET /cars?offset=10&limit=5

전체 항목을 다시 사용자에게 전달하기위해선 custom HTTP 헤더 X-Total-Count 를 사용하라.

 

다음, 이전 페이지에 대한 링크를 HTTP 헤더로 제공하라. 자신이 URL을 생성하는것보다 이 링크를 따르는게 중요하다.

 

Link: <https://blog.mwaysolutions.com/sample/api/v1/cars?offset=15&limit=5>; rel="next",

<https://blog.mwaysolutions.com/sample/api/v1/cars?offset=50&limit=3>; rel="last",

<https://blog.mwaysolutions.com/sample/api/v1/cars?offset=0&limit=5>; rel="first",

<https://blog.mwaysolutions.com/sample/api/v1/cars?offset=5&limit=5>; rel="prev",

 

8. API version

API 버전을 필수로 만들고 버전없는 API는 릴리즈하지마라. 간단한 숫자를 사용하고, 2.5같은 점 표기법(dot notation)을 피하라.

우리는 v로 시작하는 API 버전을 사용하고있다.

 

/blog/api/v1

 

9. HTTP status code 에러 처리

에러처리를 무시하는 API는 작업하기 어렵다. 순수하게 stacktrace로 HTTP 500을 반환하는건 도움이 되지않는다.

 

HTTP status code 사용

HTTP 표준은 70개가 넘는 반환값을 제공한다. 우리는 다 필요하지는 않지만 최소 10개는 사용해야한다.

 

200 – OK – Eyerything is working
201 – OK – New resource has been created
204 – OK – The resource was successfully deleted

 

304 – Not Modified – The client can use cached data

 

400 – Bad Request – The request was invalid or cannot be served. The exact error should be explained in the error payload. E.g. „The JSON is not valid“
401 – Unauthorized – The request requires an user authentication
403 – Forbidden – The server understood the request, but is refusing it or the access is not allowed.
404 – Not found – There is no resource behind the URI.
422 – Unprocessable Entity – Should be used if the server cannot process the enitity, e.g. if an image cannot be formatted or mandatory fields are missing in the payload.

 

500 – Internal Server Error – API developers should avoid this error. If an error occurs in the global catch blog, the stracktrace should be logged and not returned as response.

 

에러 응답 사용

모든 에러는 에러응답에 매핑되어야한다. 다음은 JSON 응답이 어떻게 나타나야하는지 예이다.

 

{
"errors": [{
  "userMessage": "Sorry, the requested resource does not exist",
  "internalMessage": "No car found in the database",
  "code": 34,
  "more info": "http://dev.mwaysolutions.com/blog/api/v1/errors/12345"
 }]

 

10. HTTP method 오버라이딩 허용

일부 프록시는 POST와 GET만 허용한다. 이런 한계로 REST API를 지원하려면, API가 HTTP method를 오버라이드하는 방법이 필요하다.

custom HTTP 헤더 X-HTTP-Method-Override를 사용하여 POST method를 오버라이드하라.

 

원문: https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함