Estimated reading time: 2 minutes
In this tutorial, we’ll walk through the steps to create a simple REST API using Node.js and Express. By the end, you’ll have a fully functional API that can handle CRUD (Create, Read, Update, Delete) operations.
Prerequisites
Before we begin, make sure you have the following installed:
- Node.js (v18 or higher)
- npm (Node Package Manager)
- A code editor (e.g., Visual Studio Code)
Step 1: Set Up Your Project
- Open your terminal and create a new project folder:
mkdir nodejs-api cd nodejs-api
- Initialize a new Node.js project:
npm init -y
- Install Express:
npm install express
Step 2: Create the Server
- Create a new file called
server.js
and add the following code:const express = require('express'); const app = express(); // Middleware to parse JSON app.use(express.json()); // Define a simple route app.get('/', (req, res) => { res.send('Hello, World!'); }); // Start the server const PORT = 3000; app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
- Run the server:
node server.js
- Open your browser and navigate to http://localhost:3000. You should see “Hello, World!” displayed.
Step 3: Add CRUD Operations
Let’s expand our API to handle CRUD operations for a simple “tasks” resource.
- Add the following code to
server.js
:let tasks = []; // Create a task app.post('/tasks', (req, res) => { const task = req.body; tasks.push(task); res.status(201).send(task); }); // Get all tasks app.get('/tasks', (req, res) => { res.send(tasks); }); // Update a task app.put('/tasks/:id', (req, res) => { const id = req.params.id; const updatedTask = req.body; tasks[id] = updatedTask; res.send(updatedTask); }); // Delete a task app.delete('/tasks/:id', (req, res) => { const id = req.params.id; tasks.splice(id, 1); res.status(204).send(); });
- Test your API using tools like Postman or curl.
Conclusion
Congratulations! You’ve built a simple REST API using Node.js and Express. This is just the beginning—you can expand this API by adding authentication, connecting to a database, or deploying it to the cloud.
Let me know if you have any questions or need further assistance. Happy coding!
Share this content:
Click to rate this post!
[Total: 0 Average: 0]