How to Create REST API with Express: Simple Guide
To create a REST API with
Express, first install Express and set up a server using express(). Then define routes with HTTP methods like GET, POST, PUT, and DELETE to handle API requests and send responses.Syntax
Here is the basic syntax to create a REST API endpoint in Express:
const express = require('express'): Import Express library.const app = express(): Create an Express app instance.app.use(express.json()): Middleware to parse JSON request bodies.app.METHOD(PATH, HANDLER): Define a route where METHOD is HTTP method like GET, POST, etc., PATH is the URL path, and HANDLER is a function to process requests.app.listen(PORT): Start the server on a port.
javascript
const express = require('express') const app = express() app.use(express.json()) app.get('/path', (req, res) => { res.send('response') }) app.listen(3000, () => { console.log('Server running on port 3000') })
Example
This example creates a simple REST API with Express that manages a list of items. It supports getting all items, adding a new item, updating an item by id, and deleting an item by id.
javascript
import express from 'express' const app = express() app.use(express.json()) let items = [{ id: 1, name: 'Item One' }] // Get all items app.get('/items', (req, res) => { res.json(items) }) // Add a new item app.post('/items', (req, res) => { const newItem = { id: Date.now(), name: req.body.name } items.push(newItem) res.status(201).json(newItem) }) // Update an item by id app.put('/items/:id', (req, res) => { const id = Number(req.params.id) const item = items.find(i => i.id === id) if (!item) return res.status(404).json({ error: 'Item not found' }) item.name = req.body.name res.json(item) }) // Delete an item by id app.delete('/items/:id', (req, res) => { const id = Number(req.params.id) items = items.filter(i => i.id !== id) res.status(204).end() }) app.listen(3000, () => { console.log('API running on http://localhost:3000') })
Output
API running on http://localhost:3000
Common Pitfalls
Common mistakes when creating REST APIs with Express include:
- Not using
express.json()middleware, so JSON request bodies are undefined. - Forgetting to send a response, causing requests to hang.
- Not handling errors or missing resources, leading to unclear client responses.
- Using
app.getfor all routes instead of proper HTTP methods.
javascript
/* Wrong: Missing express.json middleware */ const express = require('express') const app = express() app.post('/data', (req, res) => { // req.body will be undefined res.send(req.body) }) app.listen(3000) /* Right: Add express.json middleware */ app.use(express.json())
Quick Reference
Here is a quick reference for common Express REST API methods:
| HTTP Method | Express Method | Purpose |
|---|---|---|
| GET | app.get(path, handler) | Retrieve data from server |
| POST | app.post(path, handler) | Create new data on server |
| PUT | app.put(path, handler) | Update existing data |
| DELETE | app.delete(path, handler) | Remove data from server |
Key Takeaways
Use express.json() middleware to parse JSON request bodies.
Define routes with app.get, app.post, app.put, and app.delete for RESTful API.
Always send a response to avoid hanging requests.
Handle errors and missing data with proper status codes.
Start the server with app.listen on a chosen port.