31
REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH http://link.koreatech.ac.kr

REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Embed Size (px)

Citation preview

Page 1: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

REST(REpresentational State

Transfer)

2012. 10

Youn-Hee HanLINK@KOREATECH

http://link.koreatech.ac.kr

Page 2: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

REST 의 개념 이해

LINK@KOREATECH 2

Page 3: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

What is REST?

REST (Representational State Transfer)– 대규모 네트워크 시스템을 위한 설계패턴 또는 아키텍처

– 웹을 기반으로 하는 대규모 네트워크 시스템 설계 및 구현을 위한 일종의 원칙들의 모음

– 2000 년 Roy Fielding 의 박사 학위 논문에서 처음 제안 .• Architectural Styles and the Design of Network-based Software

Architectures (DOCTOR OF PHILOSOPHY) http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

– 최근 추가된 뜻• XML 과 HTTP 를 사용하는 단순한 웹 기반 인터페이스를 지칭

( 즉 , REST 의 원칙을 따르는 Web Services)

LINK@KOREATECH 3

Page 4: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

What is REST?

왜 Representational State Transfer 이라고 명칭을 붙였나 ?

LINK@KOREATECH 4

All Resources on WEB are represented as XML by URL (Representation)

URL 표현( 다른 URL 포함 )

CLICK

Representational State Transfer 은 잘 디자인된 웹 어플리케이션이 어떻게 동작하는 지에 대한 이미지를 떠올리게 하기 위한 용어이다 .

즉 웹을 거대한 Virtual State Machine 이라고 생각하면 우리는 그 웹의 상태를 XML 등으로 표현된 것으로 확인할 수 있고 그 전에 알고 있던 또는 XML 에 포함된 링크를 선택 /호출함으로써 Machine 내에 존재하는 State 가 전이되고 새로운 표현 (New State Representation) 이 보여지게 된다

Page 5: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

What is REST?

좀 더 현실적인 REST 의 설명– Web Service 를 구현하는 기존 방식인 SOAP, XML-RPC 보다 매우

간단– 최근 Open API 구현에 많이 사용– 많은 웹 2.0 회사들이 Open API 의 구현 방법으로 많이 사용 .– 구글 , 플리커 , 아마존 등의 Open API 가 REST 방식으로 구현되어

공개– 서비스의 서버 플랫폼 구축에 있어 필수적인 아키텍쳐로 인식됨– REST 는 실제 표준은 아니지만 HTTP/URL/MIME Type 같은 웹

표준만을 사용– 구글이 오랫동안 제공해온 SOAP 기반 검색 API 서비스가 2006 년

12 월 5 일 부로 중단• 대신 구글은 REST 기반의 Ajax Search API 를 대안으로 제시

LINK@KOREATECH 5

Page 6: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

What is REST?

REST is not a standard – You will not see the W3C REST specification. – You will not see IBM or Microsoft or Sun selling a REST

developer's toolkit.

REST is just a design pattern – You can only understand it and design your Web services

according to its rules.

REST does prescribe the use of standards:– HTTP– URL– XML/HTML/JSON/GIF/JPEG/etc. (Resource

Representations)– text/xml, text/html, image/gif, image/jpeg, etc. (Resource

Types, MIME Types)

LINK@KOREATECH 6

Page 7: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

REST 의 성공 요인– 상태를 유지하지 않는 (Stateless) 클라이언트 /서버 구조를 가진다 .

– 작고 어디에서나 적용되는 인터페이스를 가진다 .

– GET, POST, PUT, DELETE• PUT 과 DELETE 메소드는 HTTP 스펙에는 존재하지만 지원하는

브라우저는 거의 없다 .

– 모든 자원은 URL 를 이용하여 유일하게 지칭될 수 있다 .

– 자원들의 표현 (Representation) 들이 URL 을 통해 서로 연결되어 있다 .

– REST 의 원칙에는 쿠키나 세션을 사용하지 않는다 .

What is REST?

LINK@KOREATECH 7

Page 8: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

URL 을 통해 필요한 자원을 계속해서 추적하여…– 얻어 (GET) 가거나– 생성 (POST) 하거나– 삽입 (PUT)– 삭제 (DELETE)할 수 있게 분류 설계한다 .

