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:


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.

Article image Creating a CRUD with NodeJS and MongoDB: Application Deployment

Next page of the Free Ebook:

97Creating a CRUD with NodeJS and MongoDB: Application Deployment

7 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text