19
RESTful API Design Guide 김병부 (Benjamin Kim) [email protected] http://myboor.tistory.com

Restful API guide

Embed Size (px)

Citation preview

Page 1: Restful API guide

RESTful APIDesign Guide

김 병 부 (Benjamin Kim)[email protected]

http://myboor.tistory.com

Page 2: Restful API guide

Introspection

• Resource의 나열 – RESTful의 본질 외면– CRUD 제외한 operation 에 대한 어려움

– 수많은 Resource

• 보안상 문제점– Key exchange

– 메시지 암호화 X

– Error 메시지의 난립

– HTTP Resource에 노출된 정보들

• 통일된 Guide 없이 임기 응변

• OpenAPI가 될 수 없다.

Page 3: Restful API guide

Table of Contents

• RESTful API fundamental concept

• Use RESTful URLs and actions

• Error Handling

• Security

• HATEOAS (optional)

• Reference Link

Page 4: Restful API guide

RESTful API fundamental concept

• Resource– HTTP URL format

• Method– HTTP Standard Methods for CRUD

operations

– POST - Create

– GET - Read

– DELETE - Delete

– PUT - Update

• Message– XML, YAML, JSON and HTML format

HTTP POST, /instances

{

“instance” : {

“name” : “xmyboor001”,

“specId” : “x1.large”

}

}

Page 5: Restful API guide

Use RESTful URLs and actions #1

• 명사를 사용한다.

• 복수형을 사용한다.

• 구체적인 이름을 사용한다.– (O) HTTP GET /instances

– (O) HTTP GET /instances/1024

– (O) HTTP GET /instances/sdcconsoledb01

– (X) HTTP GET /instance

– (X) HTTP GET /instances?id=1024

– (X) HTTP GET /getInstance

• 예외상황– CRUD를 제외한 다른 명령어는 어떻게?

– E.g. Chef의 Role을 실행하는 경우

(O) HTTP POST /role/2048/run

(X) HTTP GET /role/run?instanceId=1024&roleId=2048

Page 6: Restful API guide

Use RESTful URLs and actions #2

• 리소스간 관계는 sub-resource를 사용한다.– HTTP GET /instances/1024/volumes/204

– HTTP POST / instances/1024/volumes

• Paging은 limit, offset 키워드를 사용한다. – Facebook Style

– HTTP GET /instances?offset=100&limit=30

• Partial Response (Optional)– Facebook Style

– HTTP GET /instances?field=instanceId,name

• ER Diagram– Table Instance and Volume

Page 7: Restful API guide

Use RESTful URLs and actions #3

Resource GETRead

POSTCreate

PUTUpdate

DELETE

/instances Returns a list of instances

Create a new Instance

Bulk update of instances

Delete all instances

/instances/1024 Returns a specificinstance

Method not allowed (405 error)

Updates a specificinstance

Delete a specificinstance

/instances/1024/volumes

Returns a list of volumes of theinstance

Create a new volume at the instance

Bulk update of volumes at the instance

Delete all volumes at the instance

/instances/1024/volumes/204

Return a specificvolume of the instance

Method not allowed (405 error)

Update a specific volume at the instance

Delete a specific volume at the instance

Page 8: Restful API guide

Use RESTful URLs and actions #4

• Searching– 파라미터 이름 ‘q’를 이용한다.

– q=name=myboor004,zone=qa&limit=30

– URLEncode 를 사용한다.

– HTTP GET /instences?q=name%3Dmyboor004,zone%3D=qa&limit=30

• Sorting – 파라미터 이름 ‘sort’ 를 이용한다.

– 기호 ‘-’ descending

– 기호 ‘+’ ascending

– HTTP GET /instences?sort=-instanceId,+

Page 9: Restful API guide

Use RESTful URLs and actions #5

• Version– Mandatory

– REST Resource에 정의하는 방법, HTTP Header에 정의 하는 방법 등이 있음

– Resource 에 정의 한다.

– HTTP GET /sdc/api/v1.0/instances

• HTTP headers for serialization formats– Client, Server 모두 format을 지정해야 한다.

– Format은 HTTP-Header의 context-type 을 사용한다.

– 기본적으로 JSON format을 사용한다.

Message Type Content-Type

JSON application/json

Page 10: Restful API guide

Use RESTful URLs and actions #6

• eXtended headers for REST API– 다음과 같은 customized 된 추가 헤더를 사용한다.

