Course Lessons

JAVASCRIPT FOUNDATIONS + AI MINDSET

Back to Course

Building a REST API with Express

JAVASCRIPT... Lesson 17 of 41 7 min

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.

LIVE AI LEARNING SESSION

Ask your AI assistant this question ↓

💬 YOU ASK THE AI:

"What are the 4 HTTP methods GET, POST, PUT, DELETE and what does each one do in a REST API? Give me a real-world analogy."

🤖 AI RESPONDS (Industry-Standard Answer):

GET — Retrieves data from the server. It should never modify data (idempotent). Analogy: Opening a library catalog to see what books are available. You're just looking, not changing anything.

POST — Creates a new resource on the server. The server assigns an ID and stores it. Analogy: Submitting a form to add a new book to the library's collection. You provide the details, the librarian creates a new entry.

PUT — Completely replaces an existing resource. You send the entire updated resource, and the server replaces the old version. Analogy: Taking a book off the shelf, replacing it with a completely new edition (same ID, completely new content).

DELETE — Removes a resource from the server. Analogy: Removing a book from the library collection permanently.

Real-world API example (Student Management):
GET /students → List all students
GET /students/1 → Get student with ID 1
POST /students → Create a new student (data in body)
PUT /students/1 → Replace student ID 1 completely
DELETE /students/1 → Delete student ID 1

Status codes to remember: 200 OK (GET success), 201 Created (POST success), 204 No Content (DELETE success), 400 Bad Request (client error), 404 Not Found (resource missing), 500 Server Error (server problem).

📝 MY NOTE — IN MY OWN WORDS

The library analogy made HTTP methods stick. GET is browsing the catalog. POST is adding a new book. PUT is replacing an entire book. DELETE is removing it. I tested my API with curl and saw real JSON responses. The express.json() middleware finally makes sense — without it, POST requests couldn't read the body. I feel confident building REST APIs now. Next step: add PUT and DELETE routes to make the API complete. The status codes (201 for created) showed me that professional APIs give meaningful responses.

HTTP Methods Quick Reference

METHODPurposeIdempotent?Has Body?Success Status
GETRead/retrieve data✅ Yes❌ No200 OK
POSTCreate new resource❌ No✅ Yes201 Created
PUTReplace entire resource✅ Yes✅ Yes200 OK
PATCHPartially update resource❌ No✅ Yes200 OK
DELETERemove resource✅ Yes⚠️ Optional204 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