🎓 A1Learner
🔍
0 of 50 lessons completed

REST in One Page

REST is a style for shaping an API around resources. Each resource gets one path, and each action gets one verb.

One resource, four routes

Each verb does one job on the same path.

GET    /api/notes
POST   /api/notes
GET    /api/notes/:id
DELETE /api/notes/:id

Deleting a note

The route removes the note and sends it back.

app.delete('/api/notes/:id', async (req, res) => {
  const note = await Note.findByIdAndDelete(req.params.id);
  res.json({ title: note.title, done: note.done });
});

Example

import express from 'express';
import mongoose from 'mongoose';

await mongoose.connect('mongodb://localhost:27017/notes');
const noteSchema = new mongoose.Schema({ title: String, done: Boolean });
const Note = mongoose.model('Note', noteSchema);
await Note.create({ title: 'Buy milk', done: false });
await Note.create({ title: 'Ship MERN', done: true });
await Note.create({ title: 'Read a book', done: false });
const app = express();
app.use(express.json());
app.get('/api/notes', async (req, res) => {
  const notes = await Note.find().sort({ title: 1 });
  res.json(notes.map((n) => ({ title: n.title, done: n.done })));
});
app.post('/api/notes', async (req, res) => {
  const note = await Note.create(req.body);
  res.status(201).json({ title: note.title, done: note.done });
});
app.get('/api/notes/:id', async (req, res) => {
  const note = await Note.findById(req.params.id);
  res.json({ title: note.title, done: note.done });
});
app.delete('/api/notes/:id', async (req, res) => {
  const note = await Note.findByIdAndDelete(req.params.id);
  res.json({ title: note.title, done: note.done });
});
const server = app.listen(0);
const port = server.address().port;
const base = `http://localhost:${port}`;
const list = await fetch(`${base}/api/notes`);
console.log(await list.text());
const created = await fetch(`${base}/api/notes`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'Water plants', done: false }),
});
console.log(await created.text());
const saved = await Note.findOne({ title: 'Water plants' });
const one = await fetch(`${base}/api/notes/${saved._id}`);
console.log(await one.text());
const removed = await fetch(`${base}/api/notes/${saved._id}`, { method: 'DELETE' });
console.log(await removed.text());
server.close();
await mongoose.disconnect();

Key points

  • REST shapes an API around resources, not actions.
  • One resource uses one path, such as /api/notes.
  • GET reads, POST creates, PATCH changes, and DELETE removes.
  • The same path does different work under each verb.
  • A missing resource answers 404, never an empty success.

In this example, the script connects to the notes database and saves the three notes. It builds an Express app with four routes on one resource, the notes. GET lists the notes, POST creates one, GET with an id reads one, and DELETE removes one. The script calls each route in turn and prints each body. The four printed lines show the whole API at work.

Note

A tidy route table is the whole design, on one page.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which verb creates a new note in a REST API?