CRUD/HTTP 사이의 대응 – 전체 시스템은 단지 다음 4 개의 명령을 사용해서만 동작한다 .

CRUD Operations in REST

애플리케이션 작업 HTTP 명령

Create POST (non idempotent)

Read GET (safe, idempotent)

Update PUT (idempotent)

Delete DELETE (idempotent)

LINK@KOREATECH 8

Page 9: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

REST vs RPC-style (Java RMI, CORBA, DCOM, SOAP…)

REST URL– 서버 주소 /서비스 이름 /자원– Examples

• 잘 된 구성 - http://wisefree.com/employee/603045 (O)• 잘못 된 구성 - http://wisefree.com/employee/getEmployee?id=603045 (X)

REST vs. RPC (Remote Procedure Call)-style

LINK@KOREATECH 9

Page 10: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Web Design, Axiom 0(Tim Berners-Lee, director of W3C)

Axiom 0: all resources on the Web must be uniquely identified with a URI.

resource1URL1

resource2URL2

resource3URL3

LINK@KOREATECH 10

Page 11: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Example1: Airline Reservation Service

The airline wants to ensure that its premier members get immediate service, its frequent flyer members get expedited service and all others get regular service

There are two main approaches to implementing the reservation service…

LINK@KOREATECH 11

Page 12: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Approach 1

"Press 1 for Premier, Press 2 for…“– The airline provides a single telephone number. – Upon entry into the system a customer encounters an

automated message, "Press 1 if you are a premier member, press 2 if you are a frequent flyer, press 3 for all others."

Premier Members

Frequent Flyer Members

Regular Members

Airline ReservationsAnsweringMachine

PremierCustomer

Representative

F.F.Customer

Representative

RegularCustomer

Representative

LINK@KOREATECH 12

Page 13: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Approach 2

" Telephone Numbers are Cheap! Use Them!”– The airline provides several telephone numbers - one number

for premier members, a different number for frequent flyers, and still another for regular customers.

Premier Members

Frequent Flyer Members

Regular Members

1-800-PremierPremier

CustomerRepresentative

F.F.Customer

Representative

RegularCustomer

Representative

1-800-Frequent

1-800-Reservation

LINK@KOREATECH 13

Page 14: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Approach 2: URLs are Cheap! Use Them!

The airline provides several URLs - one URL for premier members, a different URL for frequent flyers, and still another for regular customers.

Premier Members

Frequent Flyer Members

Regular Members

client

client

client

http://www.kings-air/reservations/premier

http://www.kings-air/reservations/frequent-flyer

http://www.kings-air/reservations/regular

PremierMember

ReservationService

FrequentFlyer

ReservationService

RegularMember

ReservationService

LINK@KOREATECH 14

Page 15: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Approach 2 Advantages

The different URLs are discoverable by search engines and UDDI registries.

It's easy to understand what each service does simply by examining the URL.

There is no need to introduce rules. – Priorities are elevated to the level of a URL. – "What you see is what you get."

It's easy to implement high priority – simply assign a fast machine at the premier member

URL.

There is no bottleneck. – There is no central point of failure.

Consistent with Axiom 0.

LINK@KOREATECH 15

Page 16: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Three Fundamental Aspects of the REST Design Pattern

Resources– Every distinguishable entity is a resource.

• A resource may be a Web site, an HTML page, an XML document, or a Web service, etc.

URL can identify Resources– Every resource is uniquely identified by a URL. – This is Tim Berners-Lee Web Design, Axiom 0.

CRUD operations

Resources

URLs Simple Operations (CRUD)LINK@KOREATECH 16

Page 17: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

REST 방식의 웹서비스 구현 및 실습

LINK@KOREATECH 17

Page 18: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

REST 구현 방법

방법 1] Restlet 라이브러리 사용– 자바를 위한 경량화 REST framework– 오픈소스 프로젝트– 서블릿의 프로그래밍 모델을 기반

• JSR (Java Specification Requests) 311 Java API for RESTful Web Services ( 이하 JSR 311)

– Restlet 홈페이지• http://www.restlet.org

방법 2] Java EE 에서 지원하는 REST 라이브러리 사용– JAX-WS (Java API for XML Web Services) 라이브러리

