Table of Contents
Creating a basic CRUD (Create, Read, Update, Delete) API in Node.js can be accomplished using the Express framework, which simplifies the process of building web applications and APIs. This guide provides a step-by-step walkthrough for creating a basic CRUD API, showcasing best practices and practical coding techniques.
We created this API to help new developers and those looking to expand their skills in building modern web applications using Node.js and Express. Whether you're just starting out with backend development or want to strengthen your understanding of Express.js, this example will serve as a simple yet powerful foundation.
Throughout this guide, you'll learn how to set up a Node.js project, create API routes, and integrate them with a database to handle basic data operations. By the end, you'll have a fully functional API that you can use as a starting point for your own projects or to deepen your understanding of backend technologies.
Prerequisites
- Node.js installed on your machine. You can download it from Node.js official website.
- npm (Node Package Manager), which comes with Node.js.
- A text editor or an IDE (like Visual Studio Code).
1: Set up the Project
Create a new directory for your project and navigate into it:
1 2 |
mkdir crud-api cd crud-api |
Initialize a new Node.js project:
1 |
npm init -y |
Install Express and other required packages:
1 |
npm install express body-parser cors |
2: Create the Basic Server
Create a new file named server.js in your project folder.
Add the following code to server.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const app = express(); const PORT = process.env.PORT || 3000; // Middleware app.use(cors()); app.use(bodyParser.json()); // Sample data (in-memory storage) let users = []; // CRUD Operations // Create a user app.post('/users', (req, res) => { const user = req.body; users.push(user); res.status(201).json(user); }); // Read all users app.get('/users', (req, res) => { res.json(users); }); // Read a single user by ID app.get('/users/:id', (req, res) => { const userId = req.params.id; const user = users.find(u => u.id === userId); if (user) { res.json(user); } else { res.status(404).send('User not found'); } }); // Update a user by ID app.put('/users/:id', (req, res) => { const userId = req.params.id; const userIndex = users.findIndex(u => u.id === userId); if (userIndex > -1) { users[userIndex] = { ...users[userIndex], ...req.body }; res.json(users[userIndex]); } else { res.status(404).send('User not found'); } }); // Delete a user by ID app.delete('/users/:id', (req, res) => { const userId = req.params.id; users = users.filter(u => u.id !== userId); res.status(204).send(); }); // Start the server app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); }); |
3: Run the Server
To start your server, run the following command in your terminal:
1 |
node server.js |
You should see the message indicating that the server is running.
4: Test the API
You can use tools like Postman or cURL to interact with your API.
Create a User
- Method: POST
- URL: http://localhost:3000/users
- Body: { "id": "1", "name": "John Doe", "email": "[email protected]" }
Read All Users
- Method: GET
- URL: http://localhost:3000/users
Read a User by ID
- Method: GET
- URL: http://localhost:3000/users/1
Update a User
- Method: PUT
- URL: http://localhost:3000/users/1
- Body: { "name": "John Smith" }
Delete a User
Method: DELETE
URL: http://localhost:3000/users/1
Conclusion
This is a simple CRUD API using Node.js and Express. It uses an in-memory array to store user data, which will be lost when the server restarts. For a production application, consider using a database (like MongoDB, PostgreSQL, etc.) to persist data.