SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
http://obeautifulcode.com made with
REST (representational state transfer)
GET /the/party?what=started
Ā© 2014 Suraj Gupta
http://obeautifulcode.com
Why Learn REST?
REST can help you build client-friendly distributed systems that are
simple to understand and simple to scale.
In other wordsā€¦
ā—¦ Clients rely on services that behave according to conventions.
Services are flexible to client needs. And the grammar is
straightforward ā€“ clients talk to services fluently.
ā—¦ Devs can grok how the pieces fit together without too much mental
acrobatics. Notice ā€œsimpleā€ and ā€œdistributedā€ in the same sentence.
ā—¦ Scale becomes more about ā€œadd another web serverā€ and less
about ā€œrethink the entire modelā€
Ā© 2014 Suraj Gupta 2
http://obeautifulcode.com
REST Should Feel Familiar
ā—¦ REST is a style, not a standard
ā—¦ REST was used to design HTTP.
ā—¦ Youā€™ve probably used/seen things like:
ā—¦ URIs, URLs
ā—¦ Hypertext
ā—¦ Accept:text/html
ā—¦ 200 OK, 400 Bad Request
ā—¦ GET, PUT, POST
ā—¦ But HTTP can also be used in non-RESTful way. Many SOAP services use
HTTP simply to transport data between two endpoints. HTTP has a rich
set of (often ignored) features that support RESTful design.
Ā© 2014 Suraj Gupta 3
http://obeautifulcode.com
There are 5 Major Concepts
Ā© 2014 Suraj Gupta 4
Resources Representations
Operations Hypertext Statelessness
and of course they are ā€œfancy-soundingā€
http://obeautifulcode.com
Resources
ā—¦ Every ā€œthingā€, every ā€œresourceā€ gets an identifier:
/game/robots/four-hand-george
/game/spaceships/destoyers/98
ā—¦ The URL is the unified concept of an identifier on the web
ā—¦ A URI identifies a resource by location, name, or both
ā—¦ A URL is a subset of URI. It specifies where a resource lives and the mechanism to retrieve it.
ā—¦ four-hand-george, the robot, is a ā€œthingā€, You can retrieve him using HTTP and he is located
here: http://obeautifulcode.com/game/robots/four-hand-george
ā—¦ So an ISBN number is a URI but not a URL (it unambiguously identifies a book, but does not
define where or how to retrieve it)
ā—¦ REST says to identify everything that is worth being identified by your clients.
ā—¦ This leads to creation of resources not typically seen in application design. For
example, a process or process step, a sale, a negotiation or a request for quote.
/game/spaceships/upgrades/56789
/game/negotations/truces/12345
Ā© 2014 Suraj Gupta 5
http://obeautifulcode.com
Resources
ā—¦ Collections of things merit identification. They are things themselves:
/game/robots (all robots)
/game/spaceships?visability=invisible (all spaceships that are invisible)
ā—¦ Resources can be static or change over time:
/game/robots/four-hand-george (might always return the same information about a particular robot)
/game/spaceships/upgrades/567
(the status of spaceship upgrade is likely to change over time and the upgrade itself may be deleted after it is complete)
ā—¦ The same resource can be referred to by more than one URI:
/game/robots/four-hand-george
/game/spaceships/987/crew/four-hand-george (george identified as a crew-member of spaceship #987)
/game/robot-factory/output/123 (george identified as the output #123 of the robot factory)
ā—¦ Use the full URI namespace for identity. Donā€™t identify things using a method (operation) + parameters approach.
For example, this is not really an identifier:
/cgi-bin/getGameObject?type=robot&name=four-hand-george
ā—¦ An identifier should not contain tech implementation details (e.g. cgi-bin). Those may change over time.
ā—¦ Some benefits of URIs in the ā€œidentifierā€ style:
ā—¦ Highly readable
ā—¦ Easy to debug
ā—¦ Easy for clients to construct
Ā© 2014 Suraj Gupta 6
http://obeautifulcode.com
Representations
ā—¦ How does a client know what to do with the data it receives when it
fetches a URL?
ā—¦ RESTful systems empower clients to asks for data in a form that they
understand.
ā—¦ Hereā€™s an HTTP header. A web browser would send this to a web server on
your behalf:
GET /pages/archive HTTP/1.1
Host: obeautifulcode.com
Accept: text/html
ā—¦ The type/form/representation of data requested is specified as a MIME
type (e.g. text/html). There are over 1000 standard MIME types.
ā—¦ So instead of requesting HTML, a client could request a resource,
represented as XML, JSON, or some other format the client understands.
Ā© 2014 Suraj Gupta 7
http://obeautifulcode.com
Representations
ā—¦ Developers frequently define different URLs for different representations of the same resource:
http://notRest.com/reports/2015/quarter/3/sales.html
http://notRest.com/reports/2015/quarter/3/sales.xml
http://notRest.com/reports/2015/quarter/3/sales.xls
ā—¦ REST says to create one identifier that can be rendered in different forms
GET /reports/2015/qtr/3/sales HTTP/1.1
Host: obeautifulcode.com
Accept: application/vnd.ms-excel
ā—¦ Some devs donā€™t realize that things can be abstracted from their representations. Like other kinds
of abstraction, this one is worthwhile because it makes life simpler for the client.
ā—¦ There has been a historic lack of tooling; redundant resources was in-part explained by developer
convenience. But modern web frameworks leave us with no excuses.
ā—¦ If the server doesn't support particular MIME type, the server can inform the client about this via a
standard error (HTTP 406)
ā—¦ The benefit of supporting a rich ecosystem of negotiable data is that you create long-lived, flexible
systems that favor the client, not the developer.
Ā© 2014 Suraj Gupta 8
http://obeautifulcode.com
Operations
ā—¦ Traditional app development focuses on operations:
GetRobots()
FlyShip(id=ā€œship-123ā€, destination=Planets.Mars)
ā—¦ Services broadcast their operations (e.g. WSDL) and clients sync-up with them.
ā—¦ There are no conventions; operation names follow the devā€™s style guidelines (if one event exists)
and documentation is needed to determine the side-effects of calling an operation.
ā—¦ REST defines 4 standard operations (HTTP calls these verbs):
ā—¦ GET: retrieve a representation of the resource
ā—¦ PUT: create a resource at a known URI or update an existing resource by replacing it
ā—¦ POST: create a resource when you donā€™t know URI, partial update of a resource, invoke arbitrary processing
ā—¦ DELETE: delete a resource
ā—¦ You perform one of these standard operations on a resource:
GET /robots/four-hand-george in XML
POST to /robots to create a new robot
ā—¦ All resources support one of more of these operations.
Ā© 2014 Suraj Gupta 9
http://obeautifulcode.com
Operations
ā—¦ When we treat resources as things to manipulate via a URL and we restrict ourselves to a small set
of operations, there is less need to extensively describe a service.
ā—¦ It's not about the 50 things you can do with a particular service (which is how SOAP developers
view the world). It's about using a standard set of things you can do (PUT, GET, etc.) with a set of
resources (robots, spaceships, flightpaths, etc.)
ā—¦ So how do you FlyShip(id=ā€œship-123ā€, destination=Planets.Mars)?
PUT to /ships/ship-123/flightpath and send ā€œdestination=marsā€ in the body of the message
Now you can poll that URI using GET for flight updates.
or
POST to /ships/ship-123/flightpaths and send ā€œ/planets/marsā€ in the body of the message. The server
might return something like /ships/ship-123/flightpaths/456 to indicate that the ship is now flying to Mars and
that a new flightpath resource was created to track it. You can poll that URI using GET for flight updates.
ā—¦ Instead of defining a new operation such as StopFlight(id) to stop the flight, do this:
DELETE /ships/ship-123/flightpaths/456
ā—¦ How does a web browser know what to do with a URL? All resources support the same operations,
and GET is one of them. The browser GETs until everything has been gotten!
Ā© 2014 Suraj Gupta 10
http://obeautifulcode.com
Operations ā€“ Safe v. Idempotent
ā—¦ Further, there are rules about the effect that standard operations can have
on a RESTful service. Clients can expect that services will follow the rules,
they donā€™t need to be spelled out by the service.
ā—¦ A safe method does not modify resources.
ā—¦ An idempotent operation has no additional effect if it is called more than
once with the same input parameters.
ā—¦ Idempotent operations are used in the design of network protocols, where
a request to perform an operation is guaranteed to happen at least once,
but might also happen more than once. There is no harm in performing
the operation two or more times.
ā—¦
Ā© 2014 Suraj Gupta 11
http://obeautifulcode.com
Operations - Rules
ā—¦ GET:
ā—¦ Safe and Idempotent ā€“ it modifies nothing and there is no adverse when called multiple times.
ā—¦ You can get google.com repeated and it will not change the Google homepage.
ā—¦ DELETE:
ā—¦ Not Safe, but Idempotent ā€“ it modifies resources, but there is no additional effect when called multiple times.
ā—¦ DELETE /ships/ship-123/flightpaths/456 stops the flight the first time it is called.
ā—¦ Subsequent calls are ignored by the server.
ā—¦ PUT:
ā—¦ Not Safe, but Idempotent ā€“ it modifies resources, but there is no additional effect when called multiple times with the same
parameters.
ā—¦ PUT to /ships/ship-123/flightpaths with a body of ā€œdestination=marsā€ creates a flight.
ā—¦ Subsequent calls to that URI with the same body have no effect on the system. The ship is already headed to Mars.
ā—¦ POST:
ā—¦ Not Safe, Not Idempotent ā€“ it modifies resources and multiple calls will cause additional effect on the system.
ā—¦ POST to /ships/ship-123/flightpaths with ā€œ/planets/marsā€ in the body creates the flight
ā—¦ Service returns a resource to track it: /ships/ship-123/flightpaths/456.
ā—¦ Subsequent POST, even with the same body, create new resources such as /ships/ā€¦/ship-123/flightpaths/457,
ā€¦/458, etc. If you keep POSTing, the shipā€™s flight manifest might fill up!
ā—¦ Server can send an error code saying that a flight to Mars is already in progress or that you have to DELETE one flight before
creating another.
Ā© 2014 Suraj Gupta 12
http://obeautifulcode.com
Hypertext
ā—¦ Here is some made-up XML:
<robot self='http://obeautifulcode.com/game/robots/123' >
<age>3</age>
<money ref='http://obeautifulcode.com/game/bank/accounts/567' />
<lastBattle ref='http://obeautifulcode/game/battles/890' />
</robot>
ā—¦ Applications can "follow" links to retrieve more information about the robot, such as the robotā€™s
last battle.
ā—¦ Web-servers publish hypertext so that web-browsers know what to do next (i.e. get one page, fetch
all the links and displaying them. When users clicks on a link, rinse and repeat)
ā—¦ In REST, application state is transferred and discovered within hypertext responses.
re-read the line above!
ā—¦ A REST client needs less knowledge about how to interact with any particular service compared to
clients that interact with operation-centric services.
ā—¦ A client transitions through application states by selecting from links. So RESTful interaction is
driven by hypermedia, not out-of-band information.
Ā© 2014 Suraj Gupta 13
http://obeautifulcode.com
Statelessness
ā—¦ REST mandates that state either be turned into resource state, or kept on the client. The client is
responsible for application state. The server is responsible for resource state.
ā—¦ The server should not retain some sort of communication state for any client it communicates with
beyond a single request. This is whatā€™s meant when we say that REST is ā€œstatelessā€
ā—¦ For example:
ā—¦ The client knows that its strategy is to deploy a robot when the spaceship reaches Mars.
ā—¦ The server is keeping track of resources such as Mars, the spaceship, the robot on the spaceship (also itā€™s
age, etc.), other robots in the universe.
ā—¦ The client call poll the flight to Mars until it has completed. The completed flight resource will contain
hypertext to inform the client about other resources it can now access.
ā—¦ At no point does the clientā€™s strategy get stored in the server. Also, the server doesnā€™t attempt to remember
the clientā€™s last 10 moves just to facilitate gameplay. That kind of state is not codified in a resource, so it
must be maintained by the client.
ā—¦ Letā€™s say the game server goes down and is immediately replaced by a new one. The game isnā€™t over. The
old server kept nothing in-memory about the clientā€™s state-of-play. The serverā€™s responsibility is to restore
the state of all resources in the universe (e.g. a particular spaceship with a particular robot is now sitting on
Mars). The clientā€™s responsibility is to know where it is and to make its next move.
Ā© 2014 Suraj Gupta 14
http://obeautifulcode.com
Statelessness - Benefits
ā—¦ Client are isolated against changes on the server.
ā—¦ Statelessness promotes redundancy. Clients are not dependent on talking to the same server in
two consecutive requests. If a server goes down, just load balance clients to other servers.
ā—¦ Statelessness unlocks performance:
ā—¦ Slap a reverse proxy in front of the server.
ā—¦ The proxy sit between a client and server and caches the serverā€™s responses.
ā—¦ The responses are simply associated with the URI ā€“ no complex algos needed.
ā—¦ Requests for a cached URI can be handled by the proxy instead of the server.
ā—¦ Proxies remove stuff from cache after some server specified elapsed time or if thereā€™s a PUT operation
(cached resource is being replaced)
ā—¦ HTTP reverse proxies have been around forever. They are time-tested and used all over the internet to
cache HTML and other requests.
Ā© 2014 Suraj Gupta 15
http://obeautifulcode.com
Errors
ā—¦ HTTP has a well-defined set of status codes for responses, some of which indicate
an error.
ā—¦ The status codes are grouped in categories. For example, 200 OK and 204 No
Content are in the 2xx category which indicates that the action requested by
the client was received, understood, accepted and processed successfully.
ā—¦ Clients doesnā€™t necessarily need to handle each and every individual code.
ā—¦ An error can be augmented with more details about what caused the error simply
by including text in the body of the response.
ā—¦ So when throwing and handling errors, RESTful systems converse using a well-
known standards.
ā—¦ Error handling becomes less about the idiosyncratic preferences of developers (is
that service going to throw InvalidOperationExeption, ArgumentException, or
AppSpecificException?). This means less documentation needed and less service-
specific error handling code.
Ā© 2014 Suraj Gupta 16
http://obeautifulcode.com
Common Objections to REST
ā—¦ Rest is usable for CRUD, but not for "real" business logic:
ā—¦ Any computation that returns a result can be transformed into a URI that identifies the result.
ā—¦ x = sum(2,3) might become http://example.com/sum/a=2&b=3
ā—¦ This is NOT a misuse of REST. Here the URI still represents a resource and not an operation - namely it
identifies the result of adding 2 and 3 together.
ā—¦ Using GET to retrieve the result might be a good idea - this is cacheable, you can reference or bookmark it,
and computing it is safe and not too costly
ā—¦ There is no formal contract/no description language like WSDL:
ā—¦ 95% of what we usually describe using WSDL for is not tied to WSDL at all, but rather is concerned with XML
Schema complex types that are defined. REST with XML supports XML Schema.
ā—¦ The most common use case for service descriptions is to generate stubs and skeletons for the service
interface. Clients use this to code against the service. This is not documentation, because WSDL tells you
nothing about the semantics of an operation, it just lists the operation names and parameters.
ā—¦ With REST, you can provide documentation via HTML. For example, when client requests HTML for a
resource you can return documentation for that resource, and when client requests, say, XML, then you can
fetch the resource itself.
Ā© 2014 Suraj Gupta 17
http://obeautifulcode.com
Common Objections to REST
ā—¦ REST does not support transactions
ā—¦ REST services are likely to interact with a database that supports transactions in the same way other SOA
environments would. The only change is that, with REST, you are likely to create transactions explicitly
yourself.
ā—¦ Things differ when you combine transactions in larger units. SOAP can be used to propagate a transaction
context using SOAP headers.
ā—¦ But loose coupling and transactions, especially those of the ACID variety, donā€™t jive. The fact that you are
coordinating a commit across multiple independent systems creates a pretty tight coupling between them.
ā—¦ No publish/subscribe (pub/sub) support - In REST, notification is done by polling. The client can poll
the server. GET is extremely optimized on the web.
ā—¦ No asynchronous interactions
ā—¦ Given HTTP's request/response model, how does one achieve async communication? How do you deliver a
request from client to server where the process takes a long time? How does consumer know when
processing is done?
ā—¦ HTTP code 202 (Accepted) means "the request has been accepted for processing, but the process has not
been completed"
ā—¦ The server can return a URI of a resource which the client can GET to access the results.
Ā© 2014 Suraj Gupta 18
http://obeautifulcode.com
The Reality of REST
ā—¦ REST says nothing about how to maintain resource state. The implementation
details and complexity is yours to own.
ā—¦ If a system requires that the client create many different kinds of resources (robots
and spaceships and 100 more things), REST might not be the right approach.
ā—¦ REST is not a good solution for a real-time system or bandwidth-constrained
environments (e.g. mobile apps). Because resources are the central concept in
REST and REST disallows a client and a server to share state, the client winds up
interacting with lots of URIs over-the-wire. HTTP uses a request/response model,
so thereā€™s a lot of baggage flying around the network to make it all work.
ā—¦ Because REST is not a standard, people and frameworks adhere to the principles to
varying degrees. Like other architectural paradigms that are this broad in scope,
the REST community has purists and pragmatists.
Ā© 2014 Suraj Gupta 19
http://obeautifulcode.com
Reference
This deck borrows from work by Stefan Tilkov, Brian
Sletten, Gregor Roth, Jim Webber, Savas Parastatidis, and
Ian Robinson which was published on March 2010 in
Issue #1 of ā€œInfoQ Explores RESTā€
In some cases I have used their text verbatim.
The publication is available here:
http://www.infoq.com/minibooks/emag-03-2010-rest
Ā© 2014 Suraj Gupta 20
http://obeautifulcode.com
Thank You!
This deck is part of a blog post found here:
made with
Please Send Feedback!
post to blog comments
-or-
email to surajg at gmail
Follow me: Twitter - Google+ - Newsletter
Ā© 2014 Suraj Gupta
http://obeautifulcode.com/API/Learn-REST-In-18-Slides

Weitere Ƥhnliche Inhalte

Was ist angesagt?

REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
Ā 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST APIAniruddh Bhilvare
Ā 
Introduction to REST - API
Introduction to REST - APIIntroduction to REST - API
Introduction to REST - APIChetan Gadodia
Ā 
Rest api-basic
Rest api-basicRest api-basic
Rest api-basicAmila Sampath
Ā 
The Internet as Web Services: introduction to ReST
The Internet as Web Services: introduction to ReSTThe Internet as Web Services: introduction to ReST
The Internet as Web Services: introduction to ReSTBruno Kessler Foundation
Ā 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsStormpath
Ā 
Rest api standards and best practices
Rest api standards and best practicesRest api standards and best practices
Rest api standards and best practicesAnkita Mahajan
Ā 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
Ā 
API Design- Best Practices
API Design-   Best PracticesAPI Design-   Best Practices
API Design- Best PracticesPrakash Bhandari
Ā 
REST and RESTful Web Services
REST and RESTful Web ServicesREST and RESTful Web Services
REST and RESTful Web ServicesKasun Madusanke
Ā 
Introduction to API
Introduction to APIIntroduction to API
Introduction to APIrajnishjha29
Ā 
REST-API overview / concepts
REST-API overview / conceptsREST-API overview / concepts
REST-API overview / conceptsPatrick Savalle
Ā 

Was ist angesagt? (20)

Web api
Web apiWeb api
Web api
Ā 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
Ā 
RESTful API - Best Practices
RESTful API - Best PracticesRESTful API - Best Practices
RESTful API - Best Practices
Ā 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Ā 
Introduction to REST - API
Introduction to REST - APIIntroduction to REST - API
Introduction to REST - API
Ā 
Rest api-basic
Rest api-basicRest api-basic
Rest api-basic
Ā 
The Internet as Web Services: introduction to ReST
The Internet as Web Services: introduction to ReSTThe Internet as Web Services: introduction to ReST
The Internet as Web Services: introduction to ReST
Ā 
Rest API
Rest APIRest API
Rest API
Ā 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
Ā 
Rest web services
Rest web servicesRest web services
Rest web services
Ā 
Rest api standards and best practices
Rest api standards and best practicesRest api standards and best practices
Rest api standards and best practices
Ā 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
Ā 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
Ā 
Express js
Express jsExpress js
Express js
Ā 
Rest api and-crud-api
Rest api and-crud-apiRest api and-crud-api
Rest api and-crud-api
Ā 
API Design- Best Practices
API Design-   Best PracticesAPI Design-   Best Practices
API Design- Best Practices
Ā 
REST and RESTful Web Services
REST and RESTful Web ServicesREST and RESTful Web Services
REST and RESTful Web Services
Ā 
What is an API
What is an APIWhat is an API
What is an API
Ā 
Introduction to API
Introduction to APIIntroduction to API
Introduction to API
Ā 
REST-API overview / concepts
REST-API overview / conceptsREST-API overview / concepts
REST-API overview / concepts
Ā 

Ƅhnlich wie Learn REST in 18 Slides

Rest Introduction (Chris Jimenez)
Rest Introduction (Chris Jimenez)Rest Introduction (Chris Jimenez)
Rest Introduction (Chris Jimenez)PiXeL16
Ā 
RefCard RESTful API Design
RefCard RESTful API DesignRefCard RESTful API Design
RefCard RESTful API DesignOCTO Technology
Ā 
Restful webservices
Restful webservicesRestful webservices
Restful webservicesLuqman Shareef
Ā 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To RESTrainynovember12
Ā 
Restful webservice
Restful webserviceRestful webservice
Restful webserviceDong Ngoc
Ā 
04 request-headers
04 request-headers04 request-headers
04 request-headerssnopteck
Ā 
Intro to RESTFul API's with ColdBox MVC
Intro to RESTFul API's with ColdBox MVCIntro to RESTFul API's with ColdBox MVC
Intro to RESTFul API's with ColdBox MVCOrtus Solutions, Corp
Ā 
REST in ( a mobile ) peace @ WHYMCA 05-21-2011
REST in ( a mobile ) peace @ WHYMCA 05-21-2011REST in ( a mobile ) peace @ WHYMCA 05-21-2011
REST in ( a mobile ) peace @ WHYMCA 05-21-2011Alessandro Nadalin
Ā 
distributing over the web
distributing over the webdistributing over the web
distributing over the webNicola Baldi
Ā 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHPMatthew Turland
Ā 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.jsAyush Mishra
Ā 
Restful web-services
Restful web-servicesRestful web-services
Restful web-servicesrporwal
Ā 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services TutorialLorna Mitchell
Ā 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorialLorna Mitchell
Ā 

Ƅhnlich wie Learn REST in 18 Slides (20)

Cqrs api v2
Cqrs api v2Cqrs api v2
Cqrs api v2
Ā 
Rest Introduction (Chris Jimenez)
Rest Introduction (Chris Jimenez)Rest Introduction (Chris Jimenez)
Rest Introduction (Chris Jimenez)
Ā 
RefCard RESTful API Design
RefCard RESTful API DesignRefCard RESTful API Design
RefCard RESTful API Design
Ā 
Cqrs api
Cqrs apiCqrs api
Cqrs api
Ā 
REST API Laravel
REST API LaravelREST API Laravel
REST API Laravel
Ā 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
Ā 
HTTP Basics Demo
HTTP Basics DemoHTTP Basics Demo
HTTP Basics Demo
Ā 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To REST
Ā 
Restful webservice
Restful webserviceRestful webservice
Restful webservice
Ā 
NodeJS
NodeJSNodeJS
NodeJS
Ā 
04 request-headers
04 request-headers04 request-headers
04 request-headers
Ā 
Intro to RESTFul API's with ColdBox MVC
Intro to RESTFul API's with ColdBox MVCIntro to RESTFul API's with ColdBox MVC
Intro to RESTFul API's with ColdBox MVC
Ā 
REST in ( a mobile ) peace @ WHYMCA 05-21-2011
REST in ( a mobile ) peace @ WHYMCA 05-21-2011REST in ( a mobile ) peace @ WHYMCA 05-21-2011
REST in ( a mobile ) peace @ WHYMCA 05-21-2011
Ā 
distributing over the web
distributing over the webdistributing over the web
distributing over the web
Ā 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
Ā 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
Ā 
Restful web-services
Restful web-servicesRestful web-services
Restful web-services
Ā 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
Ā 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
Ā 
Android networking-2
Android networking-2Android networking-2
Android networking-2
Ā 

KĆ¼rzlich hochgeladen

Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
Ā 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
Ā 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
Ā 
Call UsšŸ”>ą¼’+91-9711147426ā‡›Call In girls karol bagh (Delhi)
Call UsšŸ”>ą¼’+91-9711147426ā‡›Call In girls karol bagh (Delhi)Call UsšŸ”>ą¼’+91-9711147426ā‡›Call In girls karol bagh (Delhi)
Call UsšŸ”>ą¼’+91-9711147426ā‡›Call In girls karol bagh (Delhi)jennyeacort
Ā 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
Ā 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
Ā 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
Ā 
Dealing with Cultural Dispersion ā€” Stefano Lambiase ā€” ICSE-SEIS 2024
Dealing with Cultural Dispersion ā€” Stefano Lambiase ā€” ICSE-SEIS 2024Dealing with Cultural Dispersion ā€” Stefano Lambiase ā€” ICSE-SEIS 2024
Dealing with Cultural Dispersion ā€” Stefano Lambiase ā€” ICSE-SEIS 2024StefanoLambiase
Ā 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
Ā 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
Ā 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
Ā 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
Ā 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
Ā 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
Ā 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
Ā 
Maximizing Efficiency and Profitability with OnePlanā€™s Professional Service A...
Maximizing Efficiency and Profitability with OnePlanā€™s Professional Service A...Maximizing Efficiency and Profitability with OnePlanā€™s Professional Service A...
Maximizing Efficiency and Profitability with OnePlanā€™s Professional Service A...OnePlan Solutions
Ā 
GOING AOT WITH GRAALVM ā€“ DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM ā€“ DEVOXX GREECE.pdfGOING AOT WITH GRAALVM ā€“ DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM ā€“ DEVOXX GREECE.pdfAlina Yurenko
Ā 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
Ā 
Post Quantum Cryptography ā€“ The Impact on Identity
Post Quantum Cryptography ā€“ The Impact on IdentityPost Quantum Cryptography ā€“ The Impact on Identity
Post Quantum Cryptography ā€“ The Impact on Identityteam-WIBU
Ā 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
Ā 

KĆ¼rzlich hochgeladen (20)

Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Ā 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
Ā 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
Ā 
Call UsšŸ”>ą¼’+91-9711147426ā‡›Call In girls karol bagh (Delhi)
Call UsšŸ”>ą¼’+91-9711147426ā‡›Call In girls karol bagh (Delhi)Call UsšŸ”>ą¼’+91-9711147426ā‡›Call In girls karol bagh (Delhi)
Call UsšŸ”>ą¼’+91-9711147426ā‡›Call In girls karol bagh (Delhi)
Ā 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
Ā 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
Ā 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
Ā 
Dealing with Cultural Dispersion ā€” Stefano Lambiase ā€” ICSE-SEIS 2024
Dealing with Cultural Dispersion ā€” Stefano Lambiase ā€” ICSE-SEIS 2024Dealing with Cultural Dispersion ā€” Stefano Lambiase ā€” ICSE-SEIS 2024
Dealing with Cultural Dispersion ā€” Stefano Lambiase ā€” ICSE-SEIS 2024
Ā 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
Ā 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
Ā 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Ā 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
Ā 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Ā 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
Ā 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
Ā 
Maximizing Efficiency and Profitability with OnePlanā€™s Professional Service A...
Maximizing Efficiency and Profitability with OnePlanā€™s Professional Service A...Maximizing Efficiency and Profitability with OnePlanā€™s Professional Service A...
Maximizing Efficiency and Profitability with OnePlanā€™s Professional Service A...
Ā 
GOING AOT WITH GRAALVM ā€“ DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM ā€“ DEVOXX GREECE.pdfGOING AOT WITH GRAALVM ā€“ DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM ā€“ DEVOXX GREECE.pdf
Ā 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Ā 
Post Quantum Cryptography ā€“ The Impact on Identity
Post Quantum Cryptography ā€“ The Impact on IdentityPost Quantum Cryptography ā€“ The Impact on Identity
Post Quantum Cryptography ā€“ The Impact on Identity
Ā 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
Ā 

Learn REST in 18 Slides

  • 1. http://obeautifulcode.com made with REST (representational state transfer) GET /the/party?what=started Ā© 2014 Suraj Gupta
  • 2. http://obeautifulcode.com Why Learn REST? REST can help you build client-friendly distributed systems that are simple to understand and simple to scale. In other wordsā€¦ ā—¦ Clients rely on services that behave according to conventions. Services are flexible to client needs. And the grammar is straightforward ā€“ clients talk to services fluently. ā—¦ Devs can grok how the pieces fit together without too much mental acrobatics. Notice ā€œsimpleā€ and ā€œdistributedā€ in the same sentence. ā—¦ Scale becomes more about ā€œadd another web serverā€ and less about ā€œrethink the entire modelā€ Ā© 2014 Suraj Gupta 2
  • 3. http://obeautifulcode.com REST Should Feel Familiar ā—¦ REST is a style, not a standard ā—¦ REST was used to design HTTP. ā—¦ Youā€™ve probably used/seen things like: ā—¦ URIs, URLs ā—¦ Hypertext ā—¦ Accept:text/html ā—¦ 200 OK, 400 Bad Request ā—¦ GET, PUT, POST ā—¦ But HTTP can also be used in non-RESTful way. Many SOAP services use HTTP simply to transport data between two endpoints. HTTP has a rich set of (often ignored) features that support RESTful design. Ā© 2014 Suraj Gupta 3
  • 4. http://obeautifulcode.com There are 5 Major Concepts Ā© 2014 Suraj Gupta 4 Resources Representations Operations Hypertext Statelessness and of course they are ā€œfancy-soundingā€
  • 5. http://obeautifulcode.com Resources ā—¦ Every ā€œthingā€, every ā€œresourceā€ gets an identifier: /game/robots/four-hand-george /game/spaceships/destoyers/98 ā—¦ The URL is the unified concept of an identifier on the web ā—¦ A URI identifies a resource by location, name, or both ā—¦ A URL is a subset of URI. It specifies where a resource lives and the mechanism to retrieve it. ā—¦ four-hand-george, the robot, is a ā€œthingā€, You can retrieve him using HTTP and he is located here: http://obeautifulcode.com/game/robots/four-hand-george ā—¦ So an ISBN number is a URI but not a URL (it unambiguously identifies a book, but does not define where or how to retrieve it) ā—¦ REST says to identify everything that is worth being identified by your clients. ā—¦ This leads to creation of resources not typically seen in application design. For example, a process or process step, a sale, a negotiation or a request for quote. /game/spaceships/upgrades/56789 /game/negotations/truces/12345 Ā© 2014 Suraj Gupta 5
  • 6. http://obeautifulcode.com Resources ā—¦ Collections of things merit identification. They are things themselves: /game/robots (all robots) /game/spaceships?visability=invisible (all spaceships that are invisible) ā—¦ Resources can be static or change over time: /game/robots/four-hand-george (might always return the same information about a particular robot) /game/spaceships/upgrades/567 (the status of spaceship upgrade is likely to change over time and the upgrade itself may be deleted after it is complete) ā—¦ The same resource can be referred to by more than one URI: /game/robots/four-hand-george /game/spaceships/987/crew/four-hand-george (george identified as a crew-member of spaceship #987) /game/robot-factory/output/123 (george identified as the output #123 of the robot factory) ā—¦ Use the full URI namespace for identity. Donā€™t identify things using a method (operation) + parameters approach. For example, this is not really an identifier: /cgi-bin/getGameObject?type=robot&name=four-hand-george ā—¦ An identifier should not contain tech implementation details (e.g. cgi-bin). Those may change over time. ā—¦ Some benefits of URIs in the ā€œidentifierā€ style: ā—¦ Highly readable ā—¦ Easy to debug ā—¦ Easy for clients to construct Ā© 2014 Suraj Gupta 6
  • 7. http://obeautifulcode.com Representations ā—¦ How does a client know what to do with the data it receives when it fetches a URL? ā—¦ RESTful systems empower clients to asks for data in a form that they understand. ā—¦ Hereā€™s an HTTP header. A web browser would send this to a web server on your behalf: GET /pages/archive HTTP/1.1 Host: obeautifulcode.com Accept: text/html ā—¦ The type/form/representation of data requested is specified as a MIME type (e.g. text/html). There are over 1000 standard MIME types. ā—¦ So instead of requesting HTML, a client could request a resource, represented as XML, JSON, or some other format the client understands. Ā© 2014 Suraj Gupta 7
  • 8. http://obeautifulcode.com Representations ā—¦ Developers frequently define different URLs for different representations of the same resource: http://notRest.com/reports/2015/quarter/3/sales.html http://notRest.com/reports/2015/quarter/3/sales.xml http://notRest.com/reports/2015/quarter/3/sales.xls ā—¦ REST says to create one identifier that can be rendered in different forms GET /reports/2015/qtr/3/sales HTTP/1.1 Host: obeautifulcode.com Accept: application/vnd.ms-excel ā—¦ Some devs donā€™t realize that things can be abstracted from their representations. Like other kinds of abstraction, this one is worthwhile because it makes life simpler for the client. ā—¦ There has been a historic lack of tooling; redundant resources was in-part explained by developer convenience. But modern web frameworks leave us with no excuses. ā—¦ If the server doesn't support particular MIME type, the server can inform the client about this via a standard error (HTTP 406) ā—¦ The benefit of supporting a rich ecosystem of negotiable data is that you create long-lived, flexible systems that favor the client, not the developer. Ā© 2014 Suraj Gupta 8
  • 9. http://obeautifulcode.com Operations ā—¦ Traditional app development focuses on operations: GetRobots() FlyShip(id=ā€œship-123ā€, destination=Planets.Mars) ā—¦ Services broadcast their operations (e.g. WSDL) and clients sync-up with them. ā—¦ There are no conventions; operation names follow the devā€™s style guidelines (if one event exists) and documentation is needed to determine the side-effects of calling an operation. ā—¦ REST defines 4 standard operations (HTTP calls these verbs): ā—¦ GET: retrieve a representation of the resource ā—¦ PUT: create a resource at a known URI or update an existing resource by replacing it ā—¦ POST: create a resource when you donā€™t know URI, partial update of a resource, invoke arbitrary processing ā—¦ DELETE: delete a resource ā—¦ You perform one of these standard operations on a resource: GET /robots/four-hand-george in XML POST to /robots to create a new robot ā—¦ All resources support one of more of these operations. Ā© 2014 Suraj Gupta 9
  • 10. http://obeautifulcode.com Operations ā—¦ When we treat resources as things to manipulate via a URL and we restrict ourselves to a small set of operations, there is less need to extensively describe a service. ā—¦ It's not about the 50 things you can do with a particular service (which is how SOAP developers view the world). It's about using a standard set of things you can do (PUT, GET, etc.) with a set of resources (robots, spaceships, flightpaths, etc.) ā—¦ So how do you FlyShip(id=ā€œship-123ā€, destination=Planets.Mars)? PUT to /ships/ship-123/flightpath and send ā€œdestination=marsā€ in the body of the message Now you can poll that URI using GET for flight updates. or POST to /ships/ship-123/flightpaths and send ā€œ/planets/marsā€ in the body of the message. The server might return something like /ships/ship-123/flightpaths/456 to indicate that the ship is now flying to Mars and that a new flightpath resource was created to track it. You can poll that URI using GET for flight updates. ā—¦ Instead of defining a new operation such as StopFlight(id) to stop the flight, do this: DELETE /ships/ship-123/flightpaths/456 ā—¦ How does a web browser know what to do with a URL? All resources support the same operations, and GET is one of them. The browser GETs until everything has been gotten! Ā© 2014 Suraj Gupta 10
  • 11. http://obeautifulcode.com Operations ā€“ Safe v. Idempotent ā—¦ Further, there are rules about the effect that standard operations can have on a RESTful service. Clients can expect that services will follow the rules, they donā€™t need to be spelled out by the service. ā—¦ A safe method does not modify resources. ā—¦ An idempotent operation has no additional effect if it is called more than once with the same input parameters. ā—¦ Idempotent operations are used in the design of network protocols, where a request to perform an operation is guaranteed to happen at least once, but might also happen more than once. There is no harm in performing the operation two or more times. ā—¦ Ā© 2014 Suraj Gupta 11
  • 12. http://obeautifulcode.com Operations - Rules ā—¦ GET: ā—¦ Safe and Idempotent ā€“ it modifies nothing and there is no adverse when called multiple times. ā—¦ You can get google.com repeated and it will not change the Google homepage. ā—¦ DELETE: ā—¦ Not Safe, but Idempotent ā€“ it modifies resources, but there is no additional effect when called multiple times. ā—¦ DELETE /ships/ship-123/flightpaths/456 stops the flight the first time it is called. ā—¦ Subsequent calls are ignored by the server. ā—¦ PUT: ā—¦ Not Safe, but Idempotent ā€“ it modifies resources, but there is no additional effect when called multiple times with the same parameters. ā—¦ PUT to /ships/ship-123/flightpaths with a body of ā€œdestination=marsā€ creates a flight. ā—¦ Subsequent calls to that URI with the same body have no effect on the system. The ship is already headed to Mars. ā—¦ POST: ā—¦ Not Safe, Not Idempotent ā€“ it modifies resources and multiple calls will cause additional effect on the system. ā—¦ POST to /ships/ship-123/flightpaths with ā€œ/planets/marsā€ in the body creates the flight ā—¦ Service returns a resource to track it: /ships/ship-123/flightpaths/456. ā—¦ Subsequent POST, even with the same body, create new resources such as /ships/ā€¦/ship-123/flightpaths/457, ā€¦/458, etc. If you keep POSTing, the shipā€™s flight manifest might fill up! ā—¦ Server can send an error code saying that a flight to Mars is already in progress or that you have to DELETE one flight before creating another. Ā© 2014 Suraj Gupta 12
  • 13. http://obeautifulcode.com Hypertext ā—¦ Here is some made-up XML: <robot self='http://obeautifulcode.com/game/robots/123' > <age>3</age> <money ref='http://obeautifulcode.com/game/bank/accounts/567' /> <lastBattle ref='http://obeautifulcode/game/battles/890' /> </robot> ā—¦ Applications can "follow" links to retrieve more information about the robot, such as the robotā€™s last battle. ā—¦ Web-servers publish hypertext so that web-browsers know what to do next (i.e. get one page, fetch all the links and displaying them. When users clicks on a link, rinse and repeat) ā—¦ In REST, application state is transferred and discovered within hypertext responses. re-read the line above! ā—¦ A REST client needs less knowledge about how to interact with any particular service compared to clients that interact with operation-centric services. ā—¦ A client transitions through application states by selecting from links. So RESTful interaction is driven by hypermedia, not out-of-band information. Ā© 2014 Suraj Gupta 13
  • 14. http://obeautifulcode.com Statelessness ā—¦ REST mandates that state either be turned into resource state, or kept on the client. The client is responsible for application state. The server is responsible for resource state. ā—¦ The server should not retain some sort of communication state for any client it communicates with beyond a single request. This is whatā€™s meant when we say that REST is ā€œstatelessā€ ā—¦ For example: ā—¦ The client knows that its strategy is to deploy a robot when the spaceship reaches Mars. ā—¦ The server is keeping track of resources such as Mars, the spaceship, the robot on the spaceship (also itā€™s age, etc.), other robots in the universe. ā—¦ The client call poll the flight to Mars until it has completed. The completed flight resource will contain hypertext to inform the client about other resources it can now access. ā—¦ At no point does the clientā€™s strategy get stored in the server. Also, the server doesnā€™t attempt to remember the clientā€™s last 10 moves just to facilitate gameplay. That kind of state is not codified in a resource, so it must be maintained by the client. ā—¦ Letā€™s say the game server goes down and is immediately replaced by a new one. The game isnā€™t over. The old server kept nothing in-memory about the clientā€™s state-of-play. The serverā€™s responsibility is to restore the state of all resources in the universe (e.g. a particular spaceship with a particular robot is now sitting on Mars). The clientā€™s responsibility is to know where it is and to make its next move. Ā© 2014 Suraj Gupta 14
  • 15. http://obeautifulcode.com Statelessness - Benefits ā—¦ Client are isolated against changes on the server. ā—¦ Statelessness promotes redundancy. Clients are not dependent on talking to the same server in two consecutive requests. If a server goes down, just load balance clients to other servers. ā—¦ Statelessness unlocks performance: ā—¦ Slap a reverse proxy in front of the server. ā—¦ The proxy sit between a client and server and caches the serverā€™s responses. ā—¦ The responses are simply associated with the URI ā€“ no complex algos needed. ā—¦ Requests for a cached URI can be handled by the proxy instead of the server. ā—¦ Proxies remove stuff from cache after some server specified elapsed time or if thereā€™s a PUT operation (cached resource is being replaced) ā—¦ HTTP reverse proxies have been around forever. They are time-tested and used all over the internet to cache HTML and other requests. Ā© 2014 Suraj Gupta 15
  • 16. http://obeautifulcode.com Errors ā—¦ HTTP has a well-defined set of status codes for responses, some of which indicate an error. ā—¦ The status codes are grouped in categories. For example, 200 OK and 204 No Content are in the 2xx category which indicates that the action requested by the client was received, understood, accepted and processed successfully. ā—¦ Clients doesnā€™t necessarily need to handle each and every individual code. ā—¦ An error can be augmented with more details about what caused the error simply by including text in the body of the response. ā—¦ So when throwing and handling errors, RESTful systems converse using a well- known standards. ā—¦ Error handling becomes less about the idiosyncratic preferences of developers (is that service going to throw InvalidOperationExeption, ArgumentException, or AppSpecificException?). This means less documentation needed and less service- specific error handling code. Ā© 2014 Suraj Gupta 16
  • 17. http://obeautifulcode.com Common Objections to REST ā—¦ Rest is usable for CRUD, but not for "real" business logic: ā—¦ Any computation that returns a result can be transformed into a URI that identifies the result. ā—¦ x = sum(2,3) might become http://example.com/sum/a=2&b=3 ā—¦ This is NOT a misuse of REST. Here the URI still represents a resource and not an operation - namely it identifies the result of adding 2 and 3 together. ā—¦ Using GET to retrieve the result might be a good idea - this is cacheable, you can reference or bookmark it, and computing it is safe and not too costly ā—¦ There is no formal contract/no description language like WSDL: ā—¦ 95% of what we usually describe using WSDL for is not tied to WSDL at all, but rather is concerned with XML Schema complex types that are defined. REST with XML supports XML Schema. ā—¦ The most common use case for service descriptions is to generate stubs and skeletons for the service interface. Clients use this to code against the service. This is not documentation, because WSDL tells you nothing about the semantics of an operation, it just lists the operation names and parameters. ā—¦ With REST, you can provide documentation via HTML. For example, when client requests HTML for a resource you can return documentation for that resource, and when client requests, say, XML, then you can fetch the resource itself. Ā© 2014 Suraj Gupta 17
  • 18. http://obeautifulcode.com Common Objections to REST ā—¦ REST does not support transactions ā—¦ REST services are likely to interact with a database that supports transactions in the same way other SOA environments would. The only change is that, with REST, you are likely to create transactions explicitly yourself. ā—¦ Things differ when you combine transactions in larger units. SOAP can be used to propagate a transaction context using SOAP headers. ā—¦ But loose coupling and transactions, especially those of the ACID variety, donā€™t jive. The fact that you are coordinating a commit across multiple independent systems creates a pretty tight coupling between them. ā—¦ No publish/subscribe (pub/sub) support - In REST, notification is done by polling. The client can poll the server. GET is extremely optimized on the web. ā—¦ No asynchronous interactions ā—¦ Given HTTP's request/response model, how does one achieve async communication? How do you deliver a request from client to server where the process takes a long time? How does consumer know when processing is done? ā—¦ HTTP code 202 (Accepted) means "the request has been accepted for processing, but the process has not been completed" ā—¦ The server can return a URI of a resource which the client can GET to access the results. Ā© 2014 Suraj Gupta 18
  • 19. http://obeautifulcode.com The Reality of REST ā—¦ REST says nothing about how to maintain resource state. The implementation details and complexity is yours to own. ā—¦ If a system requires that the client create many different kinds of resources (robots and spaceships and 100 more things), REST might not be the right approach. ā—¦ REST is not a good solution for a real-time system or bandwidth-constrained environments (e.g. mobile apps). Because resources are the central concept in REST and REST disallows a client and a server to share state, the client winds up interacting with lots of URIs over-the-wire. HTTP uses a request/response model, so thereā€™s a lot of baggage flying around the network to make it all work. ā—¦ Because REST is not a standard, people and frameworks adhere to the principles to varying degrees. Like other architectural paradigms that are this broad in scope, the REST community has purists and pragmatists. Ā© 2014 Suraj Gupta 19
  • 20. http://obeautifulcode.com Reference This deck borrows from work by Stefan Tilkov, Brian Sletten, Gregor Roth, Jim Webber, Savas Parastatidis, and Ian Robinson which was published on March 2010 in Issue #1 of ā€œInfoQ Explores RESTā€ In some cases I have used their text verbatim. The publication is available here: http://www.infoq.com/minibooks/emag-03-2010-rest Ā© 2014 Suraj Gupta 20
  • 21. http://obeautifulcode.com Thank You! This deck is part of a blog post found here: made with Please Send Feedback! post to blog comments -or- email to surajg at gmail Follow me: Twitter - Google+ - Newsletter Ā© 2014 Suraj Gupta http://obeautifulcode.com/API/Learn-REST-In-18-Slides