You might have heard the term API (Application Programming Interface) before. It’s a way to communicate with other servers over the web.
In simpler words, API is similar to what the traditional postman works. Take the letter from one person and deliver it to the other. That’s what a POST request is.
Let us create a simple Rest API similar to Wikipedia, where we can query the database for all articles or for any specific article.
Before we start, create a new project folder, and run npm init inside it.
After that, install the following node modules in the project.
express – to use the express framework.
body-parser – for parsing the body of post requests.
mongoose – to work with MongoDB as a database.
Run the following command in the project folder to install all the above node packages,
$ npm install express body-parser mongoose
Create a JavaScript file named app.js inside the root directory of the project.
Open the app.js file and write the code to require the node packages which we just installed.
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
Connect with MongoDB on localhost (127.0.0.1) over the port 27017.
mongoose.connect("mongodb://127.0.0.1:27017/wikiDB");
Note that we have appended a wikiDB after the connection URL. This will create a database named wikiDB, if it’s not already present inside our local mongo installation.
We will now create a Model Schema for the Article object.
const articleSchema = new mongoose.Schema({
title: String,
content: String,
});
const Article = mongoose.model("Article", articleSchema);
We will now create an API route all of the articles in the database.
//////// Requests Targeting All Articles ////////
app.route("/articles")
.get(function (req, res) {
Article.find({}, function (err, foundArticles) {
if (!err) {
res.send(foundArticles);
}
else {
res.send(err);
}
});
})
.post(function (req, res) {
const newArticle = new Article({
title: req.body.title,
content: req.body.content,
});
newArticle.save(function (err) {
if (!err) {
res.send("Successfully added a new article!");
}
else {
res.send(err);
}
});
})
.delete(function (req, res) {
Article.deleteMany(function (err) {
if (!err) {
res.send("Successfully deleted all articles");
}
else {
res.send(err);
}
});
});
In the code above, we have created an API route using the express framework. The route will handle the GET, POST & DELETE requests.
We will now create an API route for a specific article in the database.
//////// Requests Targeting a Specific Article ////////
app.route("/articles/:articleTitle")
.get(function (req, res) {
Article.findOne({title: req.params.articleTitle}, function (err, foundArticle) {
if(foundArticle){
res.send(foundArticle);
}
else{
res.send("No articles matching that title was found!");
}
});
})
.put(function (req, res) {
Article.updateOne({title: req.params.articleTitle},{
title: req.body.title,
content: req.body.content,
}, {overwrite: true}, function (err) {
if(err){
res.send(err);
}
else{
res.send("Successfully overwritted the requested article!");
}
});
})
.patch(function (req, res) {
Article.updateOne({title: req.params.articleTitle}, {
$set: req.body
}, function (err) {
if(err){
res.send(err);
}
else{
res.send("Successfully updated the requested article!")
}
});
})
.delete(function (req, res) {
Article.deleteOne({title: req.params.articleTitle}, function (err) {
if(err){
res.send(err);
}
else{
res.send("Successfully deleted the requested article!");
}
});
});
In the code above, we have created an API route using the express framework. The route will handle the GET, PUT, PATCH & DELETE requests.
Finally, start the server on port 3000.
app.listen(3000, function () {
console.log("Server started on port 3000");
});
Start the server by entering the following command in the project terminal.
$ node app.js
You can test the API using the Postman with the endpoints defined in the Express Route Parameters.
View the complete project on GitHub:
To understand what GET, POST, PUT, PATCH & DELETE requests are, head over to a really useful article – https://dev.to/qbentil/http-methods-get-post-put-patch-delete-1fhi
Read Next: User Authentication & Session Management in Express & MongoDB [Google OAuth2.0 Included]