REST API Basics
REST maps HTTP methods to actions on resources.
Syntax
GET /resource -> 200 + JSONA REST API exposes data as resources (like users or posts) and uses HTTP methods to act on them.
| Method | Action | Example |
|---|---|---|
| GET | Read | GET /users |
| POST | Create | POST /users |
| PUT | Update | PUT /users/5 |
| DELETE | Remove | DELETE /users/5 |
Responses are usually JSON, paired with a meaningful status code.
Example
const http = require('http');
const users = [{ id: 1, name: 'Ada' }];
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/users') {
res.writeHead(200, { 'Content-Type': 'application/json' });
return res.end(JSON.stringify(users));
}
res.writeHead(404).end();
});
server.listen(3000);When to use it
- A mobile app fetches user data from a Node.js REST API using `GET /users/:id` and displays the JSON response in a profile screen.
- An order management system creates new orders via `POST /orders` and updates shipping status via `PATCH /orders/:id/status`.
- A frontend SPA deletes a blog post by sending `DELETE /posts/:id` to the Node.js API, which removes the record and returns `204 No Content`.
More examples
RESTful resource routes
Maps the six standard REST verbs to their semantic meaning and implements a minimal GET list route.
// GET /items -> list all
// GET /items/:id -> get one
// POST /items -> create
// PUT /items/:id -> replace
// PATCH /items/:id -> partial update
// DELETE /items/:id -> delete
// Minimal pure-http router
const http = require('http');
http.createServer((req, res) => {
const [,, id] = req.url.split('/');
if (req.method === 'GET' && !id) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify([{ id: 1, name: 'Widget' }]));
} else { res.writeHead(501); res.end(); }
}).listen(3000);Consume a REST API with fetch
Uses the Node 18+ global `fetch` to consume a public REST API and parse the JSON response.
// Node 18+ has global fetch built-in
async function getPost(id) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
getPost(1).then(post => console.log(post.title));Send a POST with a JSON body
Sends a JSON POST request using global `fetch` -- sets the Content-Type header and serializes the body.
async function createUser(data) {
const res = await fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
return res.json();
}
createUser({ name: 'Bob', email: '[email protected]' })
.then(user => console.log('Created:', user.id));
Discussion