Thuta Learning
Node.js
ProjectsWeb DevelopmentBeginner

REST API Intro

Node.jsLesson 2230 min

What you'll walk away with

  • Design routes around a resource, separating the collection URL (/api/users) from the item URL (/api/users/:id)
  • Choose what GET, POST, PATCH and DELETE each do and which success status each should return
  • Answer every unknown route with one consistent JSON error shape instead of an HTML page
  • Run an Express app on port 0 and check its status codes and bodies with fetch

Explain it simply

Explain it simply

Think of a REST API as a library counter. The shelves are labelled: a "users" shelf, a "books" shelf. To see a whole shelf you ask for /api/users; to get one item you ask for /api/users/2. The URL says what you are talking about, and the HTTP method (GET, POST, DELETE...) says what you want done with it.

Every answer from the counter has two parts. The status code is the short answer (200: here you go, 404: no such thing), and the JSON body carries the details. When the browser, the mobile app and the admin dashboard all know this one set of rules, none of them needs a custom guide to talk to the server.

Problem → Why → Solution

The problem: endpoints invented one at a time

Imagine a team that adds a new endpoint every time a feature needs one. Verbs creep into the URLs (/getUsers, /createUser, /deleteUser?id=2), and even the delete is called with GET. When a user does not exist the server still returns status 200, with { success: false } hidden in the body. One endpoint calls its error field message, another calls it err.

The frontend developer now writes custom parsing code for each endpoint. Worse, a link-preview bot that follows GET links can open /deleteUser?id=2 and quietly delete a user.

messy-api.js
app.get('/getUsers', (req, res) => res.json(users));

app.get('/deleteUser', (req, res) => {        // GET that changes data
  const i = users.findIndex((u) => u.id === Number(req.query.id));
  if (i === -1) return res.json({ success: false, err: 'nope' }); // 200!
  users.splice(i, 1);
  res.json({ success: true });
});

app.post('/createUser', (req, res) => {
  if (!req.body.name) return res.json({ message: 'name?' });   // 200 again
  // ...
});

Why this hurts

HTTP gives methods and status codes standard meanings (RFC 9110), and browsers, caches, proxies and retry libraries rely on them. They assume GET never changes data, so they may repeat or prefetch it. fetch's res.ok looks only at the status, so an error sent with 200 looks like success.

Core concept: the four parts of a REST contract

A REST API is not a library; it is a contract between server and client. If you write the contract down before any code, the frontend and backend teams can work at the same time. The contract has four parts to decide.

1. Name the resource with a noun URL

/api/users is the collection (all users) and /api/users/2 is one item in it. No verbs like get, create or delete go in the URL, because the method already says the action. Use plural nouns.

2. Pick the action with the method

GET only reads and must not change data (it is safe). POST creates a new item in a collection. PATCH changes some fields, PUT replaces the whole item, and DELETE removes it. GET, PUT and DELETE are idempotent: calling one once or many times leaves the server in the same state.

3. Report the outcome with a status code

2xx means success, 4xx means the client sent something wrong or missing, and 5xx means the server failed. A client should know what happened from the status alone, before it reads the body.

4. Keep one body shape

In this course every endpoint uses the same shapes: { data: ... } on success (plus count for lists) and { error: "..." } on failure.

RequestMeaningSuccess status
GET /api/usersList all users200 OK
GET /api/users/:idRead one user200 OK (404 if missing)
POST /api/usersCreate a user201 Created (400 if invalid)
PATCH /api/users/:idChange some fields200 OK
DELETE /api/users/:idRemove a user204 No Content

This table is the map for the next lessons: lesson 23 writes the list route, lesson 24 the single-item route, lesson 25 the POST route, and the mini project adds PATCH and DELETE. A user has exactly three fields: id, name and role.

Mental model: noun, verb, outcome, details
  1. URL points at the resource (noun)
  2. Method names the action (verb)
  3. Status code sums up the outcome
  4. JSON body carries the details

Before adding an endpoint, ask "which resource, which method?" Most of the time you do not need to invent a new URL at all.

General pattern

