How to Build a REST API with Node.js and Express

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

  1. Open your terminal and create a new project folder: mkdir nodejs-api cd nodejs-api
  2. Initialize a new Node.js project: npm init -y
  3. Install Express: npm install express

Step 2: Create the Server

  1. 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}`); });
  2. Run the server: node server.js
  3. 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.

  1. 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(); });
  2. 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]

Leave a Reply

Your email address will not be published. Required fields are marked *