• XML 과 웹 서비스 관련 API

– JAX-WS 의 핵심은 SOAP-WSDL 이여서 그다지 쓰이지 않았음 .– JAX-WS2 에서 HTTP 바인딩과 함께 REST 지원

LINK@KOREATECH 18

Page 19: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

REST 구현 방법

RESTlet 라이브러리 설치– http://www.restlet.org/downloads/stable (version 2.0.15)– Edition for Java SE

– D 드라이브의 특정 폴더에 압축 해제

LINK@KOREATECH 19

Page 20: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

REST 구현 방법

RESTlet 소스를 저장할 폴더로 이동

RESTlet 주요 라이브러리를 Java 의 CLASSPATH 에 추가– 소스 저장 폴더에 다음과 같은 두 개의 bat 파일 구성

• jc.bat

• j.bat

LINK@KOREATECH 20

javac -classpath "%CLASSPATH%;D:\0.MY_KUT_DATA\restlet-jse-2.0.15\lib\org.restlet.jar" %1

java -classpath "%CLASSPATH%;D:\0.MY_KUT_DATA\restlet-jse-2.0.15\lib\org.restlet.jar;." %1

Page 21: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Restlet Example-1

HelloWorld 예제 – Server

LINK@KOREATECH 21

import org.restlet.Server;import org.restlet.data.Protocol;import org.restlet.resource.Get;import org.restlet.resource.ServerResource;

