Pragmatism in the real world

Previewing OpenAPI specs using redocly's Docker container

To provide consistency between the environments of our developers, I’m a strong proponent of using containers so that every developer is using the same versions of our tools. This is really important for command line tooling that depends on a separately installed language such as NodeJS or PHP as a simple npm i -g can install wildly different versions if a dev is running an older (or newer!) version of Node.

For OpenAPI specs, listing is a must and I currently use Spectral for that, but it can be handy to have rendered documentation visible when writing specs. I don’t know about you, but I find it easier to proofread text when in a different context to the editor that I’m currently writing it in.

To render OpenAPI docs in real-time as I write, I picked Redocly which has a preview-docs option.

The local command is: redocly/cli preview-docs openapi.yaml which will render the OpenAPI spec in openapi.yaml as an HTML page at http://localhost:8080. You can then edit the spec file and it will hot reload the browser which is super-convenient.

Using preview-docs in the Docker container

To preview the docs using the redocly/cli Docker image, you need this command:

docker run --init --rm \
-p 8080:8080 -p 32201:32201 \
-v $(PWD):/spec \
redocly/cli preview-docs --use-community-edition openapi.yaml --host 0.0.0.0 

There’s quite a lot going on here, so let’s look at the key options:

  • --init is required so that ctrl+c will exit cleanly.
  • --rm deletes the container on exit, so we tidy up after ourselves.
  • -p 8080:8080 -p 32201:32201 maps ports 8080 and 32201 from the container to our local computer. We need 32201 so that hot reloading works.
  • -v $(PWD):/spec maps our current directory to the container’s /spec directory which is its working directory.
  • redocly/cli preview-docs openapi.yaml runs Redocly’s preview-docs command against our openapi.yaml OpenAPI spec file.
  • --host 0.0.0.0 to make the app accessible from all network interfaces in the container so that we can view the preview from our local computer.

We can now open http://localhost:8080/ and view our nicely rendered OpenAPI spec!

Redocli cli rps openapi.

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *