In this tutorial we are going to do two important things
- Create an API which is capable of perform CURD operation on MongoDB server
- User the API to perform CURD in a web app
Making of the API
MongoDB is NoSQL database which is capable of running on the cloud and local alike.
- How to create an API using Express in Nodejs
API is an essential part of modern apps and web applications, it allow users to perform CURD operations using one single web interface. An identical API uses JSON structure to store and retrieve data. It is suitable for mobile app or another web app.
One of the advantage of API is that it can be utilized by multiple applications. It also mean that the CURD operation need not be write again again and again in each applications.
Not sure where to start learning ?, check out these Node tutorials
API
Let’s create a simple API using
- Express
- Joi
- Nodejs
Express
Express help us create and manage web app pages or routes, it is the simplest way to create a web app in Nodejs. Many other NodeJS frameworks are build up on Express as the root.
JOI
JOI is a NPM package which help us create a schema for our API and validate.
The source code
const Joi = require("joi");
const express = require("express");
const app = express();
app.use(express.json());
const courses = [
{ id: 1, name: "course 1" },
{ id: 2, name: "course 2" },
{ id: 3, name: "course 3" },
];
app.get("/", (req, res) => {
res.send("Hello world");
});
app.get("/api/courses", (req, res) => {
res.send(courses);
});
app.post("/api/courses", (req, res) => {
const schema = {
name: Joi.string().min(3).required(),
};
const result = Joi.validate(req.body, schema);
if (result.error) {
res.status(404).send(result.error.details[0].message);
return;
}
const course = {
id: courses.length + 1,
name: req.body.name,
};
courses.push(course);
res.send(course);
});
app.delete("/api/courses/:id", (req, res) => {
const course = courses.find((c) => c.id === parseInt(req.params.id));
if (!course)
return res.status(404).send("The course not found");
const index= courses.indexOf(course)
courses.splice(index,1)
res.send(course)
});
function validateCourse(course) {
const schema = {
name: Joi.string().min(3).required(),
};
return Joi.validate(course, schema);
}
app.get("/api/courses/:id", (req, res) => {
const course = courses.find((c) => c.id === parseInt(req.params.id));
if (!course) res.status(404).send("The course not found");
res.send(course);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`listen on the port ${port}`);
});
The app has 5 APIs to perform CURD operations, as you noticed that all API routes are organized in the /api/ route which is a common standard. A secure API also uses a security key to access the data.
The API add,remove,delete,update courses. For update the data I used PUT method which is actually update all the data. .An alternative to this is a PATHCH which update one only one
The Slice method is used to remove data from the collection, Push is used to add a new data and find will fetch data from the JSON collection.
How to run and Test API
As you may noticed that this app don’t have UI for operations. API usually lack , because they are meant for developers and not to all users, so UI is less important. In order to test the API you should have Postman Like application, where you can test POST,GET,PUT APIs. Postman can be used for free, all you need to register and download the desk app for your plat form.
In the New / Next to Launch Pad you can create, test new request and in the Body – > raw you can use JSON data.
$(function () { // code block here }
HTML Web app
In the HTML file very last line of the body (</body>) tag include the script as follows, also you need to include the CDN version or local version of jQuery library.
<script src="/jquery.js"></script> -- local version of jQuery library <script src="/public/script.js"></script> -- our script
jQuery
jQuery can be placed in a file or with in HTML within <script> </script > , I used to store them as file for easy access. It is a good practice include it in a document ready function, so that we can make sure the query will only execute only when the web page loading completed.
Using the API – GET and POST request
The GET request is used to get a list of data, says product list,users list, customer list etc and the POST send data to the server. By default API call will make GET request
- GET API Call using jQuery and AJAX - How to make a get API call in HTML/web app using jQuery and AJAX
- POST API Call using jQuery and AJAX - How to make a POST API call in HTML/web app using jQuery and AJAX