New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Node.js› Building a REST API

Building a REST API

💻 Node.js

Design resources, methods and status codes for a small CRUD API.

Lesson 6 of 9 Tutorial
0 of 9 completed

REST models an API as resources. The URL names the thing and the HTTP method names the action.

By the end of this lesson you can:
  • Design resource URLs.
  • Map CRUD to HTTP methods.
  • Return consistent errors.

Resources and Methods

  • GET /students — list students.
  • GET /students/1 — one student.
  • POST /students — create.
  • PUT /students/1 — replace.
  • DELETE /students/1 — remove.

A Route Set

Keep handlers small and return the same error shape everywhere.

app.get("/students/:id", (request, response) => {
  const student = students.find(item => item.id === Number(request.params.id));

  if (!student) {
    return response.status(404).json({ error: "Student not found" });
  }

  response.json(student);
});

app.delete("/students/:id", (request, response) => {
  const index = students.findIndex(item => item.id === Number(request.params.id));

  if (index === -1) {
    return response.status(404).json({ error: "Student not found" });
  }

  students.splice(index, 1);
  response.status(204).end();
});

Validation

Validate the body before writing. A good API rejects bad input early with a 422 and a message that names the field.

Tip Use plural nouns for collections and ids for individual resources. Avoid verbs such as /getStudents in REST URLs.

Practice

  1. Add PUT /students/:id with validation.
  2. Return 404 for a missing id.
  3. Write a list of five error cases for the API.

Hands-on exercise

Extend the students API with PUT /students/:id.
1. Return 404 when the id does not exist.
2. Return 422 when name is empty.
3. Return the updated record with 200.

Recap

REST uses resource URLs and HTTP methods. Consistent status codes and error shapes make an API pleasant to use.

Example

app.get("/students/:id", (request, response) => {
  const student = students.find(item => item.id === Number(request.params.id));

  if (!student) {
    return response.status(404).json({ error: "Student not found" });
  }

  response.json(student);
});

app.delete("/students/:id", (request, response) => {
  const index = students.findIndex(item => item.id === Number(request.params.id));

  if (index === -1) {
    return response.status(404).json({ error: "Student not found" });
  }

  students.splice(index, 1);
  response.status(204).end();
});

Exercises

Exercise 1. Full CRUD Medium
Extend the students API with PUT /students/:id.
1. Return 404 when the id does not exist.
2. Return 422 when name is empty.
3. Return the updated record with 200.
Node.js exercise-1.txt
Expected Output
A complete CRUD route with clear validation and errors.

Lesson Nav

Lesson sections