Building a REST API with Express
Building a REST API with Express
Create Professional Backend Endpoints
By AI Learning Assistant · Express.js · REST API · Backend Development
🤖 AI-POWERED LESSON
This article is paired with a live AI session. Every code block includes detailed line-by-line comments explaining WHY each line exists and HOW Express handles HTTP requests. You will learn to build professional REST APIs.
Express is the most popular web framework for Node.js. It turns Node.js from a low-level HTTP server into a powerful, easy-to-use platform for building APIs. With Express, you can define routes, handle HTTP methods, send JSON responses, and create complete backend applications in minutes rather than hours.
REST (Representational State Transfer) is an architectural style for designing APIs. A RESTful API uses HTTP methods to perform operations on resources. Think of a resource as anything your API manages — students, products, users, posts. You use GET to read, POST to create, PUT to update, and DELETE to remove.
We will cover setting up an Express server, defining routes for GET and POST, sending JSON responses, understanding REST principles, and testing APIs with Thunder Client or curl. By the end, you will have a working API that manages student data.
What is Express?
MINIMAL · FLEXIBLE · NODE.JS WEB FRAMEWORK
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies the process of handling HTTP requests, routing, middleware, and sending responses. Express is the backend equivalent of what React is to frontend — the industry standard.
📜 CODE BLOCK 1: Install Express (run in terminal)
// ============================================ // STEP 1: Create project and install Express // ============================================ // Create a new directory for your API project mkdir webbo3-api cd webbo3-api // Initialize npm project npm init -y // Install Express (saves to dependencies) npm install express // For development, you might also want nodemon (auto-restart) npm install --save-dev nodemon // Update package.json scripts: // "scripts": { // "start": "node app.js", // "dev": "nodemon app.js" // }
Complete Express Server
GET · POST · JSON MIDDLEWARE · ROUTING
📜 CODE BLOCK 2: Complete app.js (with line-by-line comments)
// ============================================ // COMPLETE REST API WITH EXPRESS // ============================================ // WHY: Import the express framework // HOW: require() loads the express module from node_modules const express = require("express"); // WHY: Create an Express application instance // This app object has methods like .get(), .post(), .listen() const app = express(); // WHY: This middleware parses incoming JSON request bodies // Without this, req.body would be undefined for POST requests // .use() tells Express to use this middleware for every request app.use(express.json()); // ============================================ // DATA (simulating a database) // ============================================ // WHY: In-memory array acts as our data store // In production, this would be a real database like MongoDB or PostgreSQL const students = [ { id: 1, name: "Kemi", skill: "JavaScript" }, { id: 2, name: "Tunde", skill: "React" }, { id: 3, name: "Amara", skill: "Node.js" } ]; // ============================================ // ROUTE 1: GET / (Home/Welcome route) // ============================================ // WHY: The root endpoint returns a welcome message // HOW: app.get() handles HTTP GET requests to the specified path // req: request object (contains query params, headers, body) // res: response object (used to send data back to client) app.get("/", (req, res) => { // res.json() automatically sets Content-Type to application/json // It also stringifies the JavaScript object for you res.json({ message: "Welcome to Webbo3 API" }); }); // ============================================ // ROUTE 2: GET /students (Read all students) // ============================================ // WHY: This endpoint returns the entire list of students // REST standard: GET for reading data app.get("/students", (req, res) => { // Send the students array as JSON res.json(students); }); // ============================================ // ROUTE 3: POST /students (Create a new student) // ============================================ // WHY: This endpoint adds a new student to our data store // REST standard: POST for creating new resources // The client sends the new student data in the request body app.post("/students", (req, res) => { // Extract the new student data from the request body // req.body is populated by express.json() middleware const newStudent = { id: students.length + 1, // Auto-increment ID ...req.body // Spread operator merges name and skill }; // Add the new student to our array students.push(newStudent); // Send back the created student with HTTP status 201 (Created) // 201 is the standard status code for successful resource creation res.status(201).json(newStudent); }); // ============================================ // START THE SERVER // ============================================ // WHY: .listen() binds the server to a port and starts listening // Port 3000 is the standard development port for Express app.listen(3000, () => { console.log("API running on port 3000"); console.log("Test GET: http://localhost:3000/students"); console.log("Test POST: Use Thunder Client or curl"); }); // ============================================ // HOW TO RUN // ============================================ // $ node app.js // OR with nodemon (auto-restart on changes): // $ npx nodemon app.js
Testing Your API
THUNDER CLIENT · CURL · BROWSER
✅ TEST YOUR API
Method 1: Browser (GET only)
Open http://localhost:3000/students in your browser. You will see the JSON data.
Method 2: curl in terminal (GET)
curl http://localhost:3000/students
Method 3: curl for POST (create a student)
curl -X POST http://localhost:3000/students -H "Content-Type: application/json" -d '{"name":"Zainab","skill":"Python"}'
Method 4: Thunder Client (VS Code extension)
Install Thunder Client extension, create a new request, select GET or POST, enter URL, and send.
What Makes an API RESTful?
RESOURCE-BASED · STATELESS · STANDARD HTTP METHODS
REST (Representational State Transfer) is an architectural style, not a protocol. A RESTful API follows these principles:
- Resource-based: APIs operate on resources (students, products, users). Each resource has a unique URL.
- Stateless: Each request contains all information needed. The server doesn't remember previous requests.
- HTTP Methods: Use GET (read), POST (create), PUT (update/replace), PATCH (partial update), DELETE (remove).
- Status Codes: 200 OK, 201 Created, 400 Bad Request, 404 Not Found, 500 Server Error.
- JSON Format: Most modern REST APIs use JSON for request/response bodies.
HTTP Methods Quick Reference
| METHOD | Purpose | Idempotent? | Has Body? | Success Status |
|---|---|---|---|---|
| GET | Read/retrieve data | ✅ Yes | ❌ No | 200 OK |
| POST | Create new resource | ❌ No | ✅ Yes | 201 Created |
| PUT | Replace entire resource | ✅ Yes | ✅ Yes | 200 OK |
| PATCH | Partially update resource | ❌ No | ✅ Yes | 200 OK |
| DELETE | Remove resource | ✅ Yes | ⚠️ Optional | 204 No Content |
🤖 HOW AI ACCELERATES REST API DEVELOPMENT
Ask AI to scaffold complete route handlers:
- "Create a complete Express route for a 'products' resource with GET all, GET by ID, POST, PUT, and DELETE"
- "Add validation to my POST /students route — name must be string, skill required"
- "What status code should I return when a requested resource isn't found?"
- "Convert this Express callback to async/await with error handling"
- "Help me debug: my POST request returns 500 but works in Thunder Client"
AI-Assisted JavaScript Learning · Express.js · REST APIs · Professional Backend Development
Complete this lesson
Mark as complete to track your progress