restful web service

45
RESTful Web Service

Upload: sunguen-lee

Post on 12-Apr-2017

363 views

Category:

Internet


8 download

TRANSCRIPT

Page 1: Restful web service

RESTful Web Service

Page 2: Restful web service

REST(REpresentational State Transfer)

• The software architectural style of the World Wide Web.

• 현재의 아키텍처가 웹의 본래 설계의 우수성을 많이 사용하지 못하고 있다고 판단했기 때문에 , 웹의 장점을 최대한 활용할 수 있는 네트워크 기반의 아키텍처 제안

Page 3: Restful web service

Client-Server ModelSocket

• 높은 이식성 / 성능 , 세세한 제어• Boilerplate code, 구현 및 예외 처리의 어려움

Page 4: Restful web service

Client-Server ModelRPC(Remote Procedure Call)

• Network 통신 관련 작업은 몰라도 됨• IDL(Interface Definition Language) 활용• 원격지의 프로그램을 로컬 프로그램처럼 사용

Page 5: Restful web service

Client-Server ModelObject-Oriented RPC

• 분산 환경에서의 Remote Call

• CORBA: Common Object Request Bro-ker Architecture

• RMI: Remote Method Invocation

• DCOM: Distributed Component Object Model

Page 6: Restful web service

Client-Server ModelCORBA

• 로컬 / 원격을 포괄한 프로그램 객체 간의 메소드 호출 표준화에• 목적으로 OMG 에서 정의한 규격 .

• 다양한 언어 지원 .

Page 7: Restful web service

Client-Server ModelRMI/EJB

• 서로 다른 JVM 간의 메소드 호출을 지원 . • JAVA 만 지원 .

Page 8: Restful web service

Client-Server ModelCOM/DCOM/COM+

• COM 은 플랫폼 독립적…• 프로세스간 통신과 동적 오브젝트 생성이 가능 • 동일 OS 간 사용 ( 사실 윈도우 ..).

Page 9: Restful web service

Client-Server ModelRPC, CORBA, RMI, DCOM..

• 복잡성• 어려움• 보안• 성능• 호환성

Page 10: Restful web service

Client-Server ModelSOA(Service Oriented Architecture)

• 업무상에 일 처리에 해당하는 소프트웨어 기능을 서비스로 판단하여 그 서비스를 네트워크상에 연동하여 시스템 전체를 구축해 나가는 방법론• 공개 , 기민성 , 확장 , 연합 , 자립적 요소들로 구성된 조합 가능한 아키텍처 , 서비스 품질 , 다양한 벤더 , 상호 운영성 , 느슨한 연결 , 서비스 발견 그리고 잠재적으로 재사용 가능한 서비스들이 웹서비스로 구현

Page 11: Restful web service

Client-Server ModelSOAP(Simple Object Access Protocol)

• HTTP + XML, WSDL, UDDI• HTTP 에서 메시지 전달 Overhead• 엄격한 문법 및 고 난이도 개발

Page 12: Restful web service

The Constraints of REST• 클라이언트 - 서버 (Client-Server)

• 무상태 (Stateless)

• 캐시 (Cache)

• 균일한 인터페이스 (Uniform Interface)

• 계층 시스템 (Layered System)

• 주문형 코드 (Code-on-demand) - optional

Page 13: Restful web service

Client-Server• 웹의 일관된 인터페이스를 따른다는 전제하에 , 클라이언트와 서버는 독립적으로 구현 / 배포 되어야 함 .

Page 14: Restful web service

Stateless• 웹 서버가 클라이언트의 상태를 관리할 필요가 없어야 함 .

Page 15: Restful web service

Stateful vs Stateless

Page 16: Restful web service

Cache• 웹 서버가 응답 데이터마다 캐시 여부를 선언 할 수 있어야 함 .

Page 17: Restful web service

Uniform Interface• Identification of resources ( 자원 식별 )• Manipulation of resource through representations

( 표현을 통한 자원 처리 )• Self-descriptive messages ( 자기 서술적 메시지 )• HATEOAS (Hypermedia as the Engine Of Applica-

tion State)• 같은 인터페이스 제약에 따라 서로 일관성 있게 상호 운영 되어야 한다 .

Page 18: Restful web service

Identification of resources• 리소스란 웹 상에서 서로 구별되는 어떤 개념• 리소스는 유일하게 구별되어 저야 함 .• URI(URL,URN) 로 표현• http://www.my-domain.com/users/my-name

Page 19: Restful web service

Manipulation of resource through representations

• 클라이언트가 리소스 표현을 처리• 리소스는 다양한 방법으로 표현• 리소스 표현은 리소스와 상호작용 하는 방법

<xml> <user> <id>user-id</id> <name>user-name</name> </user></xml>

{ "user": { "id": "user-id", "name": "user-name" }}

Page 20: Restful web service

