REST(Representational State Transfer)는 월드 와이드 웹과 같은 분산 하이퍼미디어 시스템을 위한 소프트웨어 아키텍처의 한 형식이다. 이 용어는 로이 필딩(Roy Fielding)의 2000년 박사학위 논문에서 소개되었다. 그는 하이퍼텍스트 전송 프로토콜(HTTP)의 주요 저자들 가운데 한 사람이다. 그 뒤로 이 개념은 네트워킹 문화에 널리 퍼졌다.

엄격한 의미로 REST는 네트워크 아키텍처 원리의 모음이다. 여기서 네트워크 아키텍처 원리란 리소스를 정의하고 리소스에 대한 주소를 지정하는 방법에 대한 개괄을 말한다. 간단한 의미로는, 도메인 지향 데이터를 HTTP위에서 SOAP이나 쿠키를 통한 세션 트랙킹 같은 부가적인 전송 레이어 없이, 전송하기 위한 아주 간단한 인터페이스를 말한다. 이 두 가지의 의미는 당연히 겹치는 부분과 충돌되는 부분이 있다. 필딩의 REST 아키텍처 형식을 따르면 HTTP 프로토콜을 사용하지 않은 채로 또 월드 와이드 웹에서 전송하지 않고도 아주 커다란 소프트웨어 시스템을 설계하는것도 가능하다. 또한, 리모트 프로시저 콜을 이용하는 대신에 간단한 XML과 HTTP 인터페이스(REST 원리에 부합하지는 않지만)를 이용해 설계하는 것도 가능하다. 현실 세계에서의 REST 용어에 대한 이러한 두 가지 의미는 기술 토론에서 종종 혼란을 야기한다.

필딩의 REST 원리를 따르는 시스템은 종종 RESTful이란 용어로 지칭된다. 열정적인 REST 옹호자들은 스스로를 RESTafrians 이라고 부른다.

[편집]원리

REST의 지지자들은 웹이 몇 가지 핵심 설계 원칙의 직접적인 결과로서 확장성과 성장성을 갖게 되었다고 주장한다.

  • 응용 프로그램의 상태와 기능들은 리소스들로 나뉜다.
  • 모든 리소스는 하이퍼미디어 링크를 사용하는 공통 문법을 이용하여 유일한 방식으로 주소를 지정한다.
  • 모든 리소스들은 클라이언트와 리소스 사이의 상태 전송을 위한 유일한 인터페이스를 공유한다. 다음과 같이 이루어져 있다.
    • 잘 정의된(well-defined) 명령어들의 제약 집합.
    • 콘텐츠 종류와, 코드 온 디멘드를 부분적으로 지원하는 제약 집합
  • REST 아키텍처에 적용된 6가지 제한 조건 (개별 컴포넌트의 구현은 자유롭게 디자인할 수 있다)
    • 클라이언트/서버 구조 - 유니폼한 인터페이스로서 분리되어야 한다
    • 무상태(Stateless) - 각 요청 간 클라이언트의 컨텍스트가 서버에 저장되어서는 안된다
    • 캐시 처리 가능(Cacheable) - WWW에서와 같이 클라이언트는 응답을 캐싱할 수 있어야 한다.
      • 잘 관리되는 캐싱은 클라이언트-서버 간 interaction을 부분적으로 또는 완전하게 제거하여 scalability와 performance를 향상시킨다.
    • 계층화(Layered System) - 클라이언트는 보통 대상 서버에 직접 붙었는지, 또는 중간의 intermediary 서버와 붙었는지를 알 수 없다. Intermediary 서버는 로드 밸런싱을 가능하게 하거나 공유 캐시를 제공함으로써 시스템 scalability를 향상시키는 데 유용하다.
    • Code on demand (optional) - 자바 애플릿이나 자바스크립트의 제공을 통해 서버가 클라이언트가 실행시킬 수 있는 로직을 전송하여 기능을 확장시킬 수 있다.
    • Uniform Interface - 아키텍처를 단순화시키고 decouple시켜서 클라이언트, 서버 각 파트가 독립적으로 개선될 수 있도록 해준다.
  • REST 인터페이스의 원칙에 대한 가이드
    • 리소스의 구별
      • 개별적인 리소스는 요청에서 구별된다 - 웹 기반의 REST 시스템에서의 URI의 사용을 예로 들 수 있다. 리소스 그 자체는 클라이언트로 리턴되는 representation으로부터 개념적으로 분리되어 있다. 예를 들어, 서버는 그 데이터베이스를 전송하지 않는다, 단지 아마 어떤 데이터베이스 레코드를 나타내는 HTML, XML이나 JSON 등이 요청에서 구체적으로 요구되거나 서버의 구현에 따라서 예를 들어, 프랑스 어로, UTF-8로 인코딩되어 보내질 것이다.
    • 이들 representation을 통한 리소스의 조작
      • 클라이언트가 어떤 메타데이터가 첨부된 상태로 어떤 리소스의 representation을 가지고 있을 때, 만약 승인이 있다면, 서버에 있는 그 리소스를 변경 또는 삭제할 수 있는 충분한 정보를 가지고 있는 것이다.
    • 자기-서술적 메시지
      • 각 메시지는 자신을 어떻게 처리해야 하는지에 대한 충분한 정보를 포함해야 한다 - 예를 들어 어떤 파서를 불러야 하는지. 그 한 예는 MIME type과 같은 인터넷 미디어 타입의 사용을 들 수 있다. 미디어 타입만 가지고도, 클라이언트는 어떻게 그 내용을 처리해야할 지 알 수 있어야 한다. 메시지를 이해하기 위해 그 내용까지 살펴봐야 한다면, 그 메시지는 자기-서술적이 아니다. 예를 들어, 단순히 "application/xml"이라는 미디어 타입은, 코드 다운로드가 사용되지 않으면, 그 내용을 가지고 무엇을 해야할지에 대해 충분히 알려주지 못한다.
    • 애플리케이션의 상태에 대한 엔진으로서 하이퍼미디어
      • 만약에 클라이언트가 관련된 리소스에 접근하기를 원한다면, 리턴되는 representation에서 구별될 수 있어야 한다. 충분한 컨텍스트 속에서의 URI를 제공해주는 하이퍼텍스트 링크의 예를 들 수 있겠다.
  • REST 의 주요한 목표
    • 컴포넌트의 상호 연동 상의 확장성(scalability of component interactions)
    • 인터페이스의 범용성(Genrality of interfaces)
    • 컴포넌트의 독립적인 배포(Independent deployment of components)
    • 지연을 감소시키고, 보안을 강화하고, 레거시 시스템을 인캡슐레이션 시키는 중간 컴포넌트(Intermediary components to reduce latency, enforce security and encapsulate legacy systems)

