CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask-openapi3

Generate REST API and OpenAPI documentation for your Flask project with automatic request/response validation using Pydantic models.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

cli-commands.mddocs/

CLI Commands

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.

Capabilities

OpenAPI Export Command

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)
    """

Usage Examples

Basic Usage

Export OpenAPI specification to console:

# Export to console (JSON format)
flask openapi

# Export to console (YAML format) 
flask openapi --format yaml

Export to File

Export 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 4

Command Options

Available command-line options:

  • --output / -o: Specify output file path
  • --format / -f: Choose output format (json or yaml)
  • --indent / -i: Set JSON indentation level

Setup and Configuration

Flask Application Setup

To 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()

Environment Setup

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.json

Using with Flask CLI

The command integrates with Flask's CLI system:

# List available commands
flask --help

# Get help for openapi command
flask openapi --help

Output Formats

JSON Output

Default 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 Output

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
        - email

Dependencies

Required Dependencies

The CLI command is available by default with Flask-OpenAPI3 installation.

Optional Dependencies

For YAML output format:

# Install PyYAML for YAML support
pip install pyyaml

# Or install with optional dependencies
pip install flask-openapi3[yaml]

Error Handling

Common Issues

Application Context Error:

# Error: Working outside of application context
flask openapi

Solution: Ensure Flask app is properly configured with FLASK_APP environment variable.

Missing api_doc Attribute:

# Error: No OpenAPI specification found
flask openapi

Solution: Ensure your application uses OpenAPI class and has defined routes.

YAML Format Error:

# Error: pyyaml must be installed
flask openapi --format yaml

Solution: Install PyYAML dependency.

Validation

The command validates that:

  1. Flask application context is available
  2. Application has api_doc attribute (OpenAPI specification)
  3. Required dependencies are installed (PyYAML for YAML format)

Integration Examples

CI/CD Pipeline

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 yaml

Development Workflow

Generate specifications during development:

# Watch for changes and regenerate spec
flask openapi --output api-spec.json && echo "Specification updated"

Documentation Generation

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 yaml

Advanced Usage

Custom Flask CLI Commands

Extend 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)

Programmatic Access

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

docs

cli-commands.md

core-classes.md

index.md

openapi-models.md

utilities.md

validation.md

tile.json