How to Build Your Own RESTful API — Node.js & MongoDB

Photo by James Harrison on Unsplash

Developers in the tech industry love to discover and consume APIs. It is one of the most efficient and quickest way to provide public data. Ways to provide public data are quickly evolving, and you need to offer data in a simple and powerful API. 🎯

An API refers to Application Programming Interface whereas REST API refers to Representational State Transfer. It is used for web based architecture for data communication. It also uses HTTP to make calls between machines.

When Web services use REST architecture, they are called RESTful APIs or REST APIs. 💻 🔁 🌏

  • REST API is a set of web addresses that respond with pure information, not a formatted web page.
  • An API returns a JSON, which is a common format. You’ll see all of the information surrounded with quotation marks, {}, [] and descriptive titles for each bit of info.

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine and is very useful in creating quick and scalable APIs.

MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas.

Let’s start writing some Javascript and build a RESTful API in Node.js.

Prerequisites 📝

To build a RESTful API we will use :

Installation ⚙️

By installing the the following tools we will be able to start using Node.js and all its fantastic features.

  • Install nvm — Node Version Manager
  • Install npm — Node Package Manager
  • Install Node.js
  • Install and setup MongoDB — refer to this documentation

…Javascript is an ever evolving language with many versions of a library or framework. It can be quite difficult to always update packages and versions.

Here where nvm comes into play. By installing nvm we will be able to to installing the latest version of Node and npm.

Check out nvm documentation here

After installing node and npm for the first time, restart your command line to apply all the new changes.

You can always check the version of the tools you are using and stay updated. Also, make sure to always to refer to the documentation for help.

npm --version  node --version

Implementation 🖥

In this example we will be creating data for tech articles (provided a simple example to get started)

First we need to make sure that we have MongoDB installed in our system. After that open a new tab in your terminal and run

mongod

in a third tab run

mongo

running mongo will give us incredible access the all local databases on our machine where we can apply CRUD. Alternatively, you can use an application with an interface to easily manage — check out Robo3T which is specially made for MongoDB.

After that we have two options to add data to our database either by creating a database, a collection and adding to documents to that or we can use the code to insert data into the database.

In the event you choose to add data to your database by Robo3T, you can use the following example to get started.

{
"_id" : ObjectId("6043b3c4347e415633bd732b"),
"title" : " Javascript ",
"content" : " used by all web browsers, Meteor, and lots of other frameworks"
}


{
"_id" : ObjectId("6043b3c857e41543433bd733a"),
"title" : " Go ",
"content" : " newer language, built for speed."
}


{
"_id" : ObjectId("6043b3c8574434155633bd733d"),
"title" : " Objective-C ",
"content" : " the programming language behind iOS (your iPhone), lead by Apple"
}


{
"_id" : ObjectId("6043b3c857e443433bd7340"),
"title" : " Swift ",
"content" : " Apple’s newest programming language"
}


{
"_id" : ObjectId("6043b3c857e41565653bd7346"),
"title" : " Node.js ",
"content" : " a server-side javascript framework"
}


{
"_id" : ObjectId("6043b3c857e41556565bd7349"),
"title" : "Django",
"content" : "a full-stack framework built using python"
}

{
"_id" : ObjectId("6043b3c857e4123233bd734f"),
"title" : "MongoDB ",
"content" : "is an open-sourced NoSQL database and is currently the only database supported by Meteor."
}


{
"_id" : ObjectId("6043b3c857e419890633bd7352"),
"title" : "REST ",
"content" : "is a protocol mainly used for API’s. It has standard methods like GET, POST, and PUT that let information be exchanged between applications."
}


{
"_id" : ObjectId("6043d3a583489817cf21d7bf"),
"title" : "React",
"content" : "React is an open-source, front end, JavaScript library for building user interfaces or UI components",
"__v" : 0
}

Note __v refers to the version and could be disabled by setting it to false in the code. However, I don’t recommend disabling it.

In your command line first tab, make sure that you are in the same directory where you will be creating your files.

Run the following command to initialise npm and you can press enter to accept the default

npm init

npm is the node package manager. It will describe what packages we need to run the server, how to run the server from the cli, and store what version of our code we are developing.

Running the above init command will ask you some questions, such as, what you want to name the project, description, author, and version.

This will create a file called package.json, which will include all of the project’s packages and their versions.

Now let’s install the rest of the packages we need…

Express is a simple router for Node.js. It allows a developer to create simple endpoints quickly. There are many routers for Node.js, but Express is the most popular, with great documentation, and many examples.

we will install express, body-parser, mongoose

npm install express body-parser mongoose

The above npm command will install all the packages we want in one go. You can always refer back to your package.json to check your dependencies.

create a server.js file in your directory

touch server.js

Now, we have everything ready to start building our own RESTful API