[편집]같이 보기

[편집]바깥 고리






Representational state transfer (REST) or RESTful Web services are one way of providing interoperability between computer systems on the Internet. REST-compliant Web services allow requesting systems to access and manipulate textual representations of Web resources using a uniform and predefined set of stateless operations. Other forms of Web service exist, which expose their own arbitrary sets of operations such as WSDL and SOAP.[1] "Web resources" were first defined on the World Wide Web as documents or files identified by their URLs, but today they have a much more generic and abstract definition encompassing every thing or entity that can be identified, named, addressed or handled, in any way whatsoever, on the Web. In a RESTful Web service, requests made to a resource's URI will elicit a response that may be in XMLHTMLJSON or some other defined format. The response may confirm that some alteration has been made to the stored resource, and it may provide hypertext links to other related resources or collections of resources. Using HTTP, as is most common, the kind of operations available include those predefined by the HTTP verbs GET, POST, PUT, DELETE and so on. By making use of a stateless protocol and standard operations, REST systems aim for fast performance, reliability, and the ability to grow, by re-using components that can be managed and updated without affecting the system as a whole, even while it is running.

The term representational state transfer was introduced and defined in 2000 by Roy Fielding in his doctoral dissertation.[2][3] Fielding used REST to design HTTP 1.1 and Uniform Resource Identifiers (URI).[4][5][6] The term is intended to evoke an image of how a well-designed Web application behaves: it is a network of Web resources (a virtual state-machine) where the user progresses through the application by selecting links, such as /user/tom, and operations such as GET or DELETE (state transitions), resulting in the next resource (representing the next state of the application) being transferred to the user for their use.

History[edit source]

Roy Fielding speaking at OSCON 2008

REST was defined by Roy Fielding in his 2000 PhD dissertation "Architectural Styles and the Design of Network-based Software Architectures" at UC Irvine.[2] Fielding developed the REST architectural style in parallel with HTTP 1.1 of 1996–1999, based on the existing design of HTTP 1.0[7] of 1996.

