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.

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.