Creating an Express App
Install Express.js and create the foundation for your REST API — a running server with basic route handling and JSON support.
Creating an Express App
Now that you understand HTTP methods, it is time to build a real API server. Express.js is a minimal, flexible web framework for Node.js that makes creating APIs simple and clean. In this episode you will install Express and set up the server.
Step 1: Install Express
npm install express
Step 2: Create the Server
Replace the contents of index.js:
const express = require('express');
const app = express();
// Middleware to parse JSON request bodies
app.use(express.json());
// Basic route
app.get('/', (req, res) => {
res.json({ message: 'Welcome to the REST API' });
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Understanding the Code
| Line | Purpose |
|---|---|
require('express') | Imports the Express library |
express() | Creates an Express application instance |
app.use(express.json()) | Middleware that parses JSON request bodies automatically |
app.get('/', callback) | Defines a route that responds to GET requests on / |
res.json() | Sends a JSON response (sets Content-Type automatically) |
app.listen(PORT) | Starts the server on the specified port |
Route Handler Basics
app.get('/api/ninjas', (req, res) => {
res.json({ message: 'GET all ninjas' });
});
app.post('/api/ninjas', (req, res) => {
res.json({ message: 'POST a new ninja' });
});
app.get('/api/ninjas/:id', (req, res) => {
res.json({ message: 'GET ninja ' + req.params.id });
});
| Method | What It Handles |
|---|---|
app.get() | GET requests |
app.post() | POST requests |
app.put() | PUT requests |
app.delete() | DELETE requests |
app.patch() | PATCH requests |
The Request Object (req)
app.get('/api/ninjas/:id', (req, res) => {
console.log(req.params); // { id: '123' }
console.log(req.query); // { sort: 'name' } from ?sort=name
console.log(req.body); // POST/PUT body data
console.log(req.method); // 'GET'
console.log(req.url); // '/api/ninjas/123?sort=name'
});
| Property | Contains | Example |
|---|---|---|
req.params | URL parameters (from :id) | { id: '123' } |
req.query | Query string parameters | { sort: 'name' } |
req.body | Parsed request body (JSON) | { name: 'Ryu' } |
req.method | HTTP method used | 'GET' |
The Response Object (res)
// Send JSON
res.json({ name: 'Ryu' });
// Send with status code
res.status(201).json({ name: 'Ryu' });
// Send a string
res.send('Hello World');
// Send a status only
res.sendStatus(204); // 204 No Content
Testing the Server
npm run dev
Open http://localhost:3000 in a browser and you should see:
{ "message": "Welcome to the REST API" }
Key Takeaways
express()creates an app instance;app.listen()starts the serverexpress.json()middleware parses JSON request bodies automaticallyapp.get(),app.post(),app.put(),app.delete()handle specific HTTP methodsreq.paramscontains URL parameters,req.queryhas query strings,req.bodyhas parsed JSONres.json()sends a JSON response and sets the Content-Type header automatically