In a retrospective look at the development of REST, Roy Fielding said:

Throughout the HTTP standardization process, I was called on to defend the design choices of the Web. That is an extremely difficult thing to do within a process that accepts proposals from anyone on a topic that was rapidly becoming the center of an entire industry. I had comments from well over 500 developers, many of whom were distinguished engineers with decades of experience, and I had to explain everything from the most abstract notions of Web interaction to the finest details of HTTP syntax. That process honed my model down to a core set of principles, properties, and constraints that are now called REST.[7]

Architectural properties[edit source]

The architectural properties affected by the constraints of the REST architectural style are:[2][8]

  • Performance - component interactions can be the dominant factor in user-perceived performance and network efficiency[9]
  • Scalability to support large numbers of components and interactions among components. Roy Fielding, one of the principal authors of the HTTP specification, describes REST's effect on scalability as follows:

REST's client–server separation of concerns simplifies component implementation, reduces the complexity of connector semantics, improves the effectiveness of performance tuning, and increases the scalability of pure server components. Layered system constraints allow intermediaries—proxiesgateways, and firewalls—to be introduced at various points in the communication without changing the interfaces between components, thus allowing them to assist in communication translation or improve performance via large-scale, shared caching. REST enables intermediate processing by constraining messages to be self-descriptive: interaction is stateless between requests, standard methods and media types are used to indicate semantics and exchange information, and responses explicitly indicate cacheability.[2]

  • Simplicity of a Uniform Interface
  • Modifiability of components to meet changing needs (even while the application is running)
  • Visibility of communication between components by service agents
  • Portability of components by moving program code with the data
  • Reliability is the resistance to failure at the system level in the presence of failures within components, connectors, or data[9]

Architectural constraints[edit source]

There are six guiding constraints that define a RESTful system.[8][10] These constraints restrict the ways that the server may process and respond to client requests so that, by operating within these constraints, the service gains desirable non-functional properties, such as performance, scalability, simplicity, modifiability, visibility, portability, and reliability.[2] If a service violates any of the required constraints, it cannot be considered RESTful.

The formal REST constraints are as follows:

Client-Server[edit source]

The first constraints added to our hybrid style are those of the client-server architectural style, described in Section 3.4.1. Separation of concerns is the principle behind the client-server constraints. By separating the user interface concerns from the data storage concerns, we improve the portability of the user interface across multiple platforms and improve scalability by simplifying the server components. Perhaps most significant to the Web, however, is that the separation allows the components to evolve independently, thus supporting the Internet-scale requirement of multiple organizational domains.[2]

Stateless[edit source]

The client–server communication is constrained by no client context being stored on the server between requests. Each request from any client contains all the information necessary to service the request, and session state is held in the client. The session state can be transferred by the server to another service such as a database to maintain a persistent state for a period and allow authentication. The client begins sending requests when it is ready to make the transition to a new state. While one or more requests are outstanding, the client is considered to be in transition. The representation of each application state contains links that may be used the next time the client chooses to initiate a new state-transition.[11]

Cacheable[edit source]

See also: Web cache

As on the World Wide Web, clients and intermediaries can cache responses. Responses must therefore, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients from reusing stale or inappropriate data in response to further requests. Well-managed caching partially or completely eliminates some client–server interactions, further improving scalability and performance.

Layered system[edit source]

See also: Layered system

A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load balancing and by providing shared caches. They may also enforce security policies.

Code on demand (optional)[edit source]

Servers can temporarily extend or customize the functionality of a client by the transfer of executable code. Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript.

Uniform interface[edit source]

The uniform interface constraint is fundamental to the design of any REST service.[2] The uniform interface simplifies and decouples the architecture, which enables each part to evolve independently. The four constraints for this uniform interface are

Identification of resources
Individual resources are identified in requests, for example using URIs in Web-based REST systems. The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server may send data from its database as HTMLXML or JSON, none of which are the server's internal representation.
Manipulation of resources through representations
When a client holds a representation of a resource, including any metadata attached, it has enough information to modify or delete the resource.
Self-descriptive messages
Each message includes enough information to describe how to process the message. For example, which parser to invoke may be specified by an Internet media type (previously known as a MIME type).[2]
Hypermedia as the engine of application state (HATEOAS)
Having accessed an initial URI for the REST application—analogous to a human Web user accessing the home page of a website—a REST client should then be able to use server-provided links dynamically to discover all the available actions and resources it needs. As access proceeds, the server responds with text that includes hyperlinks to other actions that are currently available. There is no need for the client to be hard-coded with information regarding the structure or dynamics of the REST service.[12]

