Building a REST API
💻 Node.jsDesign resources, methods and status codes for a small CRUD API.
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
- Add PUT /students/:id with validation.
- Return 404 for a missing id.
- 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.
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
Output
Expected Output
A complete CRUD route with clear validation and errors.