Вы находитесь на странице: 1из 26

Principles of

REST Design
Adarsh Hasnah

Content
Brief overview of REST
Best practices for REST Design

What is REST?

What is REST
Representational state transfer (REST) is an abstraction of
the architecture of the World Wide Web.
REST is an architectural style consisting of a coordinated
set of architectural constraints applied to
components, connectors, and data elements, within a
distributed hypermedia system.

Architectural constraints
ClientServer
Stateless
Cacheable
Layered system
Uniform interface

Clientserver
A uniform interface separates clients from servers.
This separation of concerns means that, for example, clients are not
concerned with data storage, which remains internal to each server, so that
the portability of client code is improved.
Servers are not concerned with the user interface or user state, so that
servers can be simpler and more scalable.
Servers and clients may also be replaced and developed independently, as
long as the interface between them is not altered.

Stateless
The clientserver communication is further 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. Important to note is that
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.

Cacheable
As on the World Wide Web, clients 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 clientserver
interactions, further improving scalability and performance.

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.

Uniform interface
The uniform interface constraint is fundamental to the design of any REST
service. 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
Manipulation of resources through these representations
Self-descriptive messages
Hypermedia as the engine of application state (HATEOAS)

Uniform interface Constraint


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 HTML, XML
or JSON, none of which are the server's internal representation, and it is the same one resource
regardless.

Manipulation of resources through these representations


When a client holds a representation of a resource, including any metadata attached, it has
enough information to modify or delete the resource.

Uniform interface Constraint


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). Responses also explicitly indicate their cacheability.

Hypermedia as the engine of application state (HATEOAS)


Clients make state transitions only through actions that are dynamically identified within
hypermedia by the server (e.g., by hyperlinks within hypertext). Except for simple fixed entry
points to the application, a client does not assume that any particular action is available for any
particular resources beyond those described in representations previously received from the
server.

HTTP methods (verb)


GET
HEAD
POST
PUT
DELETE
Note:
1. PUT & DELETE are referred to as idempotent
2. GET method is a safe method (or nullipotent), i.e no side effects
3. There are others HTTP methods such as TRACE, OPTIONS, CONNECT & PATCH

Best Practices for


REST API Design

1 - Use nouns for resources


For an easy understanding use this structure for every resource:

DO NOT use verbs:


eg /getAllCars, /createNewCar, /deleteAllRedCars

2 - GET should be safe


Do not use GET for state changes
Use PUT, POST and DELETE methods instead of the
GET method to alter the state.

3 - Use plural nouns


Do not mix up singular and plural nouns.
Keep it simple and use only plural nouns for all resources.
example:

4 - Use sub-resources for relations


If a resource is related to another resource use
subresources.
example:

5 - Use HTTP headers for


serialization formats
Both, client and server, need to know which format is used
for the communication. The format has to be specified in
the HTTP-Header.
Content-Type defines the request format.
Accept defines a list of acceptable response formats.

7 - Provide filtering, sorting, field selection


and paging for collections
Filtering
Use a unique query parameter for all fields or a query language for filtering.

Sorting
Allow ascending and descending sorting over multiple fields.
This returns a list of cars sorted by descending manufacturers and ascending models.

7 - Provide filtering, sorting, field selection


and paging for collections
Field selection
Mobile clients display just a few attributes in a list. They dont need all attributes of a resource.
Give the API consumer the ability to choose returned fields. This will also reduce the network
traffic and speed up the usage of the API.

Paging
Use limit and offset. It is flexible for the user and common in leading databases. The default
should be limit=20 and offset=0. To send the total entries back to the user use the custom HTTP
header: X-Total-Count.

8 - Handle Errors with HTTP status


codes
It is hard to work with an API that ignores error handling.
Pure returning of a HTTP 500 with a stack trace is not
very helpful.
The HTTP standard provides over 70 status codes to
describe the return values. We dont need them all, but
there should be used at least a mount of 10.

8 - HTTP status codes


200 - OK - Everything is working
201 - OK - New resource has been created
204 - OK - The resouce was successfully
deleted
304 - Not modified - The client can use
cached data

8 - HTTP status codes


400 - Bad request - Invalid or cannot be served
401 - Unauthorised - require user authentication
403 - Forbidden - Access not allowed
404 - Not found - no resource behind the URI
422 - Unprocessable entity - eg mandatory fields missing
500 - Internal Server Error - API developers should avoid
this error

Other Areas of Interest


Specification for REST eg RAML, Swagger,..
Rest Server framework, eg RESTEASY for
java ee
REST Client framework / library, eg retrofit
Plugins for easy testing eg POSTMAN
Testing framework, eg REST-ASSURED

Thank you for your


participation
Any questions?

Вам также может понравиться