Applied to Web services[edit source]

Web service APIs that adhere to the REST architectural constraints are called RESTful APIs.[13] HTTP-based RESTful APIs are defined with the following aspects:[14]

  • base URL, such as http://api.example.com/resources/
  • an internet media type that defines state transition data elements (e.g., Atom, microformats, application/vnd.collection+json,[14]:91–99 etc.) The current representation tells the client how to compose requests for transitions to all the next available application states. This could be as simple as a URL or as complex as a Java applet.[15]
  • standard HTTP methods (e.g., OPTIONS, GET, PUT, POST, and DELETE)[16]

Relationship between URL and HTTP methods[edit source]

The following table shows how HTTP methods are typically used in a RESTful API:

HTTP methods
Uniform Resource Locator (URL)GETPUTPOSTDELETE
Collection, such as http://api.example.com/resources/List the URIs and perhaps other details of the collection's members.Replace the entire collection with another collection.Create a new entry in the collection. The new entry's URI is assigned automatically and is usually returned by the operation.[17]Delete the entire collection.
Element, such as http://api.example.com/resources/item17Retrieve a representation of the addressed member of the collection, expressed in an appropriate Internet media type.Replace the addressed member of the collection, or if it does not exist, create it.Not generally used. Treat the addressed member as a collection in its own right and create a new entry within it.[17]Delete the addressed member of the collection.

The GET method is a safe method (or nullipotent), meaning that calling it produces no side-effects: retrieving or accessing a record does not change it. The PUT and DELETE methods are idempotent, meaning that the state of the system exposed by the API is unchanged no matter how many times the same request is repeated.

Unlike SOAP-based Web services, there is no "official" standard for RESTful Web APIs.[18] This is because REST is an architectural style, while SOAP is a protocol. REST is not a standard in itself, but RESTful implementations make use of standards, such as HTTPURIJSON, and XML.[18]

See also[edit source]



source - https://en.wikipedia.org/wiki/Representational_state_transfer








최근에 “Lorna Mitchell” 라는

“Five Clues That Your API isn’t RESTful (당신의 API가 RESTful 하지 않는 5가지 증거)”

의 내용을 기본으로 저의 견해를 덧붙여서 재구성 해봤습니다.


참고로 “Lorna Mitchell” 여성 PHP 개발자 이면서, 특히 API 디자인에 대해서

좋은 아이디어 와 글을 포스팅 하고 있습니다.

그녀의 블로그 :http://www.lornajane.net/


개인적으로 일을 하고 있는 도메인 특정상 많은 시스템  과 다양한 업체의

사람들 과 API 연동을 합니다.


“API 정의서“를 보면 서두에 “본 API 정의서는 RESTful 기반에…부랴부랴“로 시작을

합니다.

예전에는 “TCP/IP 기반 소켓 통신” 과 “RESTful“이 방식이 아닌

각자 회사 또는 팀에서 개별적으로 정의한 “HTTP/XML “를 사용을 했습니다.


하지만 최근에는 “RESTful” 아키텍쳐를 거의 대부분 사용을 하고 있습니다.

(물론 RESTful  방식이 기술이 아니고 API 디자인 아키텍쳐 입니다.  ^^)


하지만 막상 정의서의 연동 방식을 보면 “도대체 뭐가 RESTful”하게 설계를 했다는 거지?”

라는 의문점들이 생깁니다.


그래서 “100% RESTful 아키텍쳐링“을 다 지킬수는 없지만

최소한 아래에 “언급하는 5가지 디자인“에 대해서는 인식할 필요가 있습니다.


1. API의Endpoint가 오직 한개인가?

실제 경험한 사례로써 한번은 어떤 시스템의 연동 문서를 보니

“오직 한개의 URL로 fix” 되어 있었습니다.

예를 들어서 URL은 “http://example.com/rest” 이며, 모든 request는

해당 URL로 통합니다.


실제 자원에 대한 정보, 호출 서비스 정보, 파라미터 정보 등은 “XML 형태의 Body 데이터“로

전송 하도록 되어 있었습니다.


