Express.js
Beginner
1 min read
Designing a RESTful API with Express
Example
// routes/api/v1/posts.js
const express = require('express');
const router = express.Router();
// Response helpers
const ok = (res, data, status = 200) => res.status(status).json({ data });
const fail = (res, message, status = 400) =>
res.status(status).json({ error: { message } });
// In-memory store (replace with DB)
let posts = [{ id: 1, title: 'Hello World', body: 'First post.' }];
let nextId = 2;
router.get('/', (req, res) => ok(res, posts));
router.get('/:id', (req, res) => {
const post = posts.find(p => p.id === +req.params.id);
if (!post) return fail(res, 'Post not found', 404);
ok(res, post);
});
router.post('/', (req, res) => {
const { title, body } = req.body;
if (!title) return fail(res, 'title is required', 422);
const post = { id: nextId++, title, body };
posts.push(post);
ok(res, post, 201);
});
router.patch('/:id', (req, res) => {
const post = posts.find(p => p.id === +req.params.id);
if (!post) return fail(res, 'Post not found', 404);
Object.assign(post, req.body);
ok(res, post);
});
router.delete('/:id', (req, res) => {
posts = posts.filter(p => p.id !== +req.params.id);
res.status(204).end();
});
module.exports = router;
Related Resources
Express.js Reference
Complete tag & property list
Express.js How-To Guides
Step-by-step practical guides
Express.js Exercises
Practice what you've learned
More in Express.js