Self-descriptive messages• 요청을 처리하는데 필요한 모든 정보가 포함• 리소스의 요청 상태는 클라이언트의 요청 메시지로 , 리소스의 현재 상태는 서버의 응답 메시지로 처리• 메시지는 메타데이터를 포함하고 상태 , 표현 형식 , 크기 등 추가 정보를 전달GET /users/ user-id HTTP/1.1Host: http://www.mydomain.com/User-Agent: curlAccept: application/json

HTTP/1.1 200 OKContent-Type: application/jsonLocation: http://www.mydomain.-com/users/user-idContent-Length: 35

{ …}

Page 21: Restful web service

HATEOAS• 리소스의 상태 표현은 관련 리소스의 링크를 포함• 리소스 링크를 통한 State transitions ( 상태 전이 )• 리소스의 현재 상태에서 서버가 다음으로 할 수 있는 행위 제공• 절대적 표준은 없고 RFC4287,RFC5988 의 권고 사항 따름{ "user": { "id": "user-id", "name": "user-name" }}

{ "user": { "id": "user-id", "name": "user-name" }, “links” : [{ “rel” : “delete”, “href” : “http://~/users/user-id” }]}

Page 22: Restful web service

Richardson Maturity Model• Leonard Richardson 이 고안한 HTTP 전송 계층의 관점에서 REST 를 리소스 , 메소드 , 하이퍼미디어등의 용어로 쉽게 설명한 모델

Level 0단일 URI, 단일 메소드

Level 1다중 URI 기반의 리소스 , 단일 메소드

Level 2다중 URI 기반의리소스 및 메소드

Level 3HATEOAS

Level 0 : 원격 프로시저 호출POST 로 XML 데이터를 SOAP 이나 XML-RPC 전송

Level 1 : REST 리소스함수 파라미터 대신 REST URI 이용 , 리소스 분산

Level 2 : 추가 HTTP 메소드POST 외에 GET, HEAD, DELETE, PUT, REST 진정한 유스케이스

Level 3 : HATEOAS가장 성숙한 단계로 응답 속에 클라이언트가 취해야 할 액션 전달

Page 23: Restful web service

Chain of connected feeds

Page 24: Restful web service

Layered System• 웹의 일관된 인터페이스를 사용해서 , Proxy 또는 Gate-

way 같은 네트워크 기반의 중간매체를 사용 가능하도록 함 .

Page 25: Restful web service

Code-On-Demand• 유일한 선택사항으로 스크립트나 플러그인 같은 실행 가능한 프로그램을 클라이언트에 전송하여 , 클라이언트가 실행 가능 하도록 함 .

Page 26: Restful web service

REST Goals• Performance• Scalability• Simplicity• Modifiability• Visibility• Portability• Reliability

Page 27: Restful web service

REST Goals

Page 28: Restful web service

RESTful & RESTful API ?• REST 원리 ( 제약조건 ) 를 따르는 시스템• REST 구조적 스타일에 적합한 Web API

Page 29: Restful web service

Five Clues That Your API isn't RESTful

• It has a single endpoint - http://www.mydomain.com/api• All requests are POSTs - ~/users?query=select,insert,update,delete• Response metadata is in the body, not header - HTTP1.1 200 OK resultCode: 1400, message: “bad request”• There are verbs in the URL - /item/42/activate -> /item/42/status• The URL includes method names - ?action=getRecentItems -> ?action=modifyRecentItems

Page 30: Restful web service

HTTP MethodMethod DescriptionPOST Create or Execute functionGET SelectPUT Create or UpdateDELETE DeleteOPTION Get available MethodPATCH Update partial

Page 31: Restful web service

JAX-RS Implementations• Apache CXF - an open source Web service framework (JAX-RS 2.0)• Jersey - the reference implementation from Sun(now Oracle, JAX-RS 2.0)• RESTeasy - JBoss's implementation (JAX-RS 2.0)• Restlet - a lightweight, comprehensive, open source RESTful web API

framework for the Java platform. (JAX-RS 1.1)• Apache Wink - Apache Software Foundation Incubator project, the server

module implements JAX-RS• WebSphere - Application Server from IBM• WebLogic - Application Server from Oracle, see notes• Apache Tuscany - (http://tuscany.apache.org/documentation-2x/sca-java-

bindingrest.html)• Cuubez - framework (http://www.cuubez.com)• Everrest - Codenvy's Implementation• Jello-Framework - Java Application Framework optimized for Google App

Engine.• Dropwizard, Ninja Web Framework, Play Framework, RestExpress,

Restx, Spark Framework

Page 32: Restful web service

JAX-RS API

Page 33: Restful web service

Spring

Page 34: Restful web service

JAX-RS vs Spring• @Path specifies the relative path for a resource class or method. • - @RequestMapping• @GET, @PUT, @POST, @DELETE and @HEAD specify the HTTP request type of a resource. • - @RequestMapping(method)• @Produces specifies the response Internet media types (used for content negotiation). • - @RequestMapping(headers)• @Consumes specifies the accepted request Internet media types. • - @RequestMapping(headers)• @PathParam binds the method parameter to a path segment. • - @PathVariable• @QueryParam binds the method parameter to the value of an HTTP query parameter. • - @RequestVariable• @MatrixParam binds the method parameter to the value of an HTTP matrix parameter. • - @MatrixVariable• @HeaderParam binds the method parameter to an HTTP header value. • - @RequestHeader• @CookieParam binds the method parameter to a cookie value. • - @CookieValue• @FormParam binds the method parameter to a form value. • - @RequestParam• @DefaultValue specifies a default value for the above bindings when the key is not found. • - @RequestParam(defaultValue)• @Context returns the entire context of the object (for example @Context HttpServletRequest request). • - @ResponseStatus• @Provider binds the application components(data, exception mapping and context resolution) • - @ExceptionHandler

Page 35: Restful web service

Comparison

Page 36: Restful web service

Why use JAX-RS Implementations ?

• Java 표준 API• 구현체간 쉬운 포팅• Spring 3.2 이전에는 대안이 없었음• 여전히 Spring 에서 최신 스펙 지원 X

Page 37: Restful web service

Caching• Strong Caching Header - 리소스 요효시간 지정 ex) Expires, Cache-Control, max-age• Weak Caching Header - GET 요청을 날려 캐시로부터 아이템을 가져와야 할 지 판단하기 위한 정보 ex) Last-Modified, ETag

Page 38: Restful web service

JAX-RS Cache-Control

CacheControl cacheControl = new CacheCon-trol();cacheControl.setMaxAge(3600);cacheControl.setPrivate(true);cacheControl.setNoCache(true);

Response.ResponseBuilder responseBuilder = Response.ok();responseBuilder.cacheControl(cacheControl);

Page 39: Restful web service

Spring Cache-Control

<mvc:annotation-driven/><mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/api/**/*"/> <bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor"> <property name="cacheSeconds" value="0"/> <property name="useExpiresHeader" value="true"/> <property name="useCacheControlHeader" value="true"/> <property name="useCacheControlNoStore" value="true"/> </bean> </mvc:interceptor></mvc:interceptors>

* Spring 4.2 : org.springframework.http.CacheControl

Page 40: Restful web service

ETags(Entity Tag)Client Server

GET /users/1

200 OK ETag: “1”

GET /users/1 If-None-Match: ”1”

304 Not Modified

Time

No content

1. 클라이언트에서 /users/1 로 REST 리소스를 GET 요청2. 서버는 Etag 값 ( 예 : “1” 실제로는 MD5 해쉬값 ) 과 함께 200 OK 응답 코드 전송3. 잠시 후 클라이언트는 동일한 리소스를 한번 더 GET 으로 요청 이때 If-None-Match 헤더에 마지막으로 받은 ETag 값 동봉4. 서버는 해당 리소스의 해시값이 바뀌지 않았는지 체크하고 동일한 경우 304 Not-Modified 리턴

Page 41: Restful web service

JAX-RS ETagEntityTag et = new EntityTag("1");

Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(et);

if (responseBuilder != null) { return responseBuilder.build();}

responseBuilder = Response.ok();

return responseBuilder.tag(et).build();

Page 42: Restful web service

Spring ETag<web-app> … <filter> <filter-name>etagFilter</filter-name> <filter-class> org.springframework.web.-filter.ShallowEtagHeaderFilter </filter-class> </filter> <filter-mapping> <filter-name>etagFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>

Page 43: Restful web service

Types of ETags• Strong ETag : 강한 ETag검증 일치로 두 리소스가 바이트 단위 까지 일치하고

Content-Language 필드도 변경되면 안됨• Weak ETag : 약한 ETag검증 일치로

GET 요청과 ETag, IF-None-Match, 304-Not Modified만 사용

• HTTP 응답 시 Last-Modified, ETag 중 하나 • Expires, Cache-Control max-age 중 하나• 모두 설정할 경우 Etag 가 Last-Modified 보다 우선 , Cache-Control 이 Expires 보다 우선

Page 44: Restful web service

Rate Limiting Pattern• 클라이언트의 요청 개수를 제한 하기 위해

HTTP 429 Too Many Request 를 전달HTTP/1.1 429 Too Many RequestContent-Type: text/htmlRetry-After: 3600 X-RateLimit-Limit : 100X-RateLimit-Remaining : 10

• Rety-After : 재시도 요청 대기 시간 (초단위 )

• X-RateLimit-Limit : 일정 기간 동안 클라이언트가 요청 가능 수• X-RateLimit-Remaining : 현재 남이 있는 요청 가능 수

Rate Limit Filter

Client ServerRate

Limiting Filter

Request Request

Response

420 Error, Retry-After, X-RateLmit-Remaining

Page 45: Restful web service

Tools• cURL, Postman, Advaned Rest Client• Swagger(http://swagger.io/), APIDOC(

http://apidocjs.com/), I/O DOCS(http://www.mashery.com/api/io-docs)

• RAML(http://raml.org/), WRML(http://www.wrml.org), VISUALDIAGRAM(https://www.visual-paradigm.com), APISTUDIO(http://apistudio.io/)