Table of Contents
In this tutorial, we will walk through the process of creating a RESTful API using Node.js. This guide is intended for beginners and will cover all the essential steps to get your API up and running.
Prerequisites
Before we begin, ensure you have the following installed on your machine:
- Node.js: Download and install Node.js from the official website.
- NPM: Node Package Manager comes with Node.js and is used to manage packages.
- Postman: A tool for testing APIs.
Setting Up Your Project
First, create a new directory for your project and navigate into it:
- Open your terminal.
- Run
mkdir my-apito create a new folder. - Navigate into the folder with
cd my-api.
Next, initialize a new Node.js project:
- Run
npm init -yto create apackage.jsonfile.
Installing Required Packages
We will need to install Express, a web framework for Node.js, to simplify our API development:
- Run
npm install expressto install Express.
Creating the API
Create a new file named server.js in your project directory:
- Run
touch server.js(or create it manually).
Open server.js in your favorite code editor and add the following code:
server.js
“`javascript
const express = require(‘express’);
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.get(‘/’, (req, res) => {
res.send(‘Hello World!’);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
“`
Running the Server
To start your server, run the following command in your terminal:
node server.js
Visit http://localhost:3000 in your browser, and you should see the message “Hello World!”
Creating Routes
Next, let’s add some routes to our API. Below the existing code in server.js, add the following:
Additional Routes
“`javascript
let items = [];
app.post(‘/items’, (req, res) => {
const item = req.body;
items.push(item);
res.status(201).send(item);
});
app.get(‘/items’, (req, res) => {
res.send(items);
});
“`
Testing the API
Now that we have created our routes, we can test them using Postman:
- Open Postman.
- Set the request type to POST.
- Enter the URL http://localhost:3000/items.
- In the body, select raw and choose JSON as the format.
- Enter a JSON object, for example:
{"name": "Item 1"}. - Click Send.
You should receive a response with the created item. Now, test the GET request to http://localhost:3000/items to see all items.
Conclusion
Congratulations! You have successfully created a RESTful API with Node.js. You can expand this API by adding more routes, integrating a database, and implementing authentication.
For further learning, consider exploring the following topics:
- Middleware in Express
- Connecting to MongoDB
- Implementing JWT authentication
Happy coding!