How to Build a RESTful API with Node.js: A Beginner’s Guide
Node.js is a powerful, lightweight runtime for building fast and scalable APIs. In this tutorial, you’ll create a simple RESTful API using Express, the most popular Node.js web framework. By the end, you’ll have a working endpoint that returns JSON data—and the foundation to build more complex APIs.
Before you start, make sure Node.js and npm are installed on your machine. Open your terminal and create a new folder: mkdir my-api && cd my-api. Then initialize a project with npm init -y. You’ll also need to install Express: npm install express.
1. Set Up Your Project
Create a file named index.js in the project root. Import Express and create an app instance:
- Add
const express = require('express'); - Add
const app = express(); - Add
const PORT = process.env.PORT || 3000; - Tell the app to listen:
app.listen(PORT, () => console.log('Server running'));
2. Create Your First Route
Define a GET route that returns sample data. Add this before the listen call:
app.get('/api/items', (req, res) => { res.json([{ id: 1, name: 'Item A' }]); });- Run
node index.jsand visithttp://localhost:3000/api/itemsin your browser to see the JSON response.
3. Add Error Handling and Middleware
Express makes it easy to handle errors. Add a 404 handler for unknown routes:
app.use((req, res) => res.status(404).json({ error: 'Not found' }));- Use middleware like
app.use(express.json())to parse incoming JSON bodies for POST requests.
That’s it! You now have a working Node.js API. Test it with a tool like Postman, then expand by adding POST, PUT, DELETE routes and connecting a database. Node.js scales effortlessly from here.