Application Programming Interface is short for API. An API is a software interface that allows two applications to communicate with each other. In other words, an API is a messenger that sends your request to the provider and then sends the response back to you.
💡 Fun fact: 60% of eBay transactions are done through their API
In this tutorial, we will create a RESTful CRUD (Create, Retrieve, Update, Delete) API with Node.js, Express and MongoDB.
Creation of the application
On your desktop (or any other location), create a new folder named nodejs-api
and open it in any code editor (for this tutorial I'm using VS Code). Once you're done, open the terminal (you can use the VS Code terminal or an external terminal) and run
npm init -y
This will generate a simple package.json and now we need to install some dependencies that we need. Turn on your terminal and run
npm install express body-parser mongoose
💡 Mongoose is an ODM (Object Document Mapping) tool for Node.js and MongoDB. It helps you convert objects in your code into documents in the database and vice versa.
This will install Express (for the server), Mongoose and Body Parse to parse the data.
💡 The body-parser middleware converts the text sent via an HTTP request into a target format or, in other words, body-parser parses your request and converts it into a format from which you can easily extract the relevant information you might need.
Now once everything is installed, we can start creating our web server.
Web server configuration
Create a new file named server.js
in the root folder of the application and add the following code there
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get("https://blog.suhailkakar.com/", (req, res) => {
res.json({"message": "Server is running :D"});
});
let PORT = 8080
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
In the code above
- First of all, we imported the dependencies we need, i.e. Express and Body Parser.
- Second, once we imported them, we added body scanning middleware using Express's app.use() method.
- Next, we defined a simple GET route that returns a message that the server is running.
- Finally, we set the port and listened to that port for incoming connections
Now in your terminal run node server.js
and go to http://localhost:8080
to access the route we have just defined. and you should see
{
message: "Server is running :D"
}
Connect our application to MongoDB
In server.js
import the mongoose, just like the code below
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
and add the code below after
mongoose.connect(YOUR_MONGODB_URL, {
useNewUrlParser: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Error...', err);
process.exit();
});
finally, this is how your server.js
should look like now
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect(YOUR_MONGODB_URL,
{
useNewUrlParser: true,
}
)
.then(() => {
console.log("Successfully connected to the database");
})
.catch((err) => {
console.log("Could not connect to the database. Error...", err);
process.exit();
});
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get("https://blog.suhailkakar.com/", (req, res) => {
res.json({ message: "Server is running :D" });
});
let PORT = 8080;
app.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
Define model in Mongoose
Now in the root directory create a new folder named app
and inside create another folder named models
. Create a new file named app.model.js
and add the following code inside
const mongoose = require("mongoose");
const AppSchema = mongoose.Schema({
message: String,
});
module.exports = mongoose.model("App", AppSchema);
This template contains a field that is message
Define routes
Now create a new folder called routes inside the application folder and add the following code inside
module.exports = (app) => {
const App = require("../controllers/app.controller.js");
app.post("/create", App.create);
app.get("/get-all", App.findAll);
app.get("/message/:messageId", App.findOne);
app.put("/message/:messageId", App.update);
app.delete("/message/:messageId", App.delete);
};
include the routes in server.js. Add the following require statement before the app.listen() line in the server.js file.
require('./app/routes/app.routes.js')(app);
Writing controller functions
Create a new folder called controllers in the app folder, then create a new file called app.controller.js in the app/controllers folder with the following content:
const App = require("../model/app.model.js");
exports.create = (req, res) => {
const message = new App({
message: req.body.message,
});
message
.save()
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the Message.",
});
});
};
exports.findAll = (req, res) => {
App.find()
.then((data) => {
res.send(data);
})
.catch((err) => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving messages.",
});
});
};
exports.findOne = (req, res) => {
App.findById(req.params.messageId)
.then((data) => {
if (!data) {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
res.send(data);
})
.catch((err) => {
if (err.kind === "ObjectId") {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
return res.status(500).send({
message: "Error retrieving message with id " + req.params.messageId,
});
});
};
exports.update = (req, res) => {
App.findByIdAndUpdate(
req.params.messageId,
{
message: req.body.message,
},
{ new: true }
)
.then((data) => {
if (!data) {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
res.send(data);
})
.catch((err) => {
if (err.kind === "ObjectId") {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
return res.status(500).send({
message: "Error updating message with id " + req.params.messageId,
});
});
};
exports.delete = (req, res) => {
App.findByIdAndRemove(req.params.messageId)
.then((data) => {
if (!data) {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
res.send({ message: "Message deleted successfully!" });
})
.catch((err) => {
if (err.kind === "ObjectId" || err.name === "NotFound") {
return res.status(404).send({
message: "Message not found with id " + req.params.messageId,
});
}
return res.status(500).send({
message: "Could not delete message with id " + req.params.messageId,
});
});
};
restart your node.js server and 💥 now we have our API ready
Test APIs with Postman
- Create and save a new message
- Retrieve all messages from database
- Search for a single message with a
messageId
- Update a message identified by the
messageId
in the request
- Delete a message with the specified
messageId
in the request
Conclusion ⌛
I hope you found this article useful. If you need any help, let me know in the comments section.
You can find the full source code here
Let's connect on Twitter And LinkedIn
👋 Thanks for reading, see you next time