Skip to content

[Python] How to Use FastAPI's Auto-Generated Documentation (Including Exporting Static Files)

Last Updated on 2024-09-15 by Clay

Introduction

In the FastAPI official documentation, there's a section about 'Automatic Interactive API Documentation':

  • Robust: Get production-ready code. With automatic interactive documentation.

To use this feature, we can easily call $URL/docs after launching the FastAPI service. But what if the documentation is meant to be delivered to a client instead of just being for our own reference?

In fact, FastAPI does not support the generation of static files like HTML, PDF, or formats similar to Sphinx out of the box. We need to handle this separately. However, since FastAPI's documentation is based on the standard OpenAPI format, we can still use other tools to generate static files.


Built-in Interactive Documentation

Since we wrote the services and functions ourselves, we definitely know where the service is located. By accessing $URL/docs, you can see the following screen:

You can see several functions: one POST and two GET requests. However, this might not be the best type of documentation to deliver to clients (and it's not static either).


ReDoc

If we want to view the documentation in a different style, we can change the path to $URL/redoc, which will show a different type of documentation.

This format can be transformed into a static file using tools like redoc-cli.


Generating Static Files

First, you need to install the redoc-cli tool using npm.


npm i -g @redocly/cli@latest



Next, download the openapi.json file generated by FastAPI to your local system. Then, use the redoc-cli tool to parse it into an HTML file. Once that's done, you can directly open the file (the default name is redoc-static.html) to see the static documentation!

wget $URL/openapi.json
npx @redocly/cli bundle openapi.json
open redoc-static.html


Output:


Although it looks the same as the documentation above, this is now stored locally and can be opened at any time!

The above is a record of how to generate static files from FastAPI documentation.


References


Read More

Tags:

Leave a Reply