REST의 매우 중요한 구성 요소중 하나는 “Resource” 입니다.

“Resource”의 의미는 말 그대로 서비스를 제공 하는 시스템의 자원을 말합니다.

예를 들어서 “영화 예매 시스템“일 경우 “고객“, “예약번호“, “좌석번호“, “영화정보” 같은 것이며

대부분 명사(noun) 형태의 특성을 갖습니다.

또한 각 “Resource“는 “URL로 표시가 되며, 유일한 식별자“로써 표현 됩니다.


2. 모든 요청을 POST 방식으로만 요청 하는가?

“RESTful“에서 위에서 언급한 “Resource“를 핸드링하기 위해서 “HTTP의 전송 메서드”

를 사용합니다.

자원의 생성은 “POST“, 수정은 “PUT“, 조회는 “GET“, 삭제는 “DELETE” 메서드를 사용합니다.

예를 들면

예약 생성 : POST /reservation/2013012500001

예약 수정 : PUT /reservation/2013012500001

예약 조회 : GET /reservation/2013012500001

예약취소 : DELETE /reservation/2013012500001


하지만 실제 실무에서 이런 부분에 대해서 오해를 잘못해서

아래와 비슷한 방식으로 표현을 했었습니다.


예약 생성 : POST /reservation/2013012500001?cmd=insert

예약 수정 : POST /reservation/2013012500001?cmd=update

예약 조회 : POST /reservation/2013012500001?cmd=select

예약취소 : POST /reservation/2013012500001?cmd=delete


이와 같은 표현은 “RESTful“한 설계라고 할수 없습니다.


3. 응답에 대한 메타데이터를 Body에 포함 하는가?

“RESTful” 한 설계에서 “Request/Response“에 대한 메타 데이터는 최대한

HTTP 프로토콜의 방식을 준수 합니다.


클라이언트에서 요청 후 “처리 결과 값이 성공“일 경우 해당 시스템은

처리 결과를 “Body”에 포함하는 것이 아니고, HTTP Status의 값으로써

표현을 합니다.


저 같은 경우는 최대한 “Pure한 HTTP Status” 코드를 사용하고, 추가되는 부분은

별도로 “사용자 정의” 코드로 관리 합니다.


사용자 정보가 없을 경우는 : 404 (Not Found)

요청 정보가 정확하지 않을 경우 : 400 (Bad Request)

인증 실패 : 401 (UNAUTHORIZED)


즉, 이러한 전송에 대한 메타 데이터(결과 값, 세션 키)는 최대한 HTTP 헤더로

선언하고 실제 “Body 데이터“는 위에서 언급한 “Resource의 순수한 데이터”

만을 전송 해야 합니다.


4. URL에 동사(Verb)가 포함 되어 있는가?

위에서 언급 했듯이 “RESTful“한 API 설계에서 시스템에서 제공하는 것들은 “Resource“라고

말하며 “URL“로 표기 한다라고 말씀을 드렸습니다.

또한 이러한 “Resource“들은 “명사(noun)“적 특성을 같습니다.


만약 “URL“로 표기할때 동사(Verb)가 포함이 되면 혼돈이 올수 있습니다.

행위적 표현이기때문에 RPC(메서드)를 의미하는지 “Resource“를 하는지

구분이 모호해 집니다.


예를 들어서 예약 상태 정보를 조회를 하기 위해서 “/reservation/001/activate”

라는 표현 보다 “/reservation/001/status” 라고 표현을 해야 합니다.


5. URL에 RPC 호출 메서드 명이 있는가?

다양한 시스템 연동 스펙을 보면 아래 와 같이 실제 비지니스 컴포넌트

메서드를 URL에 포함되서 호출하는 경우가 있습니다.


?action=createReservation

?action=modifyReservation

?action=findReservation

?action=removeReservation


또한 URL에 노출되지는 않지만 “Body“안에 “XML” 형태로 선언 하는 경우도 있습니다.


하지만 “RESTful” 설계의 컨셉은 “RPC (Remote Procedure Call)” 목적이 아니고

시스템에서 제공하는 “Resource“를 “bucket“화 하는 것입니다.



My Thought

실제 실무에서 외부연동을 하면 “RESTful” 방식이라고 하지만 실제로는

위에서 언급한 5가지중 몇개를 지키지 않은 경우도 있고, 심지어 5개 모두

적용이 안되는 경우가 많습니다. 또한 HTTP/JSON/XML 통신만 하면

