Creating a RESTful API with Node.js and MongoDB
Leandro Lima
Posted on April 26, 2023
Creating a RESTful API with Node.js and MongoDB
In this tutorial, we'll be building a single-page Node.js RESTful API with MongoDB as our data store. We'll look at how to set up a basic Node.js server, create the necessary routes to make requests, and then interact with a MongoDB instance. Our goal is to build a RESTful API that can handle user authentication and data storage. We'll also make use of a few Node.js packages such as Express and Mongoose to help make development easier.
Setting Up the Server
Before constructing our Node.js applications, we need to set up our server. If you don't have an existing Node.js server available, you can use a cloud platform like Heroku or DigitalOcean that offer Node.js hosting.
Install Packages
Once we have our Node.js server set up, we need to install some packages to make our development easier. We'll be making use of the Express and Mongoose packages for our application. For example, to install Express, we'll use this command:
npm install express
For Mongoose, we can use:
npm install mongoose
Create Routes with Express
Now that we have our basic server setup and our packages installed, we can create our routes with Express. Express allows us to map routes to specific URL paths, HTTP verbs, and callbacks for each route. We can set up some basic routes with the following code:
const express = require('express');
const app = express();
// Root route
app.get('/', (req, res) => {
res.send('Hello World!');
});
// Other routes
app.get('/about', (req, res) => {
res.send('About page');
});
// Start server
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running at port ${port}`);
});
From this code, we can see that when a route is requested, Express will call the associated callback with a request and response parameter. The request parameter contains information about the request, such as the query parameters and HTTP verb. The response parameter can be used to respond to the client, such as sending a response body or setting headers.
Connect to MongoDB
Once we have our routes setup, we can move on to connecting to our MongoDB instance. To do this, we'll make use of Mongoose. We can set up our Mongoose connection using the following code:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true});
This code will connect to the MongoDB instance on the default port (27017) and the test
database. Once our connection is established, we can start creating our models and interacting with our database.
Create Models with Mongoose
Once our connection is setup, we can start creating our models. Mongoose allows us to create schemas for our data that define the types and validations for our data. For example, we could create a user model with the following code:
const userSchema = new mongoose.Schema({
username: {type: String, required: true},
email: {type: String, required: true},
password: {type: String, required: true}
});
const User = mongoose.model('User', userSchema);
This code creates our user model with the required fields. Once our models are set up, we can move on to the last step of creating our API.
Implement API Endpoints
Now that our models are set up, we can start creating our API endpoints. We'll use the Express routes we created earlier to handle our API requests. For example, we can implement a registration endpoint by using the following code:
// Register endpoint
app.post('/register', async (req, res) => {
const { username, email, password } = req.body;
if(!username || !email || !password) {
return res.status(400).send({error: 'All fields required.'});
}
try {
const user = new User({ username, email, password});
await user.save();
res.send(user)
} catch(err) {
console.log(err);
res.status(500).send({error: 'Error registering new user, please try again.'});
}
});
From this code, we can see that when a request is made to the /register
endpoint, we first check that all the required fields are present. If they are, we create a new user instance and save it to our database. We then respond with the user instance.
Conclusion
In this tutorial, we looked at how to create a Node.js RESTful API with MongoDB as our data store. We discussed how to set up a basic Node.js server, install packages to make development easier, and create routes with Express. We then connected to our MongoDB instance and setup our models with Mongoose. Finally, we implemented some API endpoints to handle user authentication and data storage. Hopefully this tutorial provided some insight into creating RESTful APIs with Node.js and MongoDB.
For further reading, you can check out the following blog post discussing microservice architectures with Node.js, TypeScript, and gRPC Building a Microservice Architecture with Node.js, TypeScript, and gRPC.
Posted on April 26, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.