LoginSignup
8
2

More than 1 year has passed since last update.

FastAPIで自動生成されるドキュメントを保存する方法

Last updated at Posted at 2022-11-23

はじめに

FastAPI は、WebAPI を構築するためのモダンなWebフレームワークです。

類似したフレームワークに、Django(Rest framework)やFlaskがありますが、大きな特徴として、コードからOpenAPIに準拠したAPIドキュメントを自動生成できることが挙げられます。/docsや/redoc、/openapi.jsonで見れるやつです。

ただ、自動生成されるドキュメントを保存する方法についてあまり日本語の情報が見つからなかったのでまとめておきます。
(フロントエンドとバックエンドで分かれて開発を行なっていて、APIの仕様だけ決めてドキュメントをGitHubPagesなどで共有、それを元にそれぞれ作業を進めたい時などに便利かと思います。)

openapi()メソッドを利用してhtmlを生成する

FastAPIにはopenapiスキーマを返すopenapi()メソッドというものがあるのでこれを利用します。

有志の方が上記を利用したPythonのスクリプトを作ってくれています。(Redocの形式で出力)

python
"""Script to export the ReDoc documentation page into a standalone HTML file."""

import json

from my_app.app import app

HTML_TEMPLATE = """<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>My Project - ReDoc</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="https://fastapi.tiangolo.com/img/favicon.png">
    <style>
        body {
            margin: 0;
            padding: 0;
        }
    </style>
    <style data-styled="" data-styled-version="4.4.1"></style>
</head>
<body>
    <div id="redoc-container"></div>
    <script src="https://cdn.jsdelivr.net/npm/redoc/bundles/redoc.standalone.js"> </script>
    <script>
        var spec = %s;
        Redoc.init(spec, {}, document.getElementById("redoc-container"));
    </script>
</body>
</html>
"""

if __name__ == "__main__":
    with open(f"api-docs-my-project.html", "w") as fd:
        print(HTML_TEMPLATE % json.dumps(app.openapi()), file=fd)

下のあたりを自分のプロジェクトに合わせて変更して、同階層に配置し実行するとドキュメントが生成されます。

抜粋
from my_app.app import app
抜粋
<title>My Project - ReDoc</title>

あとは、GitHubPagesで公開するなり、そのままファイルを送るなりで共有できます。

8
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
2