Interview: What is Rest ?
REST is a style you can follow but it’s not a formal specification.
Http based REST consists of HTTP methods, status codes, response types.
HTTP methods
- Create:
POST
- READ:
GET
- UPDATE:
PUT
,PATCH
- DELETE:
DELETE
Note that a PUT
request asks clients to send the entire resource with the updated values. To partially update a resource, a PATCH
verb could be used
Status Codes
1xx — Informational Responses
2xx — Successful Responses — 201 (CREATED)
3xx — Redirects
4xx — Client Errors — 401 (UNAUTHORIZED):
5xx — Server Errors — 503 (SERVICE UNAVAILABLE)
Problems with REST
- Not a formal specification.
- The shape of incoming data is unknown.
In order for a service or API to be effectively RESTful, it must adhere to the following constraints:
- Client-server : The client and server must be independent of each other, and the client should only know the URIs to the resource.
- Stateless
- Cacheable
- Uniform interface (URL)
Why Stateless ?
Earlier clients sessions are stored in a server-instance. This starts to be an issue when trying to scale horizontally. Solutions have been found to tackle this issue (e.g. by configuring session replication and/or sticky session), but the REST architecture proposes another approach: just don’t make you server stateful, make it stateless. Session state is therefore kept entirely on the client.
How?
A common approach is a token-based authentication, especially with the trendy JSON Web Tokens.
Using cookies or headers (or anything else) has nothing to do with whether the server is stateful or stateless: these are just media that are here used to transport tokens (session identifier for stateful servers, JWT, etc.), nothing more.
Cacheable API with conditional requests
With the Last-Modified
header
The server can provide a Last-Modified
date header to the responses holding resources that are cacheable. Clients should then store this date together with the resource.
Now, each time clients request the API to read the resource, they can add to their requests an If-Modified-Since
header containing the latest Last-Modified
date they received and stored. The server has then to compare the request's header and the actual last modified date of the resource. If they are equal, the server returns a 304 (NOT MODIFIED) with an empty body: the requesting client should use the currently cached resource it has.
Also, when clients request the API to update the resource (i.e. with an unsafe verb), they can add an If-Unmodified-Since
header.
Versioning of APIs
- API is versioned through the URL (Route versioning) — e.g.
/v1/:foo/:bar/:baz