Generate REST API and OpenAPI documentation for your Flask project with automatic request/response validation using Pydantic models.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Command-line interface for exporting OpenAPI specifications in JSON or YAML format. Flask-OpenAPI3 provides a Flask CLI command to export the generated OpenAPI specification to files or console output.
Command for exporting OpenAPI specifications to files or console.
@click.command(name="openapi")
@click.option("--output", "-o", type=click.Path(), help="The output file path.")
@click.option("--format", "-f", "_format", type=click.Choice(["json", "yaml"]), help="The output file format.")
@click.option("--indent", "-i", type=int, help="The indentation for JSON dumps.")
@with_appcontext
def openapi_command(output, _format, indent):
"""
Export the OpenAPI Specification to console or a file.
Args:
output: Output file path (optional, prints to console if not provided)
_format: Output format ("json" or "yaml", defaults to json)
indent: Indentation level for JSON output (optional)
"""Export OpenAPI specification to console:
# Export to console (JSON format)
flask openapi
# Export to console (YAML format)
flask openapi --format yamlExport specification to files:
# Export to JSON file
flask openapi --output api-spec.json
# Export to YAML file
flask openapi --output api-spec.yaml --format yaml
# Export with custom indentation
flask openapi --output api-spec.json --indent 4Available command-line options:
--output / -o: Specify output file path--format / -f: Choose output format (json or yaml)--indent / -i: Set JSON indentation levelTo use the CLI command, your Flask-OpenAPI3 application must be properly configured:
from flask_openapi3 import OpenAPI, Info
from pydantic import BaseModel
# Create OpenAPI app
info = Info(title="My API", version="1.0.0")
app = OpenAPI(__name__, info=info)
class User(BaseModel):
name: str
email: str
@app.get("/users", responses={200: list[User]})
def get_users():
"""Get all users"""
return [{"name": "John", "email": "john@example.com"}]
if __name__ == "__main__":
app.run()Set the Flask application environment variable:
# Set Flask app
export FLASK_APP=myapp.py
# Or use python -m flask
python -m flask openapi --output spec.jsonThe command integrates with Flask's CLI system:
# List available commands
flask --help
# Get help for openapi command
flask openapi --helpDefault JSON format output:
{
"openapi": "3.1.0",
"info": {
"title": "My API",
"version": "1.0.0"
},
"paths": {
"/users": {
"get": {
"summary": "Get all users",
"operationId": "get_users_get",
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/User"
}
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"User": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"email": {
"type": "string"
}
},
"required": ["name", "email"]
}
}
}
}YAML format output (requires PyYAML):
openapi: 3.1.0
info:
title: My API
version: 1.0.0
paths:
/users:
get:
summary: Get all users
operationId: get_users_get
responses:
'200':
description: Successful Response
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
components:
schemas:
User:
type: object
properties:
name:
type: string
email:
type: string
required:
- name
- emailThe CLI command is available by default with Flask-OpenAPI3 installation.
For YAML output format:
# Install PyYAML for YAML support
pip install pyyaml
# Or install with optional dependencies
pip install flask-openapi3[yaml]Application Context Error:
# Error: Working outside of application context
flask openapiSolution: Ensure Flask app is properly configured with FLASK_APP environment variable.
Missing api_doc Attribute:
# Error: No OpenAPI specification found
flask openapiSolution: Ensure your application uses OpenAPI class and has defined routes.
YAML Format Error:
# Error: pyyaml must be installed
flask openapi --format yamlSolution: Install PyYAML dependency.
The command validates that:
api_doc attribute (OpenAPI specification)Use in continuous integration to generate API documentation:
#!/bin/bash
# Generate API specification for documentation
flask openapi --output docs/api-spec.json --indent 2
# Generate YAML for external tools
flask openapi --output api-spec.yaml --format yamlGenerate specifications during development:
# Watch for changes and regenerate spec
flask openapi --output api-spec.json && echo "Specification updated"Integrate with documentation tools:
# Generate spec for Swagger UI
flask openapi --output static/swagger.json
# Generate spec for external documentation
flask openapi --output docs/openapi.yaml --format yamlExtend the CLI with custom commands:
import click
from flask import current_app
from flask.cli import with_appcontext
@click.command(name="validate-api")
@with_appcontext
def validate_api_command():
"""Validate OpenAPI specification"""
if hasattr(current_app, 'api_doc'):
spec = current_app.api_doc
# Add custom validation logic
click.echo("API specification is valid")
else:
click.echo("No OpenAPI specification found")
# Register with Flask app
app.cli.add_command(validate_api_command)Access OpenAPI specification programmatically:
from flask import current_app
import json
def get_openapi_spec():
"""Get OpenAPI specification programmatically"""
with app.app_context():
if hasattr(current_app, 'api_doc'):
return current_app.api_doc
return None
# Use in code
spec = get_openapi_spec()
if spec:
with open('spec.json', 'w') as f:
json.dump(spec, f, indent=2)Install with Tessl CLI
npx tessl i tessl/pypi-flask-openapi3