Resources and URLs
Part of the REST APIs section of Coddy's Node.js journey. Lesson 1 of 25.
Other programmers call your API from their code, so its addresses must be easy to guess. Most web APIs follow a style called REST: each address names a thing, a resource, and the HTTP method says what to do with it.
GET /api/invoices the list of invoices
GET /api/invoices/7 invoice 7
POST /api/invoices add an invoice
DELETE /api/invoices/7 remove invoice 7The path holds nouns, never verbs. With /api/getInvoices and /api/deleteInvoice?id=7, a client must learn a new word for every action. A router mounted with app.use('/api/invoices', invoices) answers both addresses: its '/' route is the list and its '/:id' route is one invoice. An id that matches nothing answers 404 with a JSON error, so the client reads it like any other answer.
Challenge
Easy- Mount the router in
server.jsat/api/tasks. GET /api/tasksanswers the array fromstore.js.GET /api/tasks/:idanswers one task, or 404 with{ "error": "Task not found" }.
Press Run and send GET /api/tasks, GET /api/tasks/2 and GET /api/tasks/99.
Try it yourself
import { Router } from 'express';
import { tasks } from '../store.js';
const router = Router();
// Add a route for the whole list and a route for one task
export default router;
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in REST APIs
1Resources and Verbs
Resources and URLsCreating with POST4Browsers, Versions and Config
What Is an OriginAllowing Another OriginCORSA Page That Calls the APIPractice on your own: Express playground