How to Automatically Generate and Serve Swagger with swagger-express-ts

May 14, 2024 | Programming

In today’s tech world, documenting your API can save you and your team a lot of headaches down the road. One of the best ways to ensure comprehensive documentation is by utilizing the swagger-express-ts library. This guide will take you through setting up swagger-express-ts to easily generate and serve your API documentation.

Getting Started

To kick things off, you need to install the swagger-express-ts library. Follow these steps:

  • Open your terminal and run:
  • npm install swagger-express-ts --save
  • Initialize your tsconfig.json file according to your project needs.

The Basics

Now, let’s set the foundation for your server. We will utilize inversify-express-utils, although it’s not mandatory. Here’s how you can set up your server:

import * as bodyParser from 'body-parser';
import * as express from 'express';
import reflect-metadata;
import Container from 'inversify';
import interfaces, { InversifyExpressServer, TYPE } from 'inversify-express-utils';
import VersionController from './version/version.controller';
import * as swagger from 'swagger-express-ts';
import SwaggerDefinitionConstant from 'swagger-express-ts';

const config = require('../config.json');

// Set up container
const container = new Container();
container.bind(TYPE.Controller).to(VersionController).inSingletonScope().whenTargetNamed(VersionController.TARGET_NAME);

// Create server
const server = new InversifyExpressServer(container);
server.setConfig((app: any) => {
    app.use('/api-docs/swagger', express.static('swagger'));
    app.use('/api-docs/swagger/assets', express.static('node_modules/swagger-ui-dist'));
    app.use(bodyParser.json());
    app.use(swagger.express({
        definition: {
            info: {
                title: 'My API',
                version: '1.0'
            },
            externalDocs: {
                url: 'My URL'
            }
        }
    }));
});

server.setErrorConfig((app: any) => {
    app.use((err: Error, request: express.Request, response: express.Response, next: express.NextFunction) => {
        console.error(err.stack);
        response.status(500).send('Something broke!');
    });
});

const app = server.build();
app.listen(config.port);
console.info('Server is listening on port: ' + config.port);

Imagine you are setting up a restaurant. The container acts like your restaurant’s kitchen where all the chefs (controllers) are prepared and organized to handle customer orders (incoming API requests). Each meal (response) is crafted and served through your waiter (server), who ensures everything is running smoothly and any errors are addressed immediately.

Step-by-Step Implementation

Step 1: Configure Your Express Server

In the provided code, you’ll need to bind your controllers, serve static files, and set up error handling. Ensure that your API documentation is accessible at /api-docs/swagger.json.

Step 2: Decorate Your Model

Define your data model properly using decorators to include required properties:

@ApiModel({
    description: 'Version description',
    name: 'Version'
})
export class VersionModel {
    @ApiModelProperty({
        description: 'Id of version',
        required: true,
        example: [123456789]
    })
    id: number;
    
    @ApiModelProperty({
        description: 'Name of the version',
        required: true
    })
    name: string;

    @ApiModelProperty({
        description: 'Description of version',
        required: true
    })
    description: string;
}

Step 3: Decorate Your Controller

The controller is responsible for receiving requests and sending back responses:

@ApiPath({
    path: '/versions',
    name: 'Version',
    security: { basicAuth: [] }
})
@controller('versions')
@injectable()
export class VersionController implements interfaces.Controller {
    public static TARGET_NAME: string = 'VersionController';
    private data = [
        { id: 1, name: 'Version 1', description: 'Description Version 1', version: '1.0.0' },
        { id: 2, name: 'Version 2', description: 'Description Version 2', version: '2.0.0' }
    ];

    @ApiOperationGet({
        description: 'Get versions object list',
        summary: 'Get versions list',
        responses: {
            200: { description: 'Success', type: SwaggerDefinitionConstant.Response.Type.ARRAY, model: 'Version' }
        },
        security: { apiKeyHeader: [] }
    })
    @httpGet()
    public getVersions(request: express.Request, response: express.Response, next: express.NextFunction): void {
        response.json(this.data);
    }

    @ApiOperationPost({
        description: 'Post version object',
        summary: 'Post new version',
        parameters: {
            body: { description: 'New version', required: true, model: 'Version' }
        },
        responses: {
            200: { description: 'Success' },
            400: { description: 'Parameters fail' }
        }
    })
    @httpPost()
    public postVersion(request: express.Request, response: express.Response, next: express.NextFunction): void {
        if (!request.body) return response.status(400).end();
        this.data.push(request.body);
        response.json(request.body);
    }
}

Step 4: Testing

Launch your server and access /api-docs/swagger.json to see your API documentation.

Extra: Serving Swagger UI

To give your documentation a polished façade, install the swagger-ui-dist:

npm install swagger-ui-dist --save

Then create an index.html file in a new directory and follow the provided templates to set up swagger-ui.

Troubleshooting

  • If your server doesn’t start as expected, double-check the configuration in config.json.
  • Ensure all necessary packages are correctly installed and imported.
  • If you encounter 500 errors, look at your error logging in the console to diagnose failure reasons.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Conclusion

That’s it! You’ve successfully set up swagger-express-ts to automatically generate and serve API documentation. Happy coding, and may your APIs be ever well-documented!

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox