Creating with POST
Part of the REST APIs section of Coddy's Node.js journey. Lesson 2 of 18.
A client that adds a task needs to know where the new task lives. It sends the new resource to the list's URL with POST, and the server answers 201 Created with the resource and a Location header naming its URL.
POST /api/events { "name": "Launch party" }
201 Created
Location: /api/events/12
{ "id": 12, "name": "Launch party" }The server picks the id, so two clients can never claim the same one. With the Location header the client can fetch the new event without building the URL itself. res.location(path) sets that header, and it chains like res.status:
res.status(201).location(`/api/events/${event.id}`).json(event);Challenge
EasyPOST /api/taskswith{ "title" }answers 201 with the new task:idfromnextId()instore.js,done: false,createdAtfromnew Date().toISOString().- It sets
Locationto/api/tasks/<id>. - No
title: 400.
Send { "title": "Order new chairs" }, then GET the Location path, then POST {}.
Try it yourself
import { Router } from 'express';
import { tasks } from '../store.js';
const router = Router();
router.get('/', (req, res) => {
res.json(tasks);
});
router.get('/:id', (req, res) => {
const task = tasks.find((t) => t.id === Number(req.params.id));
if (!task) {
return res.status(404).json({ error: 'Task not found' });
}
res.json(task);
});
export default router;
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST