Your first Express API

Routes, JSON and status codes.

Node.js
import express from "express";

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

const jobs = [{ id: 1, title: "Intern" }];

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

app.get("/api/jobs/:id", (req, res) => {
  const job = jobs.find((j) => j.id === Number(req.params.id));
  if (!job) return res.status(404).json({ error: "Job not found" });
  res.json(job);
});

app.post("/api/jobs", (req, res) => {
  if (!req.body.title) return res.status(400).json({ error: "Title is required" });
  const job = { id: jobs.length + 1, title: req.body.title };
  jobs.push(job);
  res.status(201).json(job);
});

app.listen(3000, () => console.log("http://localhost:3000"));
StatusMeaning
200 / 201OK / created
400The request is wrong
401 / 403Not signed in / not allowed
404Not found
500The server failed
โ† Modules and filesMiddleware and errors โ†’