Table of Contents
Creating a RESTful API with Node.js is a fundamental skill for modern web developers. This tutorial will guide you through the process step-by-step, ensuring you understand each component involved in building a robust API.
Prerequisites
Before we start, make sure you have the following installed:
- Node.js: Download and install from the official website.
- npm: This comes with Node.js, but ensure it’s updated.
- A code editor: Use any code editor of your choice, such as Visual Studio Code.
Setting Up Your Project
Let’s create a new directory for our project and initialize it:
- Open your terminal and run
mkdir my-apito create a new folder. - Navigate into the folder with
cd my-api. - Initialize a new Node.js project with
npm init -y.
Installing Required Packages
We will use Express, a minimal and flexible Node.js web application framework, to build our API.
- Install Express by running
npm install express. - For handling JSON data, we will also need
npm install body-parser.
Creating the Server
Now, let’s create a simple server using Express.
Create a new file named server.js in your project directory and add the following code:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Defining Routes
Next, we will define some basic routes for our API.
Add the following code to your server.js file:
app.get('/api/items', (req, res) => { res.send('Get all items'); });
app.post('/api/items', (req, res) => { res.send('Item created'); });
Testing Your API
To test your API, you can use tools like Postman or curl.
- Open Postman and create a new request.
- Set the request type to GET and enter
http://localhost:3000/api/items. - Click Send and you should see the response:
Get all items.
Handling Data with POST Requests
Now let’s handle data sent to our API via POST requests.
Update the POST route in your server.js file:
app.post('/api/items', (req, res) => { const newItem = req.body; res.status(201).send(`Item created: ${JSON.stringify(newItem)}`); });
Using a Database
For a real-world application, you would typically use a database to store your data.
We will use MongoDB as our database. First, install the MongoDB package:
npm install mongoose
Connecting to MongoDB
In your server.js file, add the connection to MongoDB:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
Creating a Model
Next, define a model for your items:
const itemSchema = new mongoose.Schema({ name: String, price: Number });
const Item = mongoose.model('Item', itemSchema);
CRUD Operations
Now, let’s implement CRUD operations using our MongoDB model.
Update your GET and POST routes:
app.get('/api/items', async (req, res) => { const items = await Item.find(); res.json(items); });
app.post('/api/items', async (req, res) => { const newItem = new Item(req.body); await newItem.save(); res.status(201).send(newItem); });
Conclusion
Congratulations! You have built a simple RESTful API using Node.js and Express.
In this tutorial, you learned how to set up a server, handle routes, and connect to a MongoDB database.
Continue exploring by adding more features, such as authentication, error handling, and advanced query capabilities!