“RESTful” 하다고 생각들을 하는 것 같습니다.


개인적으로 아쉬운 부분은 약간의 시간을 내서 검토만 했었으면 어떨까 생각 듭니다.

그런데 필자도 말했지만 모든 연동 시스템이 반드시 “RESTful” 해야 하는 것인가?

에 대해서는 저는 약간 다른 생각을 합니다.


너무 유행이 되어 버려서 요새는 반드시 연동은 “RESTful“로 하려고 해서

오히려 시스템을 복잡하게 만들거나,  심지어 시스템 아키텍쳐가 흔들리는 경우도

있습니다.


2년전 제가 “일본 결제 시스템” 과 연동 한적이 있었습니다. 통신 방식은

“HTTP/XML” 이었습니다. 문서가 일본어로 되어 있어서 “번역기” 돌리고

추후에는 한글 번역본을 받아서 작업을 했는데..


연동 항목에 “Data Type, Length, Header 선언부, Null 유무” 등 깔끔하고

심플하면서, 쉽게 구성이 되었습니다.


구현은 어렵지 않았고 “결제 GW 테스트” 서버로 연동 테스트를 했는데

이해하고, 연동 테스트 하는데 3일정도 소요가 되었던것 같습니다.


반면 국내 다른 업체 연동을 할때 “RESTful” 방식으로 한다고 했는데

전혀 “RESTful” 하지도 않고 항목도 불명확해서 완전하게 테스트하는데

무려 한달이란 시간이 소요 되었고, 그 한달이란 기간이 정말 스트레스

엄청 받았었습니다.


또한 모든걸 “JSON“포맷으로 통신하는 것도 문제가 있습니다.

단말 <-> 서버는 “JSON” 포맷이 가볍고 좋을 수 있지만,

실제 “Server to Server” 연동은 가볍고, 빠른게 중요한게 아니라.

데이터의 정합성이 키포인트 입니다.


그럴 경우는 패캣이 다소 무거울수 있더라도 “XML” 포맷으로

해서 보내야 서로 비교 문석하기가 수월 합니다.


대량의 요청을 처리하는 서버는 하나의 바이트도 빼야 한다면

“A,B,C” 같은 토큰 방식으로 정의해서 보내야 하는 경우도 있습니다.


이렇듯 “연동 아키텍쳐링“을 할때


명분 없이 단지 “대세”라는 모호한 논리로 맞지도 않은 것을 도입하면

안된다고 생각 합니다.

저희는 개발자이고 아키텍트이기 때문에 “현 Usecase”에 맞는 것인지

냉정한 판단이 필요합니다.

“RESTful” 아키텍쳐는 “외부 OpenAPI“에 매우 적합한

연동 아키텍쳐인것 같습니다.

마지막으로 “차니 블로그“님께서 “API Strategy & Strata 2013 Conference” 참관기에서

했던 말을 남기며 본 글을 마무리 하겠습니다.


API 333 목표 : 3초만에 API를 이해하고, 30초만에 API 키를 발급 받아서, 

3분안에 첫번째 요청이 오도록 해라



source - https://beyondj2ee.wordpress.com/2013/03/21/%EB%8B%B9%EC%8B%A0%EC%9D%98-api%EA%B0%80-restful-%ED%95%98%EC%A7%80-%EC%95%8A%EC%9D%80-5%EA%B0%80%EC%A7%80-%EC%A6%9D%EA%B1%B0/






1. RPC에서 REST까지 간단한 개념소개 myrisinsun@gmail.com

2. •RPC •CORBA •RMI •SOAP •REST 이것들을 아주 아주 간단히 훑어볼거에요.

3. 시작하기전에.. Client-Server 모델 들어 보셨죠? 과거(?)에는
 Client가 Server에 있는 자료를
 요청하고, 받을때 주로 socket 프로그래밍을
 활용했습니다. CLIENT SERVER 주로.. LAN

4. socket 프로그래밍은..
 대부분의 프로그래밍 언어에서 
 API 형태로 제공을 합니다. 우리는 API Document의 사용법만 확인하고
 손쉽게 구현이 가능합니다. C socket.h JAVA java.net.Socket java.net.ServerSocket

