RESTful API is a structured and scalable way of architectural design used by different software components to communicate over a network.
Prerequisites: NPM or Node Package Manager must be installed from their website.
You need to use some text editors like Visual Studio Code, and javascript basic knowledge is important.
Following are the steps needed in the deploying of a restful API.
- Step 1: Initialize Your Project.
- Step 2: Install Dependencies.
- Step 3: Create an Express App.
- Step 4: Define Routes.
- Step 5: Run Your API.
- Step 6: Add More Routes.
- Step 7: Testing Your API.
- Step 8: Deploy Your API.
To begin, make sure you have Node.js and npm installed. Create a new project folder and initialize it with npm init to set up your package.json file. Install Express using npm install express.
Setting up Express
Now just create an index.js file and add the following codes.
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.json()); // Enable JSON parsing
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
This basic step includes Express and configuring it to parse JSON.
Routes:
In a REST API, routes define the endpoints for different HTTP methods (GET, POST, PUT, DELETE). Let’s create a simple example with a GET request.
const todos = [
{ id: 1, text: 'Learn Express', done: false },
{ id: 2, text: 'Build RESTful API', done: true }
];
app.get('/todos', (req, res) => {
res.json(todos);
});
app.get('/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
const todo = todos.find(todo => todo.id === id);
if (!todo) {
res.status(404).json({ error: 'Todo not found' });
} else {
res.json(todo);
}
});
Check the two routes the first one returns all todos, while the second one returns a special route depending on the id.
Handle POST requests.
app.post('/todos', (req, res) => {
const { text } = req.body;
const newTodo = { id: todos.length + 1, text, done: false };
todos.push(newTodo);
res.status(201).json(newTodo);
});
This route expects a JSON payload with a ‘text’ property and adds a new todo to the list.
Updating and Deleting:
Updating and deleting routes are given below
app.put('/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
const todo = todos.find(todo => todo.id === id);
if (!todo) {
res.status(404).json({ error: 'Todo not found' });
} else {
todo.text = req.body.text || todo.text;
todo.done = req.body.done || todo.done;
res.json(todo);
}
});
app.delete('/todos/:id', (req, res) => {
const id = parseInt(req.params.id);
const index = todos.findIndex(todo => todo.id === id);
if (index === -1) {
res.status(404).json({ error: 'Todo not found' });
} else {
const deletedTodo = todos.splice(index, 1);
res.json(deletedTodo[0]);
}
});
Congratulations! You have successfully built a basic RESTful API using ExpressJS. Customize and enhance it based on your project requirements. For more advanced features, refer to the Express documentation.
Sreyas is a prominent software and mobile app development firm, boasting extensive expertise in UI/UX design. Our global presence allows us to offer a comprehensive range of services, including data migration, database management, web hosting, infrastructure management, and more to clients worldwide.