javascript
const app = express();
app.use(express.json());                        // read JSON request bodies

app.get('/api/things', listHandler);            // collection
app.post('/api/things', createHandler);
app.get('/api/things/:id', readOneHandler);     // one item
app.delete('/api/things/:id', removeHandler);

app.use((req, res) => res.status(404).json({ error: 'message' }));
app.listen(port);

One resource gets handlers on two URLs, the collection and /:id, one per method. The fallback at the bottom answers any request that matched no route with a JSON error.

The base app for the users API

This app keeps three users in memory and has only one route so far, /api/health. Every other request gets a JSON 404. app.listen(0) asks the operating system for any free port, so it never clashes with something already running. Once the server is up, the code sends three requests with fetch and then closes the server.

app.js
const express = require('express');

const app = express();
app.use(express.json());

// The one resource this API manages (in memory until a database arrives)
const users = [
  { id: 1, name: 'Aung Aung', role: 'admin' },
  { id: 2, name: 'Mya Mya', role: 'member' },
  { id: 3, name: 'Zaw Zaw', role: 'member' },
];

app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', users: users.length });
});

// Every route we have not built yet answers with the same JSON error shape
app.use((req, res) => {
  res.status(404).json({ error: `Cannot ${req.method} ${req.path}` });
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const calls = [
    ['GET', '/api/health'],
    ['GET', '/api/users'],
    ['DELETE', '/api/users/1'],
  ];
  for (const [method, path] of calls) {
    const res = await fetch(base + path, { method });
    const type = res.headers.get('content-type');
    console.log(`${method} ${path} -> ${res.status} (${type})`);
    console.log(`  body: ${JSON.stringify(await res.json())}`);
  }
  server.close();
});

Code breakdown

  1. JSON body parserapp.use(express.json());

    Parses request bodies sent with Content-Type: application/json into req.body. Nothing uses it yet, but the POST route in lesson 25 will.

  2. The resource{ id: 1, name: 'Aung Aung', role: 'admin' },

    Every user has an id, a name and a role. The array lives only in memory, so each restart brings back the same three users.

  3. res.json()res.json({ status: 'ok', users: users.length });

    Turns the object into a JSON string and sets Content-Type to application/json; charset=utf-8. Without an explicit status, the status is 200.

  4. JSON fallbackres.status(404).json({ error: `Cannot ${req.method} ${req.path}` });

    Because this app.use() sits below the routes, it only runs when no route matched. Without it Express replies with an HTML page, and a client expecting JSON fails to parse it.

  5. Port 0const server = app.listen(0, async () => {

    With port 0 the OS picks a free port, and server.address().port tells you which one. Tests use this trick all the time.

  6. Close when doneserver.close();

    Closing the server lets the Node process finish and exit. Without it the program would keep waiting for requests forever.

You should see
GET /api/health -> 200 (application/json; charset=utf-8)
  body: {"status":"ok","users":3}
GET /api/users -> 404 (application/json; charset=utf-8)
  body: {"error":"Cannot GET /api/users"}
DELETE /api/users/1 -> 404 (application/json; charset=utf-8)
  body: {"error":"Cannot DELETE /api/users/1"}

Why safe and idempotent matter

On mobile networks a connection often drops after a request is sent but before the response arrives. The client cannot tell whether the server got it. An idempotent request such as DELETE /api/users/3 can be retried safely, because repeating it changes nothing further. Repeating POST /api/users, on the other hand, can create the same user twice.

So picking the right method is not just about tidy design: client libraries decide when retrying is allowed by looking at the method.

In real projects

In real projects

A shop might have three clients: the customer website, an Android app and an admin panel for staff. All three call the same backend and share one contract, such as /api/orders and /api/orders/:id. As long as that contract stays stable, the backend team can switch databases or rewrite code without touching any client.

Public APIs follow the same idea; GitHub's REST API uses nested resource URLs such as GET /repos/{owner}/{repo}/issues. Many teams write the contract as an OpenAPI document and generate documentation and tests from it. When a change would break the contract, they open a new version such as /api/v2 and give old clients time to move. Getting the contract right early is far cheaper than changing it after three apps depend on it.

Common mistakes

Common mistakes

Sending errors with status 200

Writing only res.json({ success: false }) still sends status 200. The client's res.ok is true and your monitoring shows a 0% error rate. Set the real status with res.status(): 404 for missing, 400 for invalid input.

Changing data inside a GET route

A route like GET /users/2/delete can be triggered by crawlers, link previews or browser prefetching without anyone clicking. Anything that changes data belongs on POST, PATCH, PUT or DELETE.

Forgetting the JSON fallback

Without a fallback, Express answers an unknown route with an HTML page reading "Cannot GET /api/userz". The client's await res.json() throws a SyntaxError that hides the real problem, a typo in the URL.

Mini challenge

Write the contract for a notes API as code

Before writing any logic for a notes resource, write its contract as data. Register a stub route for every contract entry in a loop; each stub answers 501 Not Implemented with the JSON error shape. GET /api returns the whole contract as a readable list.

  • The contract lists GET list, GET one, POST, PATCH and DELETE with correct success statuses
  • Register the routes in a loop with app[method.toLowerCase()](path, handler)
  • Every stub answers status 501 with { error: "..." }
  • A request outside the contract (for example PUT) gets a JSON 404
notes-contract.js
const express = require('express');

// TODO: one entry per route: { method, path, success, does }
const contract = [];

const app = express();
app.use(express.json());

// TODO: GET /api -> { data: ['GET /api/notes -> 200', ...] }

// TODO: loop over contract and register a 501 stub for each route

// TODO: JSON 404 fallback

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  // TODO: print GET /api, then try POST /api/notes and PUT /api/notes/7
  server.close();
});