5. server.java serverSocket = new ServerSocket(7000); socket = serverSocket.accept(); //TODO: socket으로부터 데이터를 받고, 보내고 socket.close(); serverSocket.close(); client.java socket = new Socket(’192.1.1.5’, 7000); //TODO: socket으로 데이터를 보내고, 받고 socket.close(); 위와같이 JAVA에서 제공하는 Class와 API를 이용해서
 간단한 코드만으로 작성이 가능합니다. 하지만..

6. 저런 코드가 정상 동작하려면..
 아래와 같은 상황이 보장되어야 합니다. • 네트워크는 언제나 빠르고 장애가 없음. • 서버는 클라이언트가 요청시 언제든 즉시 응답. • 클라이언트는 언제든 서버와 바로바로 연결 
 그러나 현실은..
 네트워크, 서버, 클라이언트 모두
 느려지고, 각종 문제가 발생할 수 있습니다.

7. 결국.. 발생 가능한 예외상황들을
 모두 예측을 하고
 대비(구현)해야만 합니다. 물론.. 그 모든것은 개발자의 몫!!

8. ServerClient 그래서(?) RPC가 등장합니다. RPC
 Remote Procedure Call 대략 이런 컨셉입니다. 프로그램A Client Stub
 
 프로그램B Server Stub (Skeleton) network 개발자가
 할일 RPC가 대신 해주는 일

9. 조금더 자세히 보자면.. Server에 있는
 프로그램 정보를 알고 있는 녀석(IDL)을
 활용해서 개발자는..
 network 통신과 관련된 작업은
 신경 쓰지 않아도 되고,
 원격지에 위치한 프로그램을
 로컬에 있는 프로그램처럼 사용 할 수 있습니다.
 
 
 IDL: Interface Definition Language

10. RPC에 대한 더 자세한 내용은
 아래 2개 링크를 추천. Introduction to Remote Procedure Call (RPC) - Abdelrahman Al-Ogail
 http://www.slideshare.net/ZiKaS/introduction-to-remote- procedure-call Remote Procedure Call - Roy Antony Arnold G
 https://middlewares.wordpress.com/2008/02/01/remote- procedure-call

11. 그리고 CORBA, RMI가 있습니다. CORBA: Common Object Request Broker Architecture
 로컬/원격을 포괄한 프로그램 객체 간의 메소드 호출 표준화에 목적으로 OMG에서 정의한 규격. 다양한 언어 지원. RMI: Remote Method Invocation
 서로 다른 JVM간의 메소드 호출을 지원. JAVA만 지원. 2가지 모두 RPC와 같이
 원격 프로그램을 로컬에 있는것처럼 사용가능 합니다.
 분산 환경에서의 remote call.

12. RMI, CORBA에 대한 설명은
 아래 링크 추천 RMI, CORBA and NetBeans - Sing Li
 http://www.developerfusion.com/article/84316/rmi- corba-and-netbeans Java RMI & CORBA. A comparison of two competing technologies
 http://www.javacoffeebreak.com/articles/rmi_corba 원격 객체 통신(RMI와 CORBA) - 윤경구
 http://www.javadom.com/tutorial/rmi-idl

13. 그런데
 RPC, RMI, CORBA를
 흔히? 볼수는 없습니다.
 (사실.. RPC와 그 개념은 여기저기서 사용 되고는 있습니다.) 왜일까?
 복잡성, 어려움, 보안, … 좀더 자세한 내용은 아래 링크를 추천 Why has CORBA lost popularity?
 http://stackoverflow.com/questions/3835785/why-has- corba-lost-popularity

14. 지금까지 본것처럼..
 socket을 활용해 통신을 하다가, 복잡한 네트워크와 하부영역에 대한
 캡슐화를 통해
 간단히(메소드, 펑션) 호출하려는 시도. 그리고,
 그다음은.. 우리에게 익숙한 
 web을 활용해보려는 시도로 이어집니다.

15. SOAP
 Simple Object Access Protocol 컨셉은 간단(?) 합니다. HTTP + XML 우리에게 익숙하고 각광받던 2가지 기술을 사용,
 간단히 ‘메세지’를 주고 받는것처럼 정보를 주고 받자. SOAP에서는 봉투(Envelope)라는 개념으로 부름. 간단한 그림으로 보면..

16. SOAP Simple Work Flow • Server는 서비스사용법(WSDL)을 작성해서 UDDI로 전송 • Client는 UDDI를 통해 서비스 목록을 확인(lookup)하고,
 사용법을 참고해서 메세지(SOAP형태)로 Server에게 요청. Client Server 서비스목록
 (UDDI) ……… ……lookup publish 요청 SOAP형식으로

17. 샘플 코드 보기 SOAP Message 예제
 http://ko.wikipedia.org/wiki/SOAP#SOAP_.EC.83.98.ED. 94.8C WSDL Document Example
 http://www.tutorialspoint.com/wsdl/wsdl_example.htm UDDI란?
 http://en.wikipedia.org/wiki/ Universal_Description_Discovery_and_Integration

18. 마지막으로 REST REST
 REpresentational State Transfer 그동안
 데이터의 요청/전달을 위해
 등장했던 기술들이 복잡하고 어려웠기에 우리에게 익숙한 web(HTTP)을
 있는 그대로 적용해보자는 시도.

19. REST를 간단히 정의해보자면 HTTP 1.1을 사용하며,
 URI를 자원(Resource)으로 표현하고
 처리결과를 Status Code로 사용하는 일종의 ‘스타일’을 뜻합니다. 그리고
 REST가 제안하는 스타일에 맞는다면
 RESTful하다 라고 말합니다.

20. HTTP 1.1 ? HTTP 1.0 에서는
 주로 get, post method를 사용했지만, HTTP 1.1 에서는 추가적으로
 put, delete method가 존재합니다. 그리고.. 다음과 같은 용도로 사용을 하게 됩니다. HTTP method CRUD (SQL) GET 조회 SELECT POST 등록 INSERT PUT 수정 UPDATE DELETE 삭제 DELETE

21. URI를 자원으로 표현? 쉽게 이야기하자면
 URI 에 동사없이
 명사(자원이름) 로만 구성을 해야합니다. 예를들면
 http://www.o.com/user/sunny/profile/address 참고로.. 위의 주소를
 get 방식으로 호출하면: 사용자 주소를 조회
 put 방식으로 호출하면: 사용자 주소를 수정
 delete 방식으로 호출하면: 사용자 주소 정보를 삭제

22. 처리결과를 Status Code 로 사용? 기존에는..
 http의 처리결과를
 header의 Status Code는 200 으로,
 그리고 body에 처리 결과를 작성. 하지만 REST에서는
 처리결과를 header의 Status Code를 활용. http
 header??
 body??

23. http로 전송되는 메세지의 구조 (request/response) Message Start-Line Header Field 공백줄 Message Body GET /user/sunny HTTP/1.1 Host: www.o.com Content-Length: 9 region=ko HTTP 1.1 404 Not Found Content-Length: 53 Content-Type: application/json Date: Mon, 26 Jan 2015 09:01:05 GMT { “ErrorDetail” : “사용자가 존재하지 않습 니다.” }

24. http 메세지 예제 /user/sunny 를 호출하지만, 존재하지 않는 사용자인 경우 GET /user HTTP/1.0 Host: www.o.com Content-Length: 12 userId=sunny HTTP 1.0 200 OK Content-Length: 55 Content-Type: text/html Date: Mon, 26 Jan 2015 09:01:05 GMT <html><body> 사용자가 존재하지 않습니다. </body></html> GET /user/sunny HTTP/1.1 Host: www.o.com Content-Length: 000 HTTP 1.1 404 Not Found Content-Length: 53 Content-Type: application/json Date: Mon, 26 Jan 2015 09:01:05 GMT { “ErrorDetail” : “존재하지 않는 사용자 정 보 입니다.” }

25. 그리고
 REST 방식을 사용할때(==RESTful 하게 구현할때) REST+XML 도 RESTful 입니다!
 다만, JSon이 용량도 적고 유용하기 때문에.. 마지막으로..
 RESTful 관련 추천링크입니다. 당신의 API가 RESTful 하지 않은 5가지 증거
 https://beyondj2ee.wordpress.com/2013/03/21/당신의-api 가-restful-하지-않은-5가지-증거


source - https://www.slideshare.net/WonchangSong1/rpc-restsimpleintro






'Web > Common' 카테고리의 다른 글

Adobe Flash  (0) 2012.05.11
색상표  (0) 2012.05.11
웹 어플리케이션(Web application)  (0) 2012.05.07
/favicon.ico 에 대해  (0) 2012.04.19
삼성 모바일OS '타이젠'…구글-모질라 제쳐  (0) 2012.04.08
Posted by linuxism
,