1 / 31

REST ( RE presentational S tate T ransfer)

REST ( RE presentational S tate T ransfer). 2012. 10 Youn-Hee Han LINK@KOREATECH http://link.koreatech.ac.kr. REST 의 개념 이해. What is REST?. REST (Representational State Transfer) 대규모 네트워크 시스템을 위한 설계패턴 또는 아키텍처 웹을 기반으로 하는 대규모 네트워크 시스템 설계 및 구현을 위한 일종의 원칙들의 모음

donna-reese
Download Presentation

REST ( RE presentational S tate T ransfer)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. REST의개념 이해 LINK@KOREATECH

  3. 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

  4. What is REST? • 왜 Representational State Transfer 이라고 명칭을 붙였나? All Resources on WEB are represented as XML by URL(Representation) CLICK URL 표현(다른 URL 포함) Representational State Transfer은 잘 디자인된 웹 어플리케이션이 어떻게 동작하는 지에 대한 이미지를 떠올리게 하기 위한 용어이다. 즉 웹을 거대한 Virtual State Machine이라고 생각하면 우리는 그 웹의 상태를 XML등으로 표현된 것으로 확인할 수 있고 그 전에 알고 있던 또는 XML에 포함된 링크를 선택/호출함으로써 Machine내에 존재하는 State가 전이되고 새로운 표현 (New State Representation)이 보여지게 된다 LINK@KOREATECH

  5. 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

  6. 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

  7. What is REST? • REST의성공 요인 • 상태를 유지하지 않는 (Stateless) 클라이언트/서버 구조를 가진다. • 작고 어디에서나 적용되는 인터페이스를 가진다. • GET, POST, PUT, DELETE • PUT과 DELETE 메소드는 HTTP스펙에는 존재하지만 지원하는 브라우저는 거의 없다. • 모든 자원은 URL를 이용하여 유일하게 지칭될 수 있다. • 자원들의 표현(Representation)들이 URL을 통해 서로 연결되어 있다. • REST의 원칙에는 쿠키나 세션을 사용하지 않는다. LINK@KOREATECH

  8. CRUD Operations in REST • URL을 통해 필요한 자원을 계속해서 추적하여… • 얻어(GET) 가거나 • 생성(POST) 하거나 • 삽입(PUT) • 삭제(DELETE) 할 수 있게 분류 설계한다. • CRUD/HTTP 사이의 대응 • 전체 시스템은 단지 다음 4개의 명령을 사용해서만 동작한다. LINK@KOREATECH

  9. REST vs. RPC (Remote Procedure Call)-style • 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) LINK@KOREATECH

  10. Web Design, Axiom 0(Tim Berners-Lee, director of W3C) • Axiom 0: all resources on the Web must be uniquely identified with a URI. resource1 URL1 resource2 URL2 resource3 URL3 LINK@KOREATECH

  11. 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

  12. 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 Customer Representative Premier Members F.F. Customer Representative Answering Machine Airline Reservations Frequent Flyer Members Regular Customer Representative Regular Members LINK@KOREATECH

  13. 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 Customer Representative 1-800-Premier Premier Members F.F. Customer Representative 1-800-Frequent Frequent Flyer Members Regular Customer Representative 1-800-Reservation Regular Members LINK@KOREATECH

  14. 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 Member Reservation Service http://www.kings-air/reservations/premier client Premier Members Frequent Flyer Reservation Service http://www.kings-air/reservations/frequent-flyer client Frequent Flyer Members Regular Member Reservation Service http://www.kings-air/reservations/regular client Regular Members LINK@KOREATECH

  15. 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

  16. 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

  17. REST 방식의 웹서비스 구현 및 실습 LINK@KOREATECH

  18. 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

  19. REST 구현 방법 • RESTlet 라이브러리설치 • http://www.restlet.org/downloads/stable (version 2.0.15) • Editionfor Java SE • D 드라이브의 특정 폴더에 압축 해제 LINK@KOREATECH

  20. REST 구현 방법 • RESTlet 소스를 저장할 폴더로 이동 • RESTlet 주요 라이브러리를 Java의 CLASSPATH에 추가 • 소스 저장 폴더에 다음과 같은 두 개의 bat 파일 구성 • jc.bat • j.bat 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 LINK@KOREATECH

  21. Restlet Example-1 • HelloWorld 예제 – Server RESTletHelloWorld.java 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!"; } } 컴파일: jc RESTletHelloWorld.java 실행: j RESTletHelloWorld LINK@KOREATECH

  22. Restlet Example-1 • HelloWorld 예제 – Client • 방법 1: 브라우저에서 http://localhost:8182/ 접속 • 방법 2 RESTletHelloWorldClient.java 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); } } 컴파일: jc RESTletHelloWorldClient.java 실행: j RESTletHelloWorldClient LINK@KOREATECH

  23. Restlet Example-2 • TextMessage 예제 – Server (1/2) RESTInfoService.java 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(); } LINK@KOREATECH

  24. Restlet Example-2 • TextMessage 예제 – Server (2/2) RESTInfoService.java 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; } } LINK@KOREATECH

  25. Restlet Example-3 • Route 예제 – Server (1/3) RESTRouteService.java 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(); } LINK@KOREATECH

  26. Restlet Example-3 • Route 예제 – Server (2/3) RESTRouteService.java 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); } }; LINK@KOREATECH

  27. Restlet Example-3 • Route 예제 – Server (3/3) RESTRouteService.java 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; } } LINK@KOREATECH

  28. Restlet Example-4 • QueryString 예제 – Server (1/2) RestletQueryString.java 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(); } LINK@KOREATECH

  29. Restlet Example-4 • QueryString 예제 – Server (2/2) • 테스트 – 웹 브라우저로 접속 • http://localhost:8182/query?num=10 RestletQueryString.java 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; } } LINK@KOREATECH

  30. [실습] • REST 기반 계산기 프로그램 (1/3) • 클라이언트에서 호출할 URL 및 이에 대한 XML 응답 • http://localhost:8182/plus?num1=10&num2=9 • http://localhost:8182/substraction?num1=10&num2=9 <?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> LINK@KOREATECH

  31. [실습] • 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 <?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> LINK@KOREATECH

More Related