Cover image for Publishing your OpenAPI documents automatically with NodeJS and Express

Publishing your OpenAPI documents automatically with NodeJS and Express

scampiuk profile image Chris Williams ・2 min read

Writing that OpenAPI spec document is one thing, but how can you make sure it's viewable to everyone who needs it?

There are plenty of commercial tools for sharing API information around (https://www.postman.com/ is a great example), but what's a difficult thing to do if your API is for public consumption.

You could maintain a copy on your website somewhere? Make the OpenAPI spec available so people can copy-paste to https://editor.swagger.io/?

We've tried both and found that it's hard work to maintain an up-to-date version without doing some additional automation on deployment.

Training people to check the file from the repo, copy-paste it to the online editor.. yea that works as well as you would expect it too.

Why not just expose the OpenAPI document in a nice format directly on the API?

The code to do this is really, really simple.

We're going to use swagger-ui-express by Stephen Scott

    const express = require('express')
    const swaggerUi = require('swagger-ui-express')

    const router = new express.Router()
    const jsYaml = require('js-yaml')
    const fs = require('fs')

    // Our document is YAML, if yours is JSON, then you can just
    // `const openApiDocument = require('spec/openapi.json')`
    // instead.
    const openApiDocument = jsYaml.safeLoad(
        fs.readFileSync('spec/petstore.yaml', 'utf-8'),

    // We can enable the explorer also!
    const options = { explorer: true }

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

    // If you're not using a `router`, you can use
    // `app.use('/api-docs', swaggerUi.serve,
    //    swaggerUi.setup(swaggerDocument, options));


And that's about it. Firing up our app and heading over to https://mycool.io/api-docs and you should see something like this:

Alt Text

Now, every time you deploy your API, the latest version of the OpenAPI document will be available for all to see.

Thanks, I hope this helps someone get their API documentation in front of the people who need it - I've also written an article on Handling API validation with OpenAPI (Swagger) documents in NodeJS and OpenAPI (Swagger) specifications that write your tests for you (sort of)

Header image by rawpixel

Posted on by:

scampiuk profile

Chris Williams


Just a developer trying to move things forwards. Currently working with Nodejs and high-volume, high-availability APIs and replacing legacy systems in the process. AWS, K8s, php, js, etc.


Editor guide