39
RESTful API 설계 Jinho Yoo

RESTful API 설계

Embed Size (px)

Citation preview

Page 1: RESTful API 설계

RESTful API 설계Jinho Yoo

Page 2: RESTful API 설계

바른 설계 원칙 : 생각 못한 미래의

재앙을 피하고자 쓰는 것

Page 3: RESTful API 설계

바른 설계 원칙:의사소통하는 비용이 적게

들어요.

“점 하나에서 일정 거리만큼 떨어진 점들의 집합을 그려봐"

VS

“원 하나 그려봐"

Page 4: RESTful API 설계

REST 아키텍쳐

● 웹(HTTP)의 공동 창시자 Roy Fielding의 2000년 박사

논문에 소개 됨.

● 기존의 웹이 HTTP의 장점을 100% 활용하지 못하고 있음

● 네트워크 아키텍쳐 (Not a protocol)

● De facto Standard

● 오픈 진영(Google ,Amazon) 에 의해서 주도 됨

Page 5: RESTful API 설계

구성 요소

구성 요소 내용 표현 방법

Resource 자원을 정의 HTTP URI

Verb 자원에 대한 행위를 정의 HTTP Method

Representations 자원에 대한 행위의 내용을 정의

HTTP Message Payload

Page 6: RESTful API 설계

GET/ POST/ PUT/ DELETE의 의미

Resource GET - read

POST - create

PUT- update

DELETE

/cars 자동차 ‘목록'을 넘겨준다.

새로운 차에 대한 정보를 생성한다.

모든 차들 정보를 한꺼번에 update

모든 차들을 다 지운다.

/cars/711 지정된 차에 대한 정보를 넘겨준다.

지원안됨 (405)

지정된 차의 정보를 update한다.

지정된 차의 정보를 삭제한다.

Page 7: RESTful API 설계

1. 복수명사로 쓰셔야 합니다

Resource GET - read

POST - create

PUT- update

DELETE

/cars 자동차 ‘목록'을 넘겨준다.

새로운 차에 대한 정보를 생성한다.

모든 차들 정보를 한꺼번에 update

모든 차들을 다 지운다.

/cars/711 지정된 차에 대한 정보를 넘겨준다.

지원안됨 (405)

지정된 차의 정보를 update한다.

지정된 차의 정보를 삭제한다.

Page 8: RESTful API 설계

왜?

● RESTful에서는 모든 개체를 ‘리소스'라는 단위로 표현 ● 보통 /{리소스 그룹명}/{리소스 ID}로 표현

○ Ex) /user/terry (사용자중에 테리란 인간)● REST는 이 리소스에 대한 CRUD(Create / Read / Update/

Delete)행위로 표현○ X: ‘Push message를 보낸다’○ O: ‘Push message를 생성한다.’

Page 9: RESTful API 설계

2. GET method와 query parameter는 상태를 바꾸면 안된다. ● 무언가 바꾸는 일에는 PUT, POST, DELTE를 대신 써라. ● GET을 Resource의 상태를 바꾸는 데 쓰지 마라.

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

상태를 가져오는 것이지 상태를 바꾸는 것이 아니다.

Page 10: RESTful API 설계

3. POST method와 query parameter는 상태를 읽는데 쓰면 안된다. ● 무언가 읽어오는 일에는 GET을 써라. ● 바꾸는 일에는 PUT, POST, DELTE를 대신 써라.

POST /users/711?activates or POST /users/711/activate

상태를 바꾸는 것이지 상태를 가져오는 것이 아니다.

Page 11: RESTful API 설계

POST로 안 읽어오면 argument다 보이고 보안에 취약하지 않아요? ● Argument로 인증정보를 날리려고 해서 문제.

○ RESTful API보안은 HTTP header에 인증정보를 넣고 HTTPS로 통신하는 것으로 해결해야 한다.

○ 대부분의 RESTful Server framework들이 이를 지원한다. ■ HTTP Basic authentification / OAUTH 2.0 등등…..

● 혹은 개발자가 GET/POST 따로 구현하기 싫어서 하는 소리이니 코드 리뷰나 문서 리뷰 때 문제 제기 할 것.○ 설계 원칙은 훗날 재앙을 막기 위한 것임을 기억하길.

Page 12: RESTful API 설계

4. Sub-resource를 관계 설정을 위해 사용하세요.

● GET /cars/711/drivers : Car 711을 모는 운전자들의 목록을 되돌려준다.

● GET /cars/711/drivers/4: Car 711의 #4 운전자에 대한 정보를 되돌려 준다.

자세한 내용은: Lez Hazlewood, Beautiful REST + JSON APIs

Page 13: RESTful API 설계

5. camelCase 로 이름을 지어주세요.ex)/api/v1/cars/XXXXX/engineNosle/XXXXXX

JavaScript도 그렇고 이 바닥에선 이게 표준입니다.

Page 14: RESTful API 설계

6. HATEOAS - RESTful application 설계의 제약

Hypermedia As The Engine Of Application State: link를 제공해서 탐색할 수 있게 해주는 것. (좋기는 한데, 나중에 의존성 문제가 생길 수 있어요..)

발음은 이렇게

Page 15: RESTful API 설계

예제:

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

GET /api/v1/cars/12312

Page 16: RESTful API 설계

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

Driver의 Link가 존재 :”더 자세한 정보를 알고 싶으면 이걸 열어보라.”라는 의미 (rel은 해당 resource와 link의

관계)

Page 17: RESTful API 설계

7.Filtering

● 전체 필드들을 요청하거나 혹은 filtering을 지원할 것

GET /cars?color=red : 빨간차 목록들 되돌려주기GET /cars?seats<=2 최대 좌석수가 2개인 차들

되돌려주기

Page 18: RESTful API 설계

8.Sorting

오름차순/내림차순 소팅이 여러 Field에 대해 되게 해줄 것.

GET /cars?sort=-manufactorer,+model

:menufactorrer는 내림차순으로, model은 오름차순으로 정리된 자동차 목록을 념겨준다.

Page 19: RESTful API 설계

9.Field selection

● 모바일 client는 그냥 몇 개 안되는 속성만 보여준다.● 필요한 속성만 짚어서 보여 달라 할 수 있게 API가 되어 있어야 한다.

● 이것이 네트워크 전송량을 줄이고 API를 쓰는 속도를 올려줄 것이다.

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

Page 20: RESTful API 설계

10.Paging

● 사용 limit와 offset. ● limit = 몇 개 보여줄지, offset = 몇 개 뒤부터 시작할 지.

(잘나가는 DB에는 다 있는 기능)● 보통은 limit=20, offset=0로 시작

GET /cars?offset=10&limit=5

TIP:사용자에게 전체 개수를 알려줘야 할 때는 custom HTTP header인: X-Total-Count로 줄 것

Page 22: RESTful API 설계

Paging - HTTP Header에 이렇게 줄 수도 있어요. 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",

Reference: https://developer.github.com/guides/traversing-with-pagination/

Page 23: RESTful API 설계

11. Version

‘V’로 시작하는 version을 URI에 붙여주세요.

/blog/api/v1

Page 24: RESTful API 설계

12.Error 처리 HTTP 상태 코드로 Error가 뭔지 알려주세요.

200 – OK – Eyerything is working201 – OK – New resource has been created204 – OK – The resource was successfully deleted304 – Not Modified – The client can use cached data400 – 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 authentication403 – 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.

Page 25: RESTful API 설계

Error처리 HTTP Status code와 같이 Error에 대한 정보를 같이 되돌려 주세요.{

"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"

} ]}

Page 26: RESTful API 설계

13.보안

● 절대 Session 사용하지 마세요.○ 의외로 아직도 이러는 분들 많아요. ○ Stateless에 위반됩니다. 매 Request마다 인증해야 합니다.

○ 자세한 내용은 여기 참고 ● HTTPS만 이용하세요.

○ 물론 Client가 미친 척 하는 놈이면….

Page 27: RESTful API 설계

보안-2: Basic HTTP authenficiation - Request

