← Back to Node.js Course | Chapter 8: Working with APIs | Lesson 2 of 7

GET/POST/PUT/DELETE

Each HTTP method maps onto a create, read, update or delete action for your data.

In this page:

  1. GET/POST/PUT/DELETE
Syntax
javascript
app.get('/resources', (req, res) => res.json(items));
app.post('/resources', (req, res) => { /* create */ });
app.put('/resources/:id', (req, res) => { /* replace */ });
app.delete('/resources/:id', (req, res) => { /* remove */ });

GET/POST/PUT/DELETE

Implement handlers that read or change an in-memory or database store. GET returns 200, POST returns 201 with the new item, PUT replaces, and DELETE returns 204. Validate input and return 404 when an id does not exist.

Note: Return the created resource and a Location header from POST.

Example: GET/POST/PUT/DELETE

javascript
const http = require("http");
let nextId = 1; const db = new Map();
const server = http.createServer((req, res) => {
  const id = Number(req.url.split("/")[2]);
  let body = ""; req.on("data", (c) => (body += c));
  req.on("end", () => {
    const send = (s, d) => { res.writeHead(s, { "Content-Type": "application/json" }); res.end(d === undefined ? "" : JSON.stringify(d)); };
    if (req.method === "POST") { const item = { id: nextId++, ...JSON.parse(body) }; db.set(item.id, item); return send(201, item); }
    if (req.method === "GET") return db.has(id) ? send(200, db.get(id)) : send(404, { error: "not found" });
    if (req.method === "PUT") { db.set(id, { id, ...JSON.parse(body) }); return send(200, db.get(id)); }
    if (req.method === "DELETE") { db.delete(id); return send(204); }
  });
});
server.listen(0, async () => {
  const base = "http://localhost:" + server.address().port + "/items";
  const post = await fetch(base, { method: "POST", body: JSON.stringify({ name: "pen" }) });
  console.log(post.status, await post.json());
  console.log((await fetch(base + "/1")).status);
  console.log((await fetch(base + "/1", { method: "DELETE" })).status);
  console.log((await fetch(base + "/1")).status);
  server.close();
});

// Output:
// 201 { id: 1, name: 'pen' }
// 200
// 204
// 404

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Returning 200 for created items
  2. Not validating input
  3. Forgetting 404 for missing ids
Chapter Summary
  • GET 200, POST 201
  • PUT replaces, DELETE 204
  • Validate input
  • Return 404 for unknown ids
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.