Node.js Lesson 10: Building a REST API

🟢 Node.js CourseLesson 10 of 15 · 67% complete

A REST API is the standard way for frontend apps (React, mobile) to communicate with a backend server. In this lesson, we build a complete CRUD API.

REST API Conventions

// Resource: /api/tasks
// GET    /api/tasks       — list all
// POST   /api/tasks       — create new
// GET    /api/tasks/:id   — get one
// PUT    /api/tasks/:id   — update (full replace)
// PATCH  /api/tasks/:id   — update (partial)
// DELETE /api/tasks/:id   — delete

Complete Tasks API

const express = require("express");
const app = express();
app.use(express.json());

let tasks = [
  { id: 1, title: "Learn Node.js", done: false },
  { id: 2, title: "Build an API", done: false }
];

app.get("/api/tasks", (req, res) => {
  res.json(tasks);
});

app.get("/api/tasks/: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);
});

app.post("/api/tasks", (req, res) => {
  const { title } = req.body;
  if (!title) return res.status(400).json({ error: "Title required" });
  const task = { id: Date.now(), title, done: false };
  tasks.push(task);
  res.status(201).json(task);
});

app.patch("/api/tasks/:id", (req, res) => {
  const task = tasks.find(t => t.id === Number(req.params.id));
  if (!task) return res.status(404).json({ error: "Not found" });
  Object.assign(task, req.body);
  res.json(task);
});

app.delete("/api/tasks/:id", (req, res) => {
  tasks = tasks.filter(t => t.id !== Number(req.params.id));
  res.json({ success: true });
});

app.listen(3000, () => console.log("API ready at http://localhost:3000/api/tasks"));

🏋️ Practice Task

Build a complete Books REST API. Book: { id, title, author, year, genre }. Implement all 5 endpoints. Add filtering: GET /api/books?genre=fiction should return only fiction books. Add sorting: ?sort=year should sort by year.

💡 Hint: For filtering: if (req.query.genre) result = result.filter(b => b.genre === req.query.genre). For sorting: result.sort((a,b) => a[sort] – b[sort]).

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *