How to Create a REST API with Node.js: A Step-by-Step Guide
Node.js is a powerful runtime for building server-side applications, and creating a REST API with it is one of the most common tasks for back-end developers. With the Express framework, you can set up a fully functional API in minutes.
In this guide, you’ll learn how to initialize a project, install Express, build the server, and test your endpoints. Make sure Node.js and npm are installed before you begin.
Step 1: Initialize the Project
Create a folder for your API and run npm init -y to generate a package.json file. This file keeps track of your dependencies and scripts.
Step 2: Install Express
Run npm install express to add Express as a dependency. Then create an index.js file as the main entry point for your server.
Step 3: Create the Server and Define Routes
In index.js, require Express and create your app. Add the JSON middleware and start listening on port 3000:
const express = require('express');
const app = express();
app.use(express.json());
app.listen(3000);
Define routes using methods like app.get() and app.post(). For example, a simple GET response: app.get('/api', (req, res) => res.json({ message: 'Hello' }));
Step 4: Test Your API
Start the server with node index.js. Open Postman or your browser and go to http://localhost:3000/api — you should see your JSON response. Send a POST request with JSON data to check that route too.
Conclusion
Congratulations! You’ve built a REST API with Node.js and Express. From here, you can add more routes, connect a database, or deploy your API to production. Happy coding!