This article guides you through building your first RESTful API using Node.js and Express. We’ll set up a basic server, define endpoints, and demonstrate CRUD (Create, Read, Update, Delete) operations on a sample resource. By the end, you’ll have a foundational API ready for expansion and integration with front-end applications.
Prerequisites
Before getting started, ensure you have the following:
- Node.js and npm: Install Node.js, which includes npm (Node Package Manager), to manage dependencies.
- Basic JavaScript Knowledge: Familiarity with JavaScript will help you understand Node.js and Express syntax.
To check your installation, run node -v
and npm -v
in your terminal to verify the versions.
Step 1: Setting Up the Project
1. Create a new directory for your project and navigate into it:
mkdir my-api cd my-api
2. Initialize a new Node.js project by running:
npm init -y
This will create a package.json
file, which manages your project's dependencies and scripts.
Step 2: Installing Express
Install Express as a dependency:
npm install express
Express will handle routing and middleware, allowing you to define endpoints for your RESTful API.
Step 3: Creating the Server
Create an index.js
file in your project directory to set up a basic Express server:
const express = require('express'); const app = express(); const PORT = 3000; app.use(express.json()); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
This code sets up a server that listens on port 3000 and can parse JSON data from incoming requests. Run node index.js
to start the server and check http://localhost:3000
to ensure it’s running.
Step 4: Defining CRUD Endpoints
Let’s create endpoints for managing a simple resource, such as a list of products. Add the following code to index.js
:
1. GET - Retrieve All Products
The GET method allows clients to retrieve data. We’ll create a sample array of products for demonstration purposes:
let products = [ { id: 1, name: 'Laptop', price: 999 }, { id: 2, name: 'Smartphone', price: 499 }, ]; app.get('/api/products', (req, res) => { res.json(products); });
This endpoint returns all products in the array when a GET request is sent to /api/products
.
2. POST - Add a New Product
The POST method allows clients to send data to the server to create a new resource:
app.post('/api/products', (req, res) => { const newProduct = { id: products.length + 1, ...req.body }; products.push(newProduct); res.status(201).json(newProduct); });
This endpoint adds a new product to the list when a POST request with product data is sent to /api/products
.
3. PUT - Update a Product
The PUT method allows clients to update an existing resource. We’ll update a product by ID:
app.put('/api/products/:id', (req, res) => { const { id } = req.params; const productIndex = products.findIndex(p => p.id == id); if (productIndex === -1) { return res.status(404).json({ message: 'Product not found' }); } products[productIndex] = { id: Number(id), ...req.body }; res.json(products[productIndex]); });
This endpoint updates a product based on its ID when a PUT request is sent to /api/products/:id
.
4. DELETE - Remove a Product
The DELETE method allows clients to delete a resource. We’ll delete a product by ID:
app.delete('/api/products/:id', (req, res) => { const { id } = req.params; const productIndex = products.findIndex(p => p.id == id); if (productIndex === -1) { return res.status(404).json({ message: 'Product not found' }); } products.splice(productIndex, 1); res.status(204).end(); });
This endpoint deletes a product based on its ID when a DELETE request is sent to /api/products/:id
.
Step 5: Testing the API
To test your API, you can use a tool like Postman or Insomnia. These tools allow you to send HTTP requests to your API and view responses, making it easy to verify functionality and troubleshoot any issues.
Conclusion
Building a RESTful API with Node.js and Express is a straightforward process that lays the foundation for more complex applications. By understanding how to set up a server, define endpoints, and implement CRUD operations, you’re well on your way to developing powerful APIs. This foundational API can now be expanded with features like authentication, data validation, and database integration to support real-world applications.