Free Ebook cover How to create APIs in NodeJS from basic to advanced

How to create APIs in NodeJS from basic to advanced

5

(1)

149 pages

Creating a CRUD with NodeJS and MongoDB: API Documentation

Capítulo 96

Estimated reading time: 7 minutes

Audio Icon

Listen in audio

0:00 / 0:00

One of the most crucial parts of API development is its documentation. A well-documented API is a powerful tool for developers as it makes it easy to use and understand. In this chapter, we'll cover how to document an API created with NodeJS and MongoDB, focusing on a CRUD (Create, Read, Update, Delete).

We'll start by creating a new route in our NodeJS application. We'll be using Express, a popular framework for NodeJS, to create our routes. Our route will be responsible for handling all CRUD operations for a specific resource. We will use MongoDB, a NoSQL database, to store our data.

First, let's define our route. In our routes file, we add the following code:


const express = require('express');
const router = express.Router();
const ResourceController = require('../controllers/resourceController');

router.get('/', ResourceController.getAll);
router.post('/', ResourceController.create);
router.get('/:id', ResourceController.getOne);
router.put('/:id', ResourceController.update);
router.delete('/:id', ResourceController.delete);

module.exports = router;

This code defines a new route that handles all CRUD operations for a resource. The ResourceController is a controller we'll create shortly that will handle the logic for each operation.

Now let's create our controller. In a new file, add the following code:

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app


const Resource = require('../models/resource');

exports.getAll = async (req, res) => {
    const resources = await Resource.find();
    res.json(resources);
};

exports.create = async (req, res) => {
    const newResource = new Resource(req.body);
    const resource = await newResource.save();
    res.json(resource);
};

exports.getOne = async (req, res) => {
    const resource = await Resource.findById(req.params.id);
    res.json(resource);
};

exports.update = async (req, res) => {
    const resource = await Resource.findByIdAndUpdate(req.params.id, req.body, {new: true});
    res.json(resource);
};

exports.delete = async (req, res) => {
    await Resource.findByIdAndRemove(req.params.id);
    res.json({message: 'Resource deleted'});
};

This code defines a controller that handles all CRUD operations for a resource. It uses the Resource model that we'll create shortly to interact with our MongoDB database.

Now, let's create our model. In a new file, add the following code:


const mongoose = require('mongoose');

const ResourceSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    }
});

module.exports = mongoose.model('Resource', ResourceSchema);

This code defines a template for our resources. It uses Mongoose, a popular library for MongoDB, to define a schema for our data.

Now that we have our API set up, it's time to document it. Documentation is crucial to ensuring that other developers can understand and use our API correctly. There are several tools available for documenting APIs, but one of the most popular is Swagger.

Swagger is an API documentation tool that allows developers to define the structure of their API using an API description format. It generates an interactive user interface that allows developers to explore and test the API.

To use Swagger, we first need to install the swagger-ui-express package:


npm install swagger-ui-express

Next, we can add the following code to our routes file:


const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

router.use('/api-docs', swaggerUi.serve);
router.get('/api-docs', swaggerUi.setup(swaggerDocument));

This code serves our Swagger documentation in /api-docs. The swagger.json file is where we'll define the structure of our API.

In our swagger.json file, we can add the following code:


{
    "openapi": "3.0.0",
    "info": {
        "title": "Resource API",
        "version": "1.0.0",
        "description": "API for managing resources"
    },
    "paths": {
        "/": {
            "get": {
                "summary": "Get all resources",
                "responses": {
                    "200": {
                        "description": "A list of resources"
                    }
                }
            },
            "post": {
                "summary": "Create a new resource",
                "responses": {
                    "200": {
                        "description": "The created resource"
                    }
                }
            }
        },
        "/{id}": {
            "get":{
                "summary": "Get a specific resource",
                "responses": {
                    "200": {
                        "description": "The requested resource"
                    }
                }
            },
            "put": {
                "summary": "Update a specific resource",
                "responses": {
                    "200": {
                        "description": "The updated resource"
                    }
                }
            },
            "delete": {
                "summary": "Delete a specific resource",
                "responses": {
                    "200": {
                        "description": "Confirmation of deletion"
                    }
                }
            }
        }
    }
}

This code defines the structure of our API, including all the CRUD operations we implement. It provides a description and summary for each operation, as well as possible response codes.

With that, we have a complete CRUD API with NodeJS and MongoDB, along with its documentation. This will make it much easier for other developers to use our API.

Now answer the exercise about the content:

How important is API documentation in development and what popular tool is used to document APIs?

You are right! Congratulations, now go to the next page

You missed! Try again.

API documentation is essential for ensuring that other developers can understand and use the API effectively. It provides clarity on how to interact with the API's endpoints and operations. Swagger, a widely-used tool, helps in creating interactive and user-friendly API documentation, allowing developers to define the API structure and explore it.

Next chapter

Creating a CRUD with NodeJS and MongoDB: Application Deployment

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.