Automated API Documentation

Published: 06 Feb 2023
Using Gitlab and Redoc to create automated documentation deploys


We recently had some friction at work due to a backend change that wasn’t reflected in the documentation. While this doesn’t solve the communication issue, it should help alleviate the pain of making a change in code and then having to remember to change it in all the various documentation places.

We looked into a few different tools for this, but really we just wanted a quick api reference for the deployed API. We chose redoc because we could build a Gitlab Pages site with it and not need to configure a whole front end for our application. The nice bit is that it won’t be a huge lift if we choose to move to something like Docusaurus in the future.

The bigger challenge for me was figuring out an aws cli command to export our REST API. After a good chunk of trial and error and searching the web, I found the following combination to work pretty well.

$ aws apigateway get-export \
  --rest-api-id $apiName \
  --stage-name $stageName \
  --export-type OAS30 \
  --region $REGION \
  api-latest.json

To preview the docs site:

$ npx @redocly/cli preview-docs api-latest.json

To build the docs site:

$ npx @redocly/cli build -o public/index.html api-latest.json

Now, I just needed to wire up a CI/CD job in gitlab to do the steps.

pages:
  stage: deploy
  script:
    - >
      aws apigateway get-export
      --rest-api-id $apiName
      --stage-name $stageName
      --export-type OAS30
      --region $region
      api-latest.json
    - npm install -g redoc-cli
    - redoc-cli build -o public/index.html api-latest.json
  artifacts:
    paths:
      - public
  only:
    - main

Note: I already have a build job set up so all I needed to do was add another stage to deploy the docs site. This automatically sets the variables for me.

This job will export the API to api-latest.json in OpenApiSpec3.0 format, installs redoc, and builds the site in Gitlab when code is pushed to the main branch.

A nice feature of this is that we automatically get GitLab authorization in front of the pages deployment. Only people with access to our repo will be able to access the api documentation site on gitlab.io.

In the future, I’d like to add the ability to compare changes to the api and only rebuild the site when something on the backend changes. This comparison would allow me to setup a slack integration to notify the product owners when a change has been made to the way the API returns data.


Written by: R.James Solenberg