6.3. REST APIs#
A REST API is simply a consistent way to name, organise, and use those routes so that any developer can predict how to interact with your data.
REST stands for Representational State Transfer. It is not a library, framework, or protocol. Instead think of REST as a set of manners for behaving on the web: “When you walk into the HTTP restaurant, this is how you order and how you respond”.
With REST APIs a clients and servers transfer representations (JSON) of a resource (book, user, photo).
Note
The responses from a REST API usually contain links or references to other objects so that the programmer can discover the other objects by traversing the objects. This is similar to following links on websites.
6.3.1. Resources and URLS#
In REST, the URL should point to a resource (noun), not an action (verb). The particular HTTP method used will control any actions.
For example the table below shows action-centric vs resource-centric URLs.
❌ Verb-centric |
✅ Resource-centric |
|---|---|
/getAllBooks |
/books |
/createUser |
/users |
/deleteBook/42 |
/books/42 |
Note
The words “route”, “URL” and “endpoint” refer to the same thing and are used interchangeably.
6.3.2. CRUD and HTTP Methods#
CRUD is an acronym that stands for:
Create - add new data
Read - retrieve data
Update - change existing data
Delete - remove data
REST maps each CRUD action to a HTTP method:
CRUD Action |
HTTP Method |
|---|---|
Create |
POST |
Read |
GET |
Update |
PUT or PATCH |
Delete |
DELETE |
Create Example
To create a book the client would send a request that looks like:
POST /api/books HTTP/1.1
Host: localhost:5000
Content-Type: application/json
Accept: application/json
{
"title": "Dune",
"author": "Frank Herbert",
"publication_date": "1966",
"genre": "Science Fiction"
}
Read Example
To get a book with a particular id:
GET /api/books/42 HTTP/1.1
Host: localhost:5000
Accept: application/json
Update Example
Suppose we wanted to correct the publication date of the book:
PUT /api/books/42 HTTP/1.1
Host: localhost:5000
Content-Type: application/json
Accept: application/json
{
"title": "Dune",
"author": "Frank Herbert",
"publication_date": "1965",
"genre": "Science Fiction"
}
Delete Example
To delete the book with the id of 42, the client (web browser or app) would send a DELETE request as follows:
DELETE /api/books/42 HTTP/1.1
Host: localhost:5000
With a delete operation it is usually not necessary to transfer the complete JSON representation of the resource.