Flask: how to automate OpenAPI v3 documentation? Flask: how to automate OpenAPI v3 documentation? flask flask

Flask: how to automate OpenAPI v3 documentation?


Following the suggestion of migrating from Flask to FastAPI I gave it a try and rewrote the Flask-Example of the question. The source code is also available on GitHub.

The structure of the project is almost identical, with some additional features available(e.g. the CORS Middleware):enter image description here

The models of the domain are slightly different and extend the BaseModel from Pydantic.

# author.pyfrom pydantic import BaseModelclass Author(BaseModel):    id: str    name: str

and

# book.pyfrom pydantic import BaseModelclass Book(BaseModel):    id: str    name: str

With FastAPI the equivalent of the Flask Blueprint is the APIRouter.Below are the two controllers for the authors

# author_api.pyfrom fastapi import APIRouterfrom domain.author import Authorrouter = APIRouter()@router.get("/", tags=["Authors"], response_model=list[Author])def get_authors() -> list[Author]:    authors: list[Author] = []    for i in range(10):        authors.append(Author(id="Author-" + str(i), name="Author-Name-" + str(i)))    return authors

and the books

# book_api.pyfrom fastapi import APIRouterfrom domain.book import Bookrouter = APIRouter()@router.get("/", tags=["Books"], response_model=list[Book])def get_books() -> list[Book]:    books: list[Book] = []    for i in range(10):        books.append(Book(id="Book-" + str(i), name="Book-Name-" + str(i)))    return books

It is important to note that the response model of the API endpoints is defined using Python types thanks to Pydantic. These object types are then converted into JSON schemas for the OpenAPI documentation.

In the end I simply registered/included the APIRouters under the FastAPI object and added a configuration for CORS.

# app.pyfrom fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom domain.info import Infofrom api.author.author_api import router as authors_routerfrom api.book.book_api import router as books_routerapp = FastAPI()app.include_router(authors_router, prefix="/authors")app.include_router(books_router, prefix="/books")app.add_middleware(CORSMiddleware,                   allow_credentials=True,                   allow_origins=["*"],                   allow_methods=["*"],                   allow_headers=["*"],                   )@app.get("/", response_model=Info)def info() -> Info:    info = Info(info="FastAPI - OpenAPI")    return info

The generated OpenAPI documentation is accessible at the endpoint /openapi.json while the UI (aka Swagger UI, Redoc) is accessible at /docs

enter image description here

and /redoc

enter image description here

To conclued, this is the automatically generated OpenAPI v3 documentation in JSON format, which can be used to easily generate an API client for other languages (e.g. using the OpenAPI-Generator tools).

{  "openapi": "3.0.2",  "info": {    "title": "FastAPI",    "version": "0.1.0"  },  "paths": {    "/authors/": {      "get": {        "tags": [          "Authors"        ],        "summary": "Get Authors",        "operationId": "get_authors_authors__get",        "responses": {          "200": {            "description": "Successful Response",            "content": {              "application/json": {                "schema": {                  "title": "Response Get Authors Authors  Get",                  "type": "array",                  "items": {                    "$ref": "#/components/schemas/Author"                  }                }              }            }          }        }      }    },    "/books/": {      "get": {        "tags": [          "Books"        ],        "summary": "Get Books",        "operationId": "get_books_books__get",        "responses": {          "200": {            "description": "Successful Response",            "content": {              "application/json": {                "schema": {                  "title": "Response Get Books Books  Get",                  "type": "array",                  "items": {                    "$ref": "#/components/schemas/Book"                  }                }              }            }          }        }      }    },    "/": {      "get": {        "summary": "Info",        "operationId": "info__get",        "responses": {          "200": {            "description": "Successful Response",            "content": {              "application/json": {                "schema": {                  "$ref": "#/components/schemas/Info"                }              }            }          }        }      }    }  },  "components": {    "schemas": {      "Author": {        "title": "Author",        "required": [          "id",          "name"        ],        "type": "object",        "properties": {          "id": {            "title": "Id",            "type": "string"          },          "name": {            "title": "Name",            "type": "string"          }        }      },      "Book": {        "title": "Book",        "required": [          "id",          "name"        ],        "type": "object",        "properties": {          "id": {            "title": "Id",            "type": "string"          },          "name": {            "title": "Name",            "type": "string"          }        }      },      "Info": {        "title": "Info",        "required": [          "info"        ],        "type": "object",        "properties": {          "info": {            "title": "Info",            "type": "string"          }        }      }    }  }}

In order to start the application we also need an ASGI server for production, such as Uvicorn or Hypercorn.I used Uvicorn and the app is started using the command below:

uvicorn app:app --reload

It is then available on the port 8000 of your machine.


I encourage you to switch your project to FastAPI, it isn't much different or more difficult than Flask.

FastAPI docs about generating OpenAPI schema

It will not only allow you to generate OpenAPI docs / specification easily. It is also asynchronous, much faster and modern.

See also FastAPI Alternatives, Inspiration and Comparisons to read about differences.

Especially this citation from link above should explain why doing what you try to do may not be the best idea:

Flask REST frameworks

There are several Flask REST frameworks, but after investing the timeand work into investigating them, I found that many are discontinuedor abandoned, with several standing issues that made them unfit.