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
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.