GET /accounts/x2b4jX3l31uiL HTTP/1.1Host: api.acme.comAuthorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Scheme name

SpaceScheme-specific Value

=Base64( API_KEY+’:’+API_SECRET)

Page 28: RESTful API 설계

보안-2: Basic HTTP authenficiation - Response

HTTP/1.1 200 OKContent-Type: application/json...{ “email”: “[email protected]”, “givenName”: “Joe”, “surname”: Smith”, ...}

Page 29: RESTful API 설계

보안-3: Oauth 1.0a

GET /accounts/1234 HTTP/1.1Host: api.acme.comAuthorization: OAuth realm="Photos",

oauth_consumer_key="dpf43f3p2l4k3l03",oauth_signature_method="HMAC-SHA1", oauth_timestamp="137131200",oauth_nonce="wIjqoS",

oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready", oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D"

Page 30: RESTful API 설계

보안-2: Oauth 2

GET /accounts/x2b4jX3l31uiL HTTP/1.1Host: api.acme.comAuthorization: Bearer mF_9.B5f-4.1JqM

Page 31: RESTful API 설계

보안-2: Oauth 2 MAC

GET /accounts/x2b4jX3l31uiL HTTP/1.1Host: api.acme.comAuthorization: MAC id="h480djs93hd8",nonce="264095:dj83hs9s”,mac="SLDJd4mg43cjQfElUs3Qub4L6xE="

Page 32: RESTful API 설계

문서화 & Test- Swagger ● 코드에 RESTful API에 대한

Annotation을 주면● JSON 형태로 문서를 만들어주고● /api-docs URL로 서버에 접속시 이 문서를 볼 수 있다.

● 동시에 손으로 Test도 가능. ● Demo: http://petstore.swagger.io/#/

○ Spring에서 Swagger 적용 예.

Page 33: RESTful API 설계

문서화 & Test- API Blueprint● https://apiblueprint.org/● Markdown과 유사한 방식으로

API에 대한 Spec을 손쉽게 작성.● Atom, Sublime plugin 지원● Apiary:API Blueprint를 가지고 실제 동작하는 문서와 Test page를 만들어 줌.

○ Demo

Page 34: RESTful API 설계

출처: 조대협, REST API 디자인

Page 35: RESTful API 설계

각 언어별 RESTful framework

● Java○ Spring ○ Jersey

● Node.js○ restify

● Python○ django REST framework○ flask-restful

● Ruby and Rails○ grape

앞서 만든 여러 설계 기준들을 다 직접 짜지 말고 이런 Framework들을 이용하시면 아주 쉽게 짤 수 있어요.

Page 36: RESTful API 설계

API관리 시스템 - ex) Google cloud endpoints

● Google app engine으로 Back-end를 작성 후 code에 필요한 Tag들을 붙여주면 아래의 기능들을 자동으로 붙여준다. ○ iOS, Android, JavaScript용 Client

library를 자동 생성. ○ Google Cloud Datastore, Google

Cloud Storage, Task Queue등 다양한 Google의 Back-end platform이용 가능

○ OAuth 2.0 인증 지원

Page 37: RESTful API 설계

API관리 시스템 - ex) Amazon API Gateway

● API의 수명 주기 관리● 자동 Traffic 제어 ● iOS, Android, JavaScript용 Client

library를 자동 생성● API 작업 모니터링 ● API key관리

Page 38: RESTful API 설계

GraphQL - RESTful API를 넘어서 ● 아예 RESTful API도 없이

JSON으로 된 Query를 넘기면 JSON으로 된 데이타를 넘겨주면 처리가 가능하게 하는 구조.

● Facebook이 밀고 있음.● 참고자료

Page 39: RESTful API 설계

Reference

● ThinkingMobile, 10 Best practice for Better RESTful API ● Lez Hazlewood, Beautiful REST + JSON APIs● Lez Hazlewood, Secure your REST API (the right way)● 조대협, REST API 디자인 ● https://spring.io/understanding/HATEOAS● Github API design, Traversing with pagenation● HTTP Authentication: Basic and Digest Access Authentication● Documenting a REST API with Swagger and Spring MVC