Build Your First REST API with Node.js and Express
Node.js and Express are among the most popular choices for building REST APIs quickly and efficiently. This tutorial walks you through creating a working API from scratch — covering project setup, routing, middleware, and error handling.
Prerequisites
- Node.js (v18 or later) installed on your machine
- Basic familiarity with JavaScript
- A terminal and a code editor (VS Code recommended)
- Postman or curl for testing
Step 1: Initialize Your Project
Create a new directory and initialize a Node.js project:
mkdir my-api && cd my-api
npm init -y
npm install express
Also install nodemon for automatic restarts during development:
npm install --save-dev nodemon
Update your package.json scripts section:
"scripts": {
"dev": "nodemon index.js",
"start": "node index.js"
}
Step 2: Create Your Entry Point
Create index.js in your project root:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.json({ message: 'Welcome to my API!' });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Step 3: Add Resource Routes
Create a routes/ folder and add books.js to simulate a books resource:
const express = require('express');
const router = express.Router();
let books = [
{ id: 1, title: 'Clean Code', author: 'Robert C. Martin' },
{ id: 2, title: 'The Pragmatic Programmer', author: 'Hunt & Thomas' }
];
// GET all books
router.get('/', (req, res) => res.json(books));
// GET single book
router.get('/:id', (req, res) => {
const book = books.find(b => b.id === parseInt(req.params.id));
if (!book) return res.status(404).json({ error: 'Book not found' });
res.json(book);
});
// POST new book
router.post('/', (req, res) => {
const newBook = { id: books.length + 1, ...req.body };
books.push(newBook);
res.status(201).json(newBook);
});
module.exports = router;
Register the route in index.js:
const booksRouter = require('./routes/books');
app.use('/api/books', booksRouter);
Step 4: Add Error Handling Middleware
Always add a global error handler as the last middleware in your Express app:
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong' });
});
Step 5: Test Your API
Run the server with npm run dev, then test your endpoints:
- GET
http://localhost:3000/api/books— returns all books - GET
http://localhost:3000/api/books/1— returns book with ID 1 - POST
http://localhost:3000/api/books— creates a new book (send JSON body)
Next Steps
Now that your API is working, consider adding: input validation with Joi or Zod, a real database with Prisma or Mongoose, authentication via JWT, and documentation with Swagger/OpenAPI. Each of these takes your API from a prototype to a production-ready service.