Document Your API with Swagger And Docker
When developing an API, it's good to map out what the endpoints are going to be, before actually building the API. This way other developers will know how they will be able to interface with your API, even before it's built. If you already have an API, it's useful to document the endpoints in a manner that makes it easy for others to integrate with your API without having to perform a lot of guesswork and reading.
To achieve this, I use a PHP package (I created) to generate a
However, if you want to, you can read the specifications to manually type out your own swagger.json file.
swagger.json file is just a JSON file that describes your API.
I developed the package to make it much easier, and prevent myself having to look things up all the time. I will include a video demonstration at a later date.
Once you have generated your swagger.json file you can use docker to deploy an intuitive website (swagger UI) that will use your specification, and that others can use to see how your API works, and even try it out.
docker run \ --name swaggerui \ -p 80:8080 \ -e SWAGGER_JSON=/swagger.json \ -v `pwd`/swagger.json:/swagger.json:ro \ swaggerapi/swagger-ui
There is a bunch of documentation on how you can configure various things about the UI. You could create a configuration document or pass query parameters. For example, the following will load the page with everything collapsed:
Alternative - Redoc
Alternatively, you can pass the swagger.json to Redoc for a different look:
docker run -d \ --restart=always \ -p 80:80 \ -v $(pwd)/swagger.json:/usr/share/nginx/html/swagger.json \ -e SPEC_URL=swagger.json \ redocly/redoc
If you want to generate files you can send someone, rather than having to host a website, then you can use the Redoc CLI tool.
First, install the CLI tool through NPM:
sudo npm i -g redoc-cli
Then you can generate the documentation with:
redoc-cli bundle -o docs.html swagger.json
First published: 14th March 2019