RESTful Services

24
RESTful Services What is REST and is it worth the trouble? OR How to start an argument with your coworkers.

Transcript of RESTful Services

RESTful ServicesWhat is REST and is it worth the trouble?

ORHow to start an argument with your coworkers.

What is REST?• REpresentational State Transfer• Originates from PhD thesis by Roy Felding. http://www.ics.uci.edu/~

fielding/pubs/dissertation/rest_arch_style.htm• 6 Main Tenets• Uniform Interface• Stateless• Cacheable• Client-Server• Layered System• Code-on-Demand

REST• Uniform Interface

• Everything is a resource, accessed through URIs

• Stateless• Client always passes state necessary to complete action

• Cacheable• Results can be marked as cacheable or not

• Client-Server• Client and Server are de-coupled

• Layered System• Client has no knowledge of backend implementation

• Code-on-Demand (optional)• Client can be extended with code retrieved from server• JavaScript, Applets, plug-ins, etc• Of dubious value to APIs

Uniform Interface• Resource based• Everything is a URI• Apply verbs to Resource• Avoid RPC style invocations• Don’t replicate SOAP using JSON and MVC Web API.

Layered System• Don’t expose the implentation on the backend through your API.• Don’t expose your database tables as a series of REST resources and

operations• As a general rule, defer decisions (like persistence) as long as possible.

Choose tools that allow you to defer

Richardson Maturity ModelHow RESTful is your API?

• Level 0 – Swamp of POX• Level 1 – Resource Based• Level 2 – Verbs• Level 3 – HATEOAS

Created by Leonard Richardson

HATEOAS?• Not just an evil breakfast cereal.• Hypermedia As The Engine Of Application State• Links define what can be done with resource

in current context{ id: “123”, _links: [{rel:“self”, href:“/cart/123”}, {rel:“order”, href:“/cart/123/order”}]

• Allows server to provide contextual actions to client• Client responds appropriately based on state

What is Hypermedia?• Media with Hyperlinks, that’s it.• Media type definitions define how hyperlinks work that media type• HTML <a href=… />• XML XLink• HAL _links

Why is Hypermedia important?• Discoverability• Driving State• Resiliency

Roy’s Smack down

Roy’s Smack down“API designers, please note the following rules before calling your creation a REST API:”• “A REST API should not be dependent on any single communication protocol”• “A REST API should not contain any changes to the communication protocols aside from

filling-out or fixing the details of underspecified bits of standard protocols”• “A REST API should spend almost all of its descriptive effort in defining the media type(s)

used for representing resources and driving application state”• “A REST API must not define fixed resource names or hierarchies”• “A REST API should never have “typed” resources that are significant to the client.”• “A REST API should be entered with no prior knowledge beyond the initial URI (bookmark)

and set of standardized media types that are appropriate for the intended audience”• http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

Roy’s Smack down“Of course the client has prior knowledge. Every protocol, every media type definition, every URI scheme, and every link relationship type constitutes prior knowledge that the client must know (or learn) in order to make use of that knowledge. REST doesn’t eliminate the need for a clue. What REST does is concentrate that need for prior knowledge into readily standardizable forms. That is the essential distinction between data-oriented and control-oriented integration.It has value because it is far easier to standardize representation and relation types than it is to standardize objects and object-specific interfaces. In other words, there are fewer things to learn and they can be recombined in unanticipated ways while remaining understandable to the client.”

Is HTTP required?• NO• RestBus, etc.• HTTP semantics over AMQP

• But...• HTTP is ubiquitous• Every platform can talk HTTP

• HTTP Works• HTTP is easy

Media Types• application/json• HAL+JSON• JSON API• No Custom types: application/vnd.ebayorder+json

HTTP Verbs• GET – Retreive a Representation• POST – Create (Server generated ID)• PUT – Create OR Replace (Client generated ID)• PATCH – Update• DELETE – Delete

• Verbs act on nouns. Represent everything as a noun.

HTTP Response Codes• Use the most specific response code• 2XX for Success• 3XX for Redirections• 4XX for Client related errors• 5XX for service related errors

2XX Examples• 200 OK in response to successful GET• 201 Created for successful POST• Location header for location of new resource

• 202 Accepted for async operations• Location header for polling endpoint

• 200 with status message, 303 once created, 410 GONE once status endpoint no longer makes sense to keep

• 206 Partial Content for ranged requests• Use with Range header• Can be used for paging

3XX Examples• 302/303 for redirect• Location header

• 304 Not Modified• Use with If-Modified-Since or If-None-Match headers

• 307/308• Temporary vs Permanent Redirect• VERB cannot change

4XX Examples• 400 Bad Request• 401 Unauthorized• - You’re Not Authenticated

• 403 Forbidden• You don’t have permission

• 404 Not Found• Resource doesn’t exist (yet)

• 405 Method (VERB) not allowed• 409 conflict• Use with ETags for concurrency

4XX Examples• 410 Gone• Resource no longer exists• Use instead of 404 if you want client to know that it used to exist but doesn’t

anymore

• 429 Too Many Requests• Use for Rate Limiting

5XX Examples• 500 Internal Server Error• Something’s broke

• 502 Bad Gateway• Can be used if you wish to signal to the client that the problem lies with

another endpoint• Ex. Client calls your service and your service calls 3rd party that is down.

Versioning

• http://www.troyhunt.com/2014/02/your-api-versioning-is-wrong-which-is.html• Require version on each request• Use API gateway to route requests• Make non breaking changes when possible• Deploy to new endpoint on major/breaking changes if backward

compatability is a requirement.

Best Practices• Require a correlation ID for all requests• Generate one if client doesn’t provide it

• Always return a payload with error information on 4XX and 5XX responses• Use ETags for caching and concurrency• Prefer X-xxx header naming for custom headers to avoid conflicts• Use UTC time and ISO8601 format (2016-02-15T23:30:00Z) • Use Swagger (OpenAPI) for documentation (http://swagger.io/)