2. REST
(REpresentational State Transfer)
• The software architectural style of the World
Wide Web.
• 현재의 아키텍처가 웹의 본래 설계의 우수성을 많이 사
용하지 못하고 있다고 판단했기 때문에, 웹의 장점을 최
대한 활용할 수 있는 네트워크 기반의 아키텍처 제안
10. Client-Server Model
SOA(Service Oriented
Architecture)
• 업무상에 일 처리에 해당하는 소프트웨어 기능
을 서비스로 판단하여 그 서비스를 네트워크상
에 연동하여 시스템 전체를 구축해 나가는 방법
론
• 공개, 기민성, 확장, 연합, 자립적 요소들로 구성
된 조합 가능한 아키텍처, 서비스 품질, 다양한
벤더, 상호 운영성, 느슨한 연결, 서비스 발견 그
리고 잠재적으로 재사용 가능한 서비스들이 웹
서비스로 구현
17. Uniform Interface
• Identification of resources (자원 식별)
• Manipulation of resource through representations (표
현을 통한 자원 처리)
• Self-descriptive messages (자기 서술적 메시지)
• HATEOAS (Hypermedia as the Engine Of Application
State)
• 같은 인터페이스 제약에 따라 서로 일관성 있게 상호 운
영 되어야 한다.
18. Identification of resources
• 리소스란 웹 상에서 서로 구별되는 어떤 개념
• 리소스는 유일하게 구별되어 저야 함.
• URI(URL,URN)로 표현
• http://www.my-domain.com/users/my-name
19. Manipulation of resource
through representations
• 클라이언트가 리소스 표현을 처리
• 리소스는 다양한 방법으로 표현
• 리소스 표현은 리소스와 상호작용 하는 방법
<xml>
<user>
<id>user-id</id>
<name>user-name</name>
</user>
</xml>
{
"user": {
"id": "user-id",
"name": "user-name"
}
}
20. Self-descriptive messages
• 요청을 처리하는데 필요한 모든 정보가 포함
• 리소스의 요청 상태는 클라이언트의 요청 메시지로, 리
소스의 현재 상태는 서버의 응답 메시지로 처리
• 메시지는 메타데이터를 포함하고 상태, 표현 형식, 크기
등 추가 정보를 전달
GET /users/ user-id HTTP/1.1
Host: http://www.mydomain.com/
User-Agent: curl
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
Location:
http://www.mydomain.com/users/user
-id
Content-Length: 35
{
…
}
21. 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”
}]
}
22. Richardson Maturity Model
• Leonard Richardson이 고안한 HTTP 전송 계층의 관점에
서 REST를 리소스, 메소드, 하이퍼미디어등의 용어로 쉽
게 설명한 모델
Level 0
단일 URI, 단일 메소드
Level 1
다중 URI 기반의 리소스,
단일 메소드
Level 2
다중 URI 기반의
리소스 및 메소드
Level 3
HATEOAS
Level 0 : 원격 프로시저 호출
POST로 XML 데이터를 SOAP이나 XML-RPC 전송
Level 1 : REST 리소스
함수 파라미터 대신 REST URI 이용, 리소스 분산
Level 2 : 추가 HTTP 메소드
POST 외에 GET, HEAD, DELETE, PUT,
REST 진정한 유스케이스
Level 3 : HATEOAS
가장 성숙한 단계로 응답 속에 클라이언트가
취해야 할 액션 전달
28. RESTful & RESTful API ?
• REST 원리(제약조건)를 따르는 시스템
• REST 구조적 스타일에 적합한 Web API
29. 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
30. HTTP Method
Method Description
POST Create or Execute function
GET Select
PUT Create or Update
DELETE Delete
OPTION Get available Method
PATCH Update partial
31. 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
34. 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
37. Caching
• Strong Caching Header
- 리소스 요효시간 지정
ex) Expires, Cache-Control, max-age
• Weak Caching Header
- GET 요청을 날려 캐시로부터 아이템을
가져와야 할 지 판단하기 위한 정보
ex) Last-Modified, ETag
40. 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 리턴
41. JAX-RS ETag
EntityTag et = new EntityTag("1");
Response.ResponseBuilder responseBuilder =
request.evaluatePreconditions(et);
if (responseBuilder != null) {
return responseBuilder.build();
}
responseBuilder = Response.ok();
return responseBuilder.tag(et).build();
43. 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 보다 우선
44. Rate Limiting Pattern
• 클라이언트의 요청 개수를 제한 하기 위해
HTTP 429 Too Many Request를 전달
HTTP/1.1 429 Too Many Request
Content-Type: text/html
Retry-After: 3600
X-RateLimit-Limit : 100
X-RateLimit-Remaining : 10
• Rety-After : 재시도 요청 대기 시간(초단위)
• X-RateLimit-Limit : 일정 기간 동안 클라이언트가 요청 가능 수
• X-RateLimit-Remaining : 현재 남이 있는 요청 가능 수
Rate Limit Filter
Client Server
Rate
Limiting
Filter
Request Request
Response
420 Error, Retry-After,
X-RateLmit-Remaining
Reprensentational -> 구상주의 : 구체적인 이미지나 상징을 표한하는 것(리소스를 표현한다는 의미)
ROA라고도 함
네트워크 아키텍처 원리'란 자원을 정의하고 자원에 대한 주소를 지정하는 방법
Hessian: Caucho가 제공하는 HTTP기반 경랑 바이너리 프로토콜
Burlap : XML기반 Hessian 대안 FactoryBean, ServiceExporter제공
JAX-RPC : 원격 지원 표준
JAX-WS : JAX-RPC의 상위 버전 Java EE5, Java SE6 지원
네트워크 아키텍처 원리'란 자원을 정의하고 자원에 대한 주소를 지정하는 방법
네트워크 아키텍처 원리'란 자원을 정의하고 자원에 대한 주소를 지정하는 방법
네트워크 아키텍처 원리'란 자원을 정의하고 자원에 대한 주소를 지정하는 방법
통신의 동작 상태를 정의하지 않고 항상 클라이언트로부터의 독립적인 request에 의해
서비스를 제공하는 서버를 stateless 서버라고 한다.
Note: Pronunciations of HATEOAS vary. Some people pronounce it as "hate-ee-os," similar to "hideous," or as "hate O-A-S". People also refer to it as a hypermedia-driven system.
Proxy - 웹 서버와 마찬가지로 HTTP 요청을 구성요소로 부터 받지만 웹서버와는 다르게 요청을 처리하지 않고 다른 서버, 프록시, 게이트웨이로 보내고 응답을 기다림.Gateway - HTTP와 다른 프로토콜 사이에서 중계하는 프록시.
swagger-editor : 스웨거 명세를 작성하게 도와주는 텍스트 에디터. http://editor.swagger.io/#/
swagger-ui: swagger api를 문서화 해서 보여주고 직접 rest api call도 해볼 수 있음http://petstore.swagger.io/
swagger-codegen : swagger 명세를 기반으로 각 언어로 소스 뼈대를 만들어줌. Java, Scala, node 등을 지원해 줌. 등이 있고, 잘 사용하면 유용하게 사용할 수 있다.
http://heidloff.net/article/usage-of-swagger-2-0-in-spring-boot-applications-to-document-apis/