The key abstraction of information in REST is a resource. Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on.
http://localhost:1234/users # the resource is a collection
http://localhost:1234/users/1 # the resource is a singleton# collection
https://api-example/movies
# singleton
https://api-example/movies/{id}
# sub-collection
https://api-example/movies/{id}/actors
# controller (executable functions)
https://api-example/movies/{id}/tickets/{id}/checkout{
"id": "1",
"title": "Black Panther",
"release": "2019-01-29T00:00:00Z",
"actors": [
"Chadwick Boseman",
"Michael B. Jordan",
"Lupita Nyong'o"
]
}<?xml version="1.0" encoding="UTF-8" ?>
<id>1</id>
<title>Black Panther</title>
<release>2019-01-29T00:00:00Z</release>
<actors>Chadwick Boseman</actors>
<actors>Michael B. Jordan</actors>
<actors>Lupita Nyong'o</actors>https://api-example/movieshttps://api-example/movies/1https://api-example/movieshttps://api-example/movieshttps://api-example/movies/1https://api-example/movieshttps://api-example/movies/1$ yarn add express
$ npm install express --save
// file app.js
const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello, World!'));
app.listen(3000, () => {
console.log('Listening on port 3000!');
});$ node ./app.js # then, load localhost:3000/ in a browser
app.method(path, handler);app.get('/movies', (req, res) => {
// fetch movies from DB, from JSON, ...
// send collection to `res` (response)
res.status(200).json(movies);
});app.post('/movies', (req, res) => {
const newMovie = req.body;
// add new movie from `req` (request) to collection
// send new movie to `res` (response)
res.status(201).json(newMovie);
});// To parse json body (for POST / PUT)
const bodyParser = require('body-parser');
app.use(bodyParser.json());app.put('/movies/:id', (req, res) => {
const movieId = req.params.id;
const movie = req.body;
// update movie from id in collection
// send updated movie to `res` (or nothing)
res.status(200).json(movie);
// or res.status(204);
});app.delete('/movies/:id', (req, res) => {
const movieId = req.params.id;
// delete movie from id in collection
// send response
res.status(200).json(deletedMovie);
// or res.status(204);
});const middleware = (req, res, next) => {
console.log('Time:', Date.now());
// calling next() to continue request-response cycle
next();
};
const app = express();
app.use(middleware);
const middleware = (req, res, next) => { ... };
const app = express();
app.get('/movies', middleware, (req, res) => {
// fetch all movies
res.json(movies);
});