How to create an API endpoint in Node.js

·

3 min read

Node.js is a popular JavaScript runtime environment used to build web applications. It can be used to create high-performance backend applications. It has a large open-source community, and it can be written with our beloved JavaScript programming language. In this article, we will attempt to show you how APIs can be created in Node.js using the express framework.

Table of Contents

  1. API verbs

  2. Routes

  3. Controller methods

  4. Conclusion

API Verbs

API verbs also known as REST verbs are used to determine the operations to be performed on a particular route. They represent the Create, Read, Update, and Delete (CRUD) operations that are to be performed in the application. The most popular of them are GET, POST, PUT, PATCH and DELETE.

Routes

To create an API in express we need to create a file where we instantiate express.js. This instance will then be used to listen to the server. From there we can also call the use method to pass the route. A route is the address of a specific endpoint that is being called with the API verbs.

const express = require("express");

//Route files

const products = require("./routes/products");

const app = express();

app.use(express.json());

//Mount routers

app.use("/api/v1/products", products);

const PORT = process.env.PORT || 5000;

app.listen(
  PORT,

  console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`)
);

In the code above a server.js file where express has been instantiated. A route called products has been created.

const express = require("express");

...

const router = express.Router();

router.route("/").get(getProducts).post(createProduct);

router.route("/:productId").delete(deleteProduct);

module.exports = router;

A product.js route file where all the routes are being implemented.

Controller Methods

When we create our routes the final part of creating an API endpoint involves creating a controller method. A controller is a method that contains the logic that handles the response that will be sent to the client when a request is made to a particular endpoint.

Sample code for how a controller should look like:

const asyncHandler = require("../middleware/async");
const Product = require("../models/Product");

// @desc    Get all products
// @route   GET /api/v1/products
// @access  Public
exports.getProducts = asyncHandler(async (req, res, next) => {
  const products = await Products.find();

  res.status(200).json({
    success: true,

    data: products,
  });
});

In the code snippet above you can see an implementation of a controller method to get all products in a database. The method when successful returns a success status of true and a list of all the products.

Conclusion

We can see how straightforward it is to create an API endpoint in Node using express.js. The idea is to create a route, a controller method for your logic, and call the right verb on your route. Also, you need to take care of error handling although that's not covered in this article. You can learn more by practicing creating APIs on your projects from what you learned in this article.