HTTP Verbs through a Gateway
Select a method and fire it through the API gateway. Watch the request reach the endpoint and return a status code.
Code example
Making REST calls with fetch() and handling them with Express.js.
// REST client using fetch()
const BASE = 'https://api.example.com';
// GET — read a resource
const user = await fetch(`${BASE}/users/42`).then(r => r.json());
// POST — create a resource
const created = await fetch(`${BASE}/users`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Naser', role: 'admin' })
}).then(r => r.json()); // ? 201 Created
// PUT — replace a resource
await fetch(`${BASE}/users/42`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Naser S.', role: 'superadmin' })
}); // ? 204 No Content
// DELETE — remove a resource
await fetch(`${BASE}/users/42`, { method: 'DELETE' });
// ? 204 No Content
// Express.js server — REST route handlers
const express = require('express');
const app = express();
app.use(express.json());
// GET /users/:id — read
app.get('/users/:id', (req, res) => {
const user = db.find(req.params.id);
if (!user) return res.status(404).json({ error: 'Not found' });
res.json(user); // 200 OK
});
// POST /users — create
app.post('/users', (req, res) => {
const user = db.create(req.body);
res.status(201).json(user); // 201 Created
});
// PUT /users/:id — replace
app.put('/users/:id', (req, res) => {
db.replace(req.params.id, req.body);
res.status(204).end(); // 204 No Content
});
// DELETE /users/:id — remove
app.delete('/users/:id', (req, res) => {
db.remove(req.params.id);
res.status(204).end();
});
Key concepts
API
An Application Programming Interface is a defined contract: here are the requests you can make, here is the format of responses. The implementation details are hidden.
REST
Representational State Transfer — 6 constraints: client-server, stateless, cacheable, uniform interface, layered system, optional code-on-demand. Stateless means no server session.
HTTP Verbs
GET reads, POST creates, PUT replaces, PATCH modifies, DELETE removes. The verb + URL together describe the operation on a resource.
Status Codes
200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Internal Server Error. Always return the right code.