flask-openapi3
Flask-OpenAPI3 is a web API framework based on Flask, currently at version 4.3.1. It simplifies the generation of REST APIs and OpenAPI documentation (including Swagger UI, ReDoc, and RapiDoc) for Flask projects. It leverages Pydantic for data validation and schema definition, and is actively maintained with frequent updates.
Warnings
- breaking The upcoming major version (v5.0.0rc1 and beyond) renames the library from `flask-openapi3` to `flask-openapi`. This will require installing a new package (`pip install flask-openapi`) and updating import statements.
- gotcha When using Pydantic v2 (required `Pydantic>=2.4`), be aware that the `ValidationError` schema changed. Version 4.3.0 of `flask-openapi3` includes a fix for this, so ensure you are on `v4.3.0` or newer for full compatibility.
- gotcha When registering blueprints, older versions of `flask-openapi3` (prior to 4.2.1) had an issue where `register_api` was not idempotent. Repeated calls could lead to unexpected behavior or duplicate routes.
- gotcha The generated API documentation (Swagger UI, Redoc, etc.) is typically served under the `/openapi` path (e.g., `http://127.0.0.1:5000/openapi`). Users sometimes expect direct access at `/swagger` or `/redoc`.
Install
-
pip install flask-openapi3 -
pip install flask-openapi3[swagger,redoc,rapidoc]
Imports
- OpenAPI
from flask_openapi3 import OpenAPI
- Info
from flask_openapi3 import Info
- Tag
from flask_openapi3 import Tag
- BaseModel
from pydantic import BaseModel
Quickstart
from flask_openapi3 import Info, Tag, OpenAPI
from pydantic import BaseModel
info = Info(title='Book API', version='1.0.0')
app = OpenAPI(__name__, info=info)
book_tag = Tag(name='book', description='Book management operations')
class BookQuery(BaseModel):
age: int
author: str
@app.get('/book', tags=[book_tag], summary='Get books by query')
def get_book(query: BookQuery):
"""Retrieves a list of books based on age and author."""
return {
"code": 0,
"message": "ok",
"data": [
{"bid": 1, "age": query.age, "author": query.author},
{"bid": 2, "age": query.age, "author": query.author}
]
}
if __name__ == '__main__':
# Access OpenAPI docs at http://127.0.0.1:5000/openapi
app.run(debug=True)