public class RESTletHelloWorld extends ServerResource {

public static void main(String[] args) throws Exception { // Create the HTTP server and listen on port 8182 new Server(Protocol.HTTP, 8182, RESTletHelloWorld.class).start(); } @Get public String toString() { return “Hello, RESTlet World!"; } }

RESTletHelloWorld.java

컴파일 : jc RESTletHelloWorld.java

실행 : j RESTletHelloWorld

Page 22: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Restlet Example-1

HelloWorld 예제 – Client– 방법 1: 브라우저에서 http://localhost:8182/ 접속

– 방법 2

LINK@KOREATECH 22

import org.restlet.resource.ClientResource;

public class RESTletHelloWorldClient extends ClientResource { public static void main(String[] args) throws Exception { // Create the client resource ClientResource resource = new ClientResource("http://localhost:8182/"); // Write the response entity on the console resource.get().write(System.out); }}

RESTletHelloWorldClient.java

컴파일 : jc RESTletHelloWorldClient.java

실행 : j RESTletHelloWorldClient

Page 23: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Restlet Example-2

TextMessage 예제 – Server (1/2)

LINK@KOREATECH 23

import org.restlet.Application;import org.restlet.Request;import org.restlet.Response;import org.restlet.Restlet;import org.restlet.Server;import org.restlet.data.MediaType;import org.restlet.data.Protocol;

public class RESTInfoService extends Application { public static void main(String[] args) throws Exception { // Create the HTTP server and listen on port 8182 Server server = new Server(Protocol.HTTP, 8182); server.setNext(new RESTInfoService()); server.start(); }

RESTInfoService.java

Page 24: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Restlet Example-2

TextMessage 예제 – Server (2/2)

LINK@KOREATECH 24

public Restlet restlet = new Restlet() { @Override public void handle(Request request, Response response) {

String message = "Method : " + request.getMethod() + '\n' + "Resource URI : " + request.getResourceRef() + '\n' + "IP address : " + request.getClientInfo().getAddress() + '\n' + "Agent name : " + request.getClientInfo().getAgentName() + '\n' + "Agent version : " + request.getClientInfo().getAgentVersion();

response.setEntity(message, MediaType.TEXT_PLAIN); } };

@Override public Restlet createInboundRoot() { return restlet; }}

RESTInfoService.java

Page 25: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Restlet Example-3

Route 예제 – Server (1/3)

LINK@KOREATECH 25

import org.restlet.Application;import org.restlet.Request;import org.restlet.Response;import org.restlet.Restlet;import org.restlet.Server;import org.restlet.data.MediaType;import org.restlet.data.Protocol;import org.restlet.routing.Router;

public class RESTRouteService extends Application { public static void main(String[] args) throws Exception { // Create the HTTP server and listen on port 8182 Server server = new Server(Protocol.HTTP, 8182); server.setNext(new RESTRouteService()); server.start(); }

RESTRouteService.java

Page 26: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Restlet Example-3

Route 예제 – Server (2/3)

LINK@KOREATECH 26

public Restlet restlet1 = new Restlet() { public void handle(Request request, Response response) { String message = "This is a information for students"; response.setEntity(message, MediaType.TEXT_PLAIN); } }; public Restlet restlet2 = new Restlet() { public void handle(Request request, Response response) { String message = "<?xml version='1.0' encoding='UTF-8'?><students>

<student><id>1</id><url>/students/1</url></student><student><id>2</id><url>/students/2</url></student></students>";

response.setEntity(message, MediaType.TEXT_XML); } };

RESTRouteService.java

Page 27: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Restlet Example-3

Route 예제 – Server (3/3)

LINK@KOREATECH 27

public Restlet restlet3 = new Restlet() { public void handle(Request request, Response response) { String message = "<?xml version='1.0' encoding='UTF-8'?><student>

<id>1</id><name>Jun-Ha Jung</name><address>Seoul</address></student>";

response.setEntity(message, MediaType.TEXT_XML); } }; @Override public Restlet createInboundRoot() { Router router = new Router(); router.attach("http://localhost:8182/info", restlet1); router.attach("http://localhost:8182/students", restlet2); router.attach("http://localhost:8182/students/1", restlet3); return router; }}

RESTRouteService.java

Page 28: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Restlet Example-4

QueryString 예제 – Server (1/2)

LINK@KOREATECH 28

import org.restlet.Application;import org.restlet.Request;import org.restlet.Response;import org.restlet.Restlet;import org.restlet.Server;import org.restlet.data.MediaType;import org.restlet.data.Form;import org.restlet.data.Protocol;import org.restlet.routing.Router;

public class RestletQueryString extends Application { public static void main(String[] args) throws Exception { // Create the HTTP server and listen on port 8182 Server server = new Server(Protocol.HTTP, 8182); server.setNext(new RestletQueryString()); server.start(); }

RestletQueryString.java

Page 29: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

Restlet Example-4

QueryString 예제 – Server (2/2)

– 테스트 – 웹 브라우저로 접속• http://localhost:8182/query?num=10

LINK@KOREATECH 29

public Restlet restlet1 = new Restlet() { public void handle(Request request, Response response) { Form queryString = request.getResourceRef().getQueryAsForm(); String num = queryString.getValues("num"); String message = "<?xml version='1.0' encoding='UTF-8'?><num>"

+ num + "</num>"; response.setEntity(message, MediaType.TEXT_XML); } }; @Override public Restlet createInboundRoot() { Router router = new Router(); router.attach("http://localhost:8182/query", restlet1); return router; }}

RestletQueryString.java

Page 30: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

[ 실습 ]

REST 기반 계산기 프로그램 (1/3)– 클라이언트에서 호출할 URL 및 이에 대한 XML 응답

• http://localhost:8182/plus?num1=10&num2=9

• http://localhost:8182/substraction?num1=10&num2=9

LINK@KOREATECH 30

<?xml version='1.0' encoding='UTF-8'?><plus><num1>10</num1><num2>9</num2><solution>18</solution></plus>

<?xml version='1.0' encoding='UTF-8'?><substraction><num1>10</num1><num2>9</num2><solution>1</solution></substraction>

Page 31: REST (REpresentational State Transfer) 2012. 10 Youn-Hee Han LINK@KOREATECH

[ 실습 ]

REST 기반 계산기 프로그램 (2/3)– 클라이언트에서 호출할 URL 및 이에 대한 XML 응답

• http://localhost:8182/product?num1=10&num2=9

• http://localhost:8182/divide?num1=10&num2=9• http://localhost:8182/divide?num1=10&num2=0

LINK@KOREATECH 31

<?xml version='1.0' encoding='UTF-8'?><product><num1>10</num1><num2>9</num2><solution>90</solution></product>

<?xml version='1.0' encoding='UTF-8'?><divide><num1>10</num1><num2>9</num2><solution>1.111</solution></divide>

<?xml version='1.0' encoding='UTF-8'?><divide><num1>10</num1><num2>0</num2><solution>Error!</solution></divide>