How to Build a REST API with Node.js: A Step-by-Step Guide
Building a REST API with Node.js is a core skill for modern backend developers. Node.js, paired with Express, delivers a minimal yet powerful framework for creating fast, scalable APIs. In this tutorial, you’ll learn how to structure a REST API with full CRUD operations.
Prerequisites include a working installation of Node.js and npm, a code editor, and basic familiarity with JavaScript. This guide assumes you are starting from an empty project folder.
1. Initialize the Project
Open a terminal, create a new directory, and run npm init -y to create a package.json file. Then install the dependencies: npm install express and npm install body-parser. Express will handle routing, while body-parser parses incoming JSON payloads.
2. Set Up the Server
Create an index.js file and import Express with require('express'). Initialise the app with express(), add the body-parser middleware, and define an array to hold in-memory data. Finally, listen on port 3000.
3. Implement CRUD Routes
Define your API endpoints. Use GET /api/items to fetch all records and GET /api/items/:id to retrieve a single record. Add POST /api/items to create a new entry. Use PUT /api/items/:id to update an existing record and DELETE /api/items/:id to remove one. Always send appropriate status codes.
4. Test the API
Run the server with node index.js. Use Postman or cURL to send requests to http://localhost:3000/api/items. Test each HTTP method to confirm everything works.
Conclusion
You now have a working REST API built with Node.js. Take it further by integrating a database like MongoDB, adding validation, and implementing authentication.