How to Create REST API in Node.js with Express
To create a REST API in
Node.js, use the Express framework to handle HTTP requests and define routes for different API endpoints. Set up routes with methods like GET, POST, PUT, and DELETE to manage data and send JSON responses.Syntax
Here is the basic syntax to create a REST API route in Node.js using 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 or POST, PATH is the URL path, and HANDLER is a function to handle requests.res.json(DATA): Send JSON response to client.app.listen(PORT): Start server on given port.
javascript
const express = require('express') const app = express() app.use(express.json()) app.get('/api/example', (req, res) => { res.json({ message: 'Hello from API' }) }) app.listen(3000, () => { console.log('Server running on port 3000') })
Output
Server running on port 3000
Example
This example shows a simple REST API with Express that handles GET and POST requests to manage a list of items in memory.
javascript
const express = require('express') const app = express() app.use(express.json()) let items = [] // Get all items app.get('/api/items', (req, res) => { res.json(items) }) // Add a new item app.post('/api/items', (req, res) => { const newItem = req.body items.push(newItem) res.status(201).json(newItem) }) app.listen(3000, () => { console.log('API server running on port 3000') })
Output
API server running on port 3000
Common Pitfalls
Common mistakes when creating REST APIs in Node.js include:
- Not using
express.json()middleware, so JSON request bodies are undefined. - Forgetting to send a response, causing the request to hang.
- Using wrong HTTP methods or paths that don't match client requests.
- Not handling errors or invalid input properly.
javascript
/* Wrong: Missing JSON middleware, so req.body is undefined */ const express = require('express') const app = express() app.post('/api/data', (req, res) => { // req.body will be undefined res.json(req.body) }) app.listen(3000) /* Right: Add express.json() middleware */ app.use(express.json())
Quick Reference
Here is a quick reference for creating REST API routes in Express:
| HTTP Method | Purpose | Example Route |
|---|---|---|
| GET | Retrieve data | app.get('/api/items', handler) |
| POST | Create new data | app.post('/api/items', handler) |
| PUT | Update existing data | app.put('/api/items/:id', handler) |
| DELETE | Delete data | app.delete('/api/items/:id', handler) |
Key Takeaways
Use Express framework with express.json() middleware to create REST APIs in Node.js.
Define routes with app.get, app.post, app.put, and app.delete for different API actions.
Always send a response to avoid hanging requests.
Test your API endpoints with tools like Postman or curl.
Handle errors and invalid input gracefully in your API.