Let’s write some JavaScript to require the packages we just installed, spin the server and create our database connection.

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3000;const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(PORT, () => {
console.log("Server is spinning and listening on port " + PORT);
});

To create our database and connection we will be using mongoose package which will make it quite easy to establish connection, create schema, and model.

Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.

uri = "mongodb://localhost:27017/blogDB";mongoose.connect(uri, {useNewUrlParser: true,useUnifiedTopology: true,});const articleSchema = mongoose.Schema({title: String,content: String,});const Article = mongoose.model("article", articleSchema);

In the above code, uri is pointing to our local machine and the final name “blogDB” is the database name that will be automatically created when running the server or will be pointed to the same database if it was created previously.

There are several deprecations in the MongoDB Node.js driver that Mongoose users should be aware of. Mongoose provides options to work around these deprecation warnings

For that reason, I have added use”NewUrlParser”, and “useUnifiedTopology”

Next creating a schema, in this example it’s a simple one to get you started. The schema above has two fields “title” and “content” — note that you can add more fields and customise them more. Also, for validation, mongoose makes it easy as well to add validation — check out their documentation for more info.

Finally creating a model (collection), note that when creating a model, mongoDB naming convention is that the collection name has to be in lowercase letter and in a singular form. Cleverly enough it will automatically change the collection name to plural and capitalise the first letter.

Planning API

It’s considered best practice, when creating an API, to version your endpoints, that way you can maintain compatibility with older services, while continuing to improve your API. In this example we won’t version the endpoints.

In order to requests all the articles and start testing, let’s write a GET request

Request for all articles

GET

app.route("/articles").get((req, res) => {Article.find((err, foundArticles) => {if (err) {console.log(err);} else {console.log(foundArticles);res.send(foundArticles);}});})

Note that in the code above we are using express route chaining which will makes it easier to manage and help us keep the code clean and DRY.

Get request will get us all the articles in that specific route, and inside we use find method to get all the articles in the database without adding conditions.

Screenshot from PostMan (Get request)

In your Postman client, you can add your development url, localhost in my example and port 3000, and then add the route where it should look and what you specified in the code.

POST

.post((req, res) => {const newArticle = new Article({title: req.body.title,content: req.body.content,});newArticle.save();})

Continuing the route chaining we add .post method to send data to our sever and by using save() mongoDB method, we can save the data send to the database. To test it in Postman, check the screenshot below

Using body-parser npm package allowed us to insert data using the req.body as shown above.

DELETE

.delete((req, res) => {Article.deleteMany((err) => {if (!err) {console.log("successfully deleted all the articles");} else {console.log(err); }}) });

In the above delete method, notice that it’s still pointing to the main route we specified earlier which will delete all the articles if run on Postman. We use modelName.deleteMany({condition }, (err)=>{})

Request for a specific article

We need to use route chaining again because now we are targeting a specific article and url will change

GET

app.route("/articles/:articleTitle").get((req, res) => {Article.findOne({ title: req.params.articleTitle }, (err, foundArticle) => {if (!err) {res.send(foundArticle);} else {res.send("No article found", err);} });})

using the article title above and passing it to the route using params will give you the option to choose however you want how to select articles from the database — in our case it’s articleTitle

In the above screenshot, I added “python” to the end of my endpoint which will pass in as title and use findOne method from MongoDB to find that specific article.

PUT

In this .put method I can update the articles in the database.

.put((req, res) => {Article.update({ title: req.params.articleTitle },{ title: req.body.title, content: req.body.content, }, { overwrite: true }, (err) => {if (!err) {console.log("successfully updated the article");} else {console.log(err);}}); })

PATCH

.patch((req, res) => {Article.update({ title: req.params.articleTitle }, { $set: req.body }, (err) => {if (!err) { res.send("successfully updated article");} 
else {res.send(err);}}) });

In the patch request, we can update the data, but only the field that we provided data for

DELETE

.delete((req, res) => {Article.deleteOne({ title: req.params.articleTitle }, (err) => {if (!err) {res.send("successfully deleted the article");} else {res.send(err);}});});

Conclusion

In this article, we have build our own RESTful API in Node.js and connecting it to a real database.

Follow me on GitHub 👨‍💻

--

--

--

Every time I complete building something useful and fun I realise the immense satisfaction I get from it. I hope someday my code can help lots of people.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Build a recipe app fetching API using React

Build A Production Ready Node/Express API With Docker

One-way Data Flow (in AngularJS 1.6)

Angular Framework

Creating Maintainable Interface Patterns

How to use Tesseract OCR in React Native Android( Without Expo )

Creating a simple website with Node.js, Express and EJS view engine

Multiply Strings

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ayman

Ayman

Every time I complete building something useful and fun I realise the immense satisfaction I get from it. I hope someday my code can help lots of people.

More from Medium

Backend OF Shopclues.com

Defining Routes with Express JS for your App

Node.Js for Web Application Development

How to make a small calculator using Express