Lesson 14: Building an API: Routes, JSON and REST
An API, an Application Programming Interface, is a way for programs to talk to each other, and a web API is a server that answers requests with data, usually in JSON format, instead of with pages. The Alpha School site you are studying uses exactly this idea: its pages ask an API for course data, and the API answers with a list of lessons. Building an API is therefore one of the most useful skills in web development, because the same API can serve a website, a phone app and any other program that needs the data. This lesson builds a small API with Express, the most widely used web framework for Node.js, and along the way it introduces REST, the set of conventions that keeps APIs predictable.
Routes: one address, one job
An API is organised into routes, each one pairing a method and a path with a job. A route such as GET /api/courses returns the list of courses, GET /api/courses/french returns one course, and POST /api/courses creates a new one. Express lets you write routes in a few lines: app.get('/api/courses', function (req, res) { res.json(courses); });, where req is the request and res is the response, and res.json() sends the data as JSON with the right headers. Keeping each route small and giving it a clear path makes the API easy to understand and easy to test, and you can test routes with your browser for GET requests and with a free tool such as Postman or curl for the others, which is a habit worth building now.
JSON: the language of data
JSON, JavaScript Object Notation, is a text format for data that both people and programs can read. An object is written with curly braces and named values, such as {"title": "French", "lessons": 20}, and an array is written with square brackets, such as ["HTML", "CSS", "JavaScript"]. JSON is strict in ways JavaScript is not: keys must be in double quotes, there are no comments, and there is no trailing comma after the last item, which are the three most common mistakes when writing it by hand. In JavaScript, JSON.stringify() turns a value into JSON text, and JSON.parse() turns JSON text back into a value, and the fetch() call you met in Lesson 12 uses response.json() to do the second step for you. Because JSON is just text, any language can read it, which is why it has become the standard format for APIs.
const express = require('express');
const app = express();
app.use(express.json());
const courses = [
{ id: 'french', title: 'French', lessons: 20 },
{ id: 'web', title: 'Web Development', lessons: 20 }
];
app.get('/api/courses', function (req, res) {
res.json(courses);
});
app.get('/api/courses/:id', function (req, res) {
const course = courses.find(function (c) {
return c.id === req.params.id;
});
if (!course) {
return res.status(404).json({ error: 'Course not found' });
}
res.json(course);
});
app.listen(3000);
REST: conventions that make APIs predictable
REST, Representational State Transfer, is a set of conventions for designing APIs, and its core idea is simple: use nouns for resources and HTTP methods for actions. A collection such as /api/courses is a noun, GET reads it, POST adds to it, and a single item such as /api/courses/french is read with GET, replaced with PUT, changed in part with PATCH, and removed with DELETE. The server should be stateless, meaning each request carries everything the server needs, and it should answer with the right status code: 200 for a successful read, 201 when something is created, 400 for a bad request, and 404 when the resource does not exist. Following these conventions means anyone who has used one REST API can guess how yours works, which is why they are worth learning even though no law forces you to follow them.
Errors, validation and safety
A good API is honest about problems. When a request is missing a required field, answer with 400 and a message naming the field, not with a crash or a silent success. When a resource does not exist, answer with 404, as in the example above, rather than sending an empty page. Never trust data from a client: check that numbers are numbers, that text is not absurdly long, and that an id refers to something that exists before you act on it, because a careless API is an open door, a topic the cybersecurity course explores in depth. Log requests on the server so you can see what was asked for, keep your routes in separate files as the API grows, and test every route, including the error cases, before you call the API finished.
Key Terms
- API
- Application Programming Interface, a way for programs to talk to each other, here a server that answers with data.
- Route
- A pairing of a method and a path with a job, such as GET /api/courses returning the course list.
- JSON
- JavaScript Object Notation, a strict text format for data, readable by any language.
- Express
- A widely used web framework for Node.js, for writing servers and APIs in JavaScript.
- REST
- A set of conventions for APIs: nouns for resources, HTTP methods for actions, and the right status codes.
- Stateless
- Each request carries everything the server needs, with nothing remembered between requests.
- Route parameter
- A variable part of a path, such as :id in /api/courses/:id, read from req.params.
Discussion Questions
- Why is it better to name a route /api/courses (a noun) than /api/getCourses (a verb)?
- JSON is stricter than JavaScript: keys need double quotes and there are no trailing commas. Why might that strictness be a good thing for data exchange?
- An API returns a 200 status with an empty page when a course does not exist. Why is a 404 with an error message better?
Practice Questions
- What does the route GET /api/courses/:id do in the example?
- Why must JSON keys be in double quotes?
- In REST, which method creates a new resource, and which deletes one?
- What does res.json(courses) do in Express?
- What status code should an API return when something is created successfully?
Show answers
- It returns the single course whose id matches :id. If no course matches, it answers with a 404 and an error message in JSON.
- Because JSON is a strict text format, not JavaScript. Single quotes, unquoted keys and trailing commas are all invalid JSON and will fail to parse.
- POST creates and DELETE removes. GET reads, PUT replaces a whole resource, and PATCH changes part of one.
- It sends the courses data as JSON with the right headers. The client receives JSON text it can parse back into a value.
- 201 Created. A plain 200 means success in general, while 201 specifically says a new resource was made.