REST Architectural Style for API design

What is RESTful api?

Representational state transfer (REST) is a software architectural style to design web services proposed by Roy Fielding in 2000.
REST is independent of any underlying protocol and is not necessarily tied to HTTP. However, most common REST API implementations use HTTP as the application protocol, and this guide focuses on designing REST APIs for HTTP.

restful api
restful api

A web service that follows these guidelines is called RESTful. Such a web service must provide its web resources in a textual representation and allow them to be read and modified with a stateless protocol and a predefined set of operations.

Semantics of HTTP methods

HTTP methodCRUD equivalentDescription
GETReadGet a representation of the target resource’s state.
POSTCreateLet the target resource process the representation enclosed in the request.
PUTUpdateSet the target resource’s state to the state defined by the representation enclosed in the request.
DELETEDeleteDelete the target resource’s state.
PATCH-Partially update resource’s state.
OPTIONS-Advertising the available methods.
  • The GET method is safe, meaning that applying it to a resource does not result in a state change of the resource (read-only semantics)

  • The GET, PUT, and DELETE methods are idempotent, meaning that applying them multiple times to a resource results in the same state change of the resource as applying them once, though the response might differ.

  • The GET and POST methods are cacheable, meaning that responses to them are allowed to be stored for future reuse.

  • The GET (read), PUT (create and update), and DELETE (delete) methods are CRUD operations as they have storage management semantics, meaning that they let user agents directly manipulate the states of target resources.

    The POST method is not a CRUD operation but a process operation that has target-resource-specific semantics excluding storage management semantics, so it does not let user agents directly manipulate the states of target resources.

Architectural Constraints

A system that complies with some or all of these constraints is loosely referred to as RESTful.
When these constraints are applied to the system architecture, it gains desirable non-functional properties, such as performance, scalability, simplicity, modifiability, visibility, portability, and reliability.

The formal REST constraints are as follows:

Client-Server Architecture

  • The client-server design pattern enforces the principle of separation of concerns: separating the user interface concerns from the data storage concerns.
  • This separation improves anarchic scalability.

Statelessness

  • Relevant session data is sent to the receiver by the client in such a way that every packet of information transferred can be understood in isolation, without context information from previous packets in the session.
  • Increases performance by removing server load caused by retention of session information.

Cacheability

  • Responses must, implicitly or explicitly, define themselves as either cacheable or non-cacheable to prevent clients from providing 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.
  • The cache can be performed at the client machine in memory or browser cache storage.
  • Additionally cache can be stored in a Content Delivery Network (CDN).

Layered system

  • Intermediary servers (proxy or load balancer or api gateway) can be placed in between client and server, and it won’t affect their communications (no need to update the client or server code).
  • Improve system scalability (by enabling load balancing and by providing shared caches) and security (by adding a security layer, separating business logic from security logic)

Code on demand (optional)

  • Servers can temporarily extend or customize the functionality of a client by transferring executable code
  • Example: compiled components such as Java applets, or client-side scripts such as JavaScript.

Uniform Interface

Resource identification in requests

  • Individual resources are identified in requests, for example using URIs in RESTful Web services.
  • The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server could send data from its database as HTML, XML or as JSON—none of which are the server’s internal representation.

Resource manipulation 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’s state.

Self-descriptive messages

  • Each message includes enough information to describe how to process the message. For example, which parser to invoke can be specified by a media type.

Hypermedia as the Engine of Application State (HATEOAS)

  • When we perform a REST request, we only get the data and not any actions around it. This is where HATEOAS comes in the fill in the gap. With HATEOAS, a request for a REST resource gives both data, and actions (links/hrefs) related to the data.
  • The single most important reason for HATEOAS is loose coupling. If a consumer of a REST service needs to hard-code all the resource URLs, then it is tightly coupled with your service implementation.

REST API Design - Best Practices

Aim

Most modern web applications expose APIs that clients can use to interact with the application. A well-designed web API should aim to support:

  • Platform independence.

    Any client should be able to call the API, regardless of how the API is implemented internally. This requires using standard protocols, and having a mechanism whereby the client and the web service can agree on the format of the data to exchange.

  • Service evolution.

    The web API should be able to evolve and add functionality independently from client applications. As the API evolves, existing client applications should continue to function without modification. All functionality should be discoverable so that client applications can fully use it.

Practices

  • Use nouns instead of verbs in endpoint paths. We already have verbs mapped to CRUD operations.
  • Use logical nesting on endpoints, example: /articles/:articleId/comments
    • This is good practice regardless of whether your data is structured like this in your database. In fact, it may be advisable to avoid mirroring your database structure in your endpoints to avoid giving attackers unnecessary information.
    • Avoid 3 or more level nesting
  • Handle errors gracefully and return standard error codes
  • Allow filtering, sorting, and pagination
  • Accept and respond with JSON
  • Maintain good security practices
  • Cache data to improve performance
  • Versioning the APIs

More

FAQs

Restful Vs Restless

  • RESTful services use REST architectural style
  • RESTless means not restful. If the web service does not adhere to RESTful principles then it is not RESTful
  • Many developers describe their APIs as being RESTful, even though these APIs do not fulfill all of the architectural constraints described above (especially the uniform interface constraint).

REST Vs SOAP

  • There is no “official” standard for RESTful web APIs. This is because REST is an architectural style.
    REST is not a standard in itself, but RESTful implementations make use of standards, such as HTTP, URI, JSON, and XML.

  • SOAP is a protocol

URI Vs URL

URIs –> identify
URLs –> locate

However, locators are also identifiers, so every URL is also a URI, but there are URIs which are not URLs.

Examples:
John Doe is a name, which is an identifier. It is like a URI, but cannot be a URL, as it tells you nothing about the location.
21st Jump Street, Beverly Hills is a locator, which is an identifier for that physical location. It is like both a URL and URI (since all URLs are URIs), and also identifies the resource indirectly as “resident of..”.

From Wikipedia:

In computing, a Uniform Resource Locator (URL) is a subset of the Uniform Resource Identifier (URI) that specifies where an identified resource is available and the mechanism for retrieving it. In popular usage and in many technical documents and verbal discussions it is often incorrectly used as a synonym for URI, …

Because of this common confusion, many products and documentation incorrectly use one term instead of the other, assign their own distinction, or use them synonymously.