– Mandatory or 401 error

– Client Side

Header Name Description

X-NETMARBLE-LOGINID 로그인 아이디 정보

X-NETMARBLE-CHANNEL OpenAPI에 접속하는 Channel 정보

Page 11: Restful API guide

Error Handling #1

• Error 처리는 HTTP Status Code를 사용한다.

• 약 70여 개의 HTTP Status Code가 존재– http://en.wikipedia.org/wiki/Http_error_codes

• 다음과 같은 방식으로 HTTP Status Code를 사용한다.– 200 - OK : 성공 (동기식)

– 201 - OK : 성공 (비동기식)

– 400 - Bad Request : Parameter validation 실패, Json 포멧 에러

– 401 - Unauthorized : 인증 실패

– 403 – Forbidden : 인가 실패

– 404 - Not Found

– 410 - Gone : 요청된 resource가 더 이상 존재하지 않을때 발생하는 에러.

– 500 - Internal Server Error : 서버 측 에러

Page 12: Restful API guide

Error Handling #2

• Error Payload– HTTP Status code 만으로 충분한 메시지가 전달되기 힘들다.

– 서버에서는 다음과 같은 format으로 response body에 응답한다.

HTTP Status Code : 401

{

“status” : “401”,

“userMessage” : “Authentication Failure”,

“errorCode” : “30201”,

“errorInfo” : “http://sdn/wiki/errors/30201”

}

– 단 2XX code에서는 payload가 필요없다.

– Exception Stack 정보를 포함하지 않는다.

Page 13: Restful API guide

Security #1

• 인증 (Authentication)– REST API를 호출하는 대상을 확인하는 절차

• 인가 (Authorization)– REST API의 resource를 사용할 권한이 있는지 확인하는 절차

• 네트워크 레벨의 암호화– 네트워크 프로토콜 단의 암호화.

– HTTPS 를 사용한다.

• 메시지 무결성 보장– 메시지 변조를 방지하기 위해서, 메시지의 Hash Code를 비교하여 메시지 무결성을 확인

• 메시지 본문 암호화– 네트워크 레벨의 암호화를 사용 못하는 경우, 메시지 본문을 암호화한다.

Page 14: Restful API guide

Security #2

• Authentication– Basic Authentication 은 가능한 피한다. 계정와 암호를 Base64 인코딩하므로 디코딩 가능함.

– Token 방식의 digest algorithm – HMAC-SHA256

– Use OAuth 1.0a or Oauth 2

• API Key를 사용– Entropy

– Reduced Exposure

– Traceability

– Avoid Sessions

– Authenticate every request

Page 15: Restful API guide

Security #3

• API Access Token 인증방법– Use HTTPS

– Token exchange using Secure Cookie

https://www.owasp.org/index.php/SecureFlag

– Access token is valid within expireTime

– 조대협님 블로그 (http://bcho.tistory.com/955)

Page 16: Restful API guide

Security #4

• REST API Message Policy in Spring MVC– Controller, Service, Dao

– ValueObject – Table Record와 일치

> ValueObject 를 JSON 포멧으로 마샬링할 때,

중요한 데이터까지 사용자에게 노출된다.

– DomainObject for JSON Message

– Controller Layer에서 marshalling, unmarshalling 하기 위해서 Domain 객체를 사용한다.

Page 17: Restful API guide

HATEOAS (optional)

• HATEOAS– Hypermedia as the engine of application state

– HTTP Response에 다음 action에 관한 링크를 제공

– E.g. detail 링크를 제공하는 경우

– E.g. paging 링크를 제공하는 경우HTTP GET /instances?limit=30&offset=30

{

“rows” : [

{“instanceId” : 1024, “name” : “sdcconsoledb01”},

{“instanceId” : 1025, “name” : “sdcconsoledb02”}

],

“links” : [

{“rel” : “prev”, “href” : “http://sdc/instances?limit=30&offset=0”},

{“rel” : “next”, “href” : “http://sdc/instances?limit=30&offset=60”}

]

}

Page 18: Restful API guide

Reference Link

• http://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/

• http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api

• http://restful-api-design.readthedocs.org/en/latest/resources.html

• http://www.slideshare.net/stormpath/secure-your-rest-api-the-right-way

• http://bcho.tistory.com/914

• http://bcho.tistory.com/953

• http://bcho.tistory.com/955

Page 19: Restful API guide