Expected: Five contract lines (GET /api/notes -> 200 through DELETE /api/notes/:id -> 204), then POST answering 501 and PUT answering 404, both with a JSON error.

Show hint

app.get and app['get'] are the same function, so you can lowercase the method string and call app[...] with it. Inside each stub, the route variable is available through the closure.

Show solution
notes-contract.js
const express = require('express');

const contract = [
  { method: 'GET', path: '/api/notes', success: 200, does: 'list notes' },
  { method: 'GET', path: '/api/notes/:id', success: 200, does: 'read one note' },
  { method: 'POST', path: '/api/notes', success: 201, does: 'create a note' },
  { method: 'PATCH', path: '/api/notes/:id', success: 200, does: 'change some fields' },
  { method: 'DELETE', path: '/api/notes/:id', success: 204, does: 'remove a note' },
];

const app = express();
app.use(express.json());

app.get('/api', (req, res) => {
  res.json({ data: contract.map((r) => `${r.method} ${r.path} -> ${r.success}`) });
});

for (const route of contract) {
  app[route.method.toLowerCase()](route.path, (req, res) => {
    res.status(501).json({ error: `Not implemented yet: ${route.does}` });
  });
}

app.use((req, res) => {
  res.status(404).json({ error: `Cannot ${req.method} ${req.path}` });
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const index = await (await fetch(`${base}/api`)).json();
  index.data.forEach((line) => console.log(line));

  for (const [method, path] of [['POST', '/api/notes'], ['PUT', '/api/notes/7']]) {
    const res = await fetch(base + path, { method });
    console.log(method, path, res.status, JSON.stringify(await res.json()));
  }
  server.close();
});

Quick quiz 1 / 3

Which request follows REST style for deleting the user with id 7?

Quick quiz 2 / 3

While the example app runs, what does fetch(base + '/api/users/1', { method: 'DELETE' }) get back?

Quick quiz 3 / 3

An endpoint replies with status 200 and { success: false, error: 'not found' }. What is res.ok on the client?

What to remember

  • The URL names the resource (a noun) and the method names the action
  • /api/users is the collection and /api/users/:id is one item in it
  • The status code reports the outcome; never send an error with 200
  • A JSON fallback below the routes answers every unknown route with the same error shape

HTTP Semantics (RFC 9110) — RFC Editor

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

REST API Intro | Thuta Learning