This tutorial aims to guide you through the process of building a basic REST API. The API will be able to perform fundamental operations like creating, reading, updating, and deleting data (CRUD operations).
By the end of this tutorial, you will be able to:
- Set up a server using Node.js and Express.js
- Define routes and controllers
- Interact with a database using MongoDB
You should have a basic understanding of:
- JavaScript programming language
- Node.js and npm (Node package manager)
- MongoDB
We will use Node.js and Express.js to set up our server. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
Before proceeding, ensure you have Node.js installed. If not, download it from the official Node.js website. Node.js comes with npm, which we will use to install Express.js.
To create a new Node.js application, create a new directory and initialize it with npm:
mkdir myapp
cd myapp
npm init
This will create a package.json file in your application directory.
Next, install Express:
npm install express --save
Create a new file named app.js
and add the following code:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Run your application with the command node app.js
and visit http://localhost:3000
in your browser. You should see 'Hello, World!'.
Routes are used to determine how an application responds to a client request for a specific endpoint. Let's add a route for each of the CRUD operations:
app.get('/users', getUsers); // Get all users
app.get('/users/:id', getUser); // Get a single user by id
app.post('/users', createUser); // Create a new user
app.put('/users/:id', updateUser); // Update a user by id
app.delete('/users/:id', deleteUser); // Delete a user by id
Controllers handle the logic for each route. Let's define these controllers:
function getUsers(req, res) {
// Code to fetch users from the database
}
function getUser(req, res) {
// Code to fetch a single user by id from the database
}
function createUser(req, res) {
// Code to create a new user
}
function updateUser(req, res) {
// Code to update a user by id
}
function deleteUser(req, res) {
// Code to delete a user by id
}
In this tutorial, we have covered:
- Setting up a server using Node.js and Express.js
- Defining routes and controllers for various operations
- A brief introduction to interacting with a MongoDB database
For next steps, consider:
- Learning more about database interaction with MongoDB
- Exploring more advanced features of Express.js
Remember, practice is key when learning web development. Don't hesitate to experiment and try different things!