flask-ast-openapi
Generate OpenAPI 3 specifications from Flask source code using Python's Abstract Syntax Tree (AST).
flask-ast-openapi analyzes Flask controller source files without importing or executing them and generates an OpenAPI specification that can be exported as JSON or served through Swagger UI.
Features
- Flask route detection
@app.route(...)@app.get(...)@app.post(...)@app.put(...)@app.patch(...)@app.delete(...)- Blueprint URL prefix detection
- Path parameter conversion
- Query parameter detection
- JSON request body detection
- Response status code detection
- Response schema inference
- Marshmallow schema support
- Marshmallow required fields
- Nested Marshmallow schemas
List(Nested(...))support- OpenAPI
components.schemas - Route docstring descriptions
:request:schema references:response:schema references- Configurable authentication decorators
- Multiple OpenAPI security schemes
- AND / OR authentication modes
- JSON output
- Command-line interface
- Built-in Swagger UI integration for Flask
Installation
Install from PyPI:
pip install flask-ast-openapi
To install a specific version:
pip install flask-ast-openapi==0.1.0
CLI Usage
Generate an OpenAPI JSON file from a Flask controller directory:
flask-ast-openapi ./controllers -o openapi.json
Specify the API title and version:
flask-ast-openapi ./controllers \
-o openapi.json \
--title "My API" \
--version "1.0.0"
On PowerShell:
flask-ast-openapi `
".\controllers" `
-o openapi.json `
--title "My API" `
--version "1.0.0"
Python Usage
from flask_ast_openapi import FlaskASTOpenAPI
generator = FlaskASTOpenAPI(
"./controllers"
)
spec = generator.generate(
title="My API",
version="1.0.0",
)
generator.write_json(
spec,
"openapi.json",
)
Swagger UI Integration
The package can expose both the generated OpenAPI specification and Swagger UI directly from an existing Flask application.
from flask import Flask
from flask_ast_openapi import create_swagger_blueprint
app = Flask(__name__)
swagger_bp = create_swagger_blueprint(
"./controllers",
title="My API",
version="1.0.0",
docs_url="/api/docs",
spec_url="/api/openapi.json",
)
app.register_blueprint(swagger_bp)
Then open:
http://localhost:5000/api/docs
for Swagger UI.
The raw OpenAPI specification is available at:
http://localhost:5000/api/openapi.json
Flask Route Example
Given:
@app.get("/users/<int:user_id>")
def get_user(user_id):
"""Get a user by ID."""
return {
"id": user_id,
"name": "John",
}, 200
The generated OpenAPI path will contain:
/users/{user_id}
with an integer path parameter named user_id.
Marshmallow Support
The package can use Marshmallow schemas referenced from route docstrings.
Example:
from marshmallow import Schema, fields
class UserRequestSchema(Schema):
name = fields.String(required=True)
age = fields.Integer()
class UserResponseSchema(Schema):
id = fields.Integer(required=True)
name = fields.String(required=True)
@app.post("/users")
def create_user():
"""
Create a user.
:request: UserRequestSchema
:response: UserResponseSchema
"""
...
flask-ast-openapi detects:
:request: UserRequestSchema
and:
:response: UserResponseSchema
and converts those Marshmallow schemas into OpenAPI schemas.
Nested Schemas
Nested Marshmallow schemas are supported:
class ProfileSchema(Schema):
bio = fields.String()
class UserSchema(Schema):
name = fields.String(required=True)
profile = fields.Nested(ProfileSchema)
The nested schema is represented using an OpenAPI $ref:
{
"$ref": "#/components/schemas/ProfileSchema"
}
Lists of nested schemas are also supported:
members = fields.List(
fields.Nested(UserSchema)
)
Authentication
Authentication decorator names can be configured.
generator = FlaskASTOpenAPI(
"./controllers",
auth_decorator_names={
"require_auth",
"jwt_required",
},
)
Security schemes can also be configured:
generator = FlaskASTOpenAPI(
"./controllers",
auth_decorator_names={
"require_auth",
},
auth_scheme_mapping={
"require_auth": [
"BearerAuth",
"ApiKeyAuth",
],
},
auth_scheme_modes={
"require_auth": "or",
},
security_schemes={
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
},
"ApiKeyAuth": {
"type": "apiKey",
"in": "header",
"name": "X-API-Token",
},
},
)
With:
auth_scheme_modes={
"require_auth": "or",
}
the generated OpenAPI security requirement means:
BearerAuth OR ApiKeyAuth
Using:
auth_scheme_modes={
"require_auth": "and",
}
means both schemes are required.
How It Works
The library uses Python's built-in ast module to parse source files.
The general flow is:
Python source files
|
v
AST
|
v
Flask route discovery
|
v
Request / response analysis
|
v
Marshmallow schema analysis
|
v
OpenAPI 3 specification
The Flask application itself does not need to be imported or executed during static OpenAPI generation.
Development
Clone the repository:
git clone <repository-url>
cd flask-ast-openapi
Create a virtual environment and install the project in editable mode:
python -m pip install -e ".[dev]"
Run the test suite:
python -m pytest -v
On systems where the temporary directory causes pytest issues:
python -m pytest -v --basetemp=.pytest_tmp
Current Limitations
AST-based analysis is static, so some highly dynamic Flask patterns may not be detectable.
Examples include:
- Dynamically constructed route paths
- Dynamically generated decorators
- Runtime-only schema definitions
- Complex request validation implemented outside the controller
- Response structures assembled through highly dynamic code
- Custom Marshmallow fields that cannot be inferred statically
Unknown field types currently fall back to a basic OpenAPI-compatible representation where possible.
Python Support
Python 3.10 or newer is required.
License
See the LICENSE file for license information.
Version
Current release:
0.1.0
Metadata
Release files for flask-ast-openapi 0.1.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| flask_ast_openapi-0.1.1.tar.gz | 28.5 kB | Without provenance | Details for flask_ast_openapi-0.1.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| flask_ast_openapi-0.1.1-py3-none-any.whl | Python 3 | none | any | Details for flask_ast_openapi-0.1.1-py3-none-any.whl |
Total release size: 43.3 kB
Release files / flask_ast_openapi-0.1.1.tar.gz
| Download URL | flask_ast_openapi-0.1.1.tar.gz |
|---|---|
| Size | 28.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6d16b88484b3d351244e5d3f62d513f24a757078519f9a798338198be3f20eb7
|
|
BLAKE2b-256 checksum How to use checksums |
a27847b9866c9be62da3d176e9108896c9cefa70dea2649c5a0da89a085bb939
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.13
|
Release files / flask_ast_openapi-0.1.1-py3-none-any.whl
| Download URL | flask_ast_openapi-0.1.1-py3-none-any.whl |
|---|---|
| Size | 14.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
2a9776a85ff869ad0993e351fc931688764d3e8796717bd8d079517c37ff646e
|
|
BLAKE2b-256 checksum How to use checksums |
8157c935b7a067b661744628853efb07ecbe09fedf46c8413dc840e7d2669b24
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.13
|
Security for flask-ast-openapi 0.1.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.