Skip to main content

Swagger UI for Flask - Automatically configure Swagger UI for Flask applications, just like FastAPI's /docs endpoint

Project description

SwagFlask 🎉

Swagger UI for Flask - Bring FastAPI's beloved /docs experience to Flask!

SwagFlask automatically configures Swagger UI for your Flask applications, making API documentation and testing as easy as typing /docs in your browser.

License: MIT Python Flask

✨ Features

  • 🚀 FastAPI-like /docs endpoint for Flask
  • 📝 Automatic OpenAPI/Swagger spec generation from your Flask routes
  • 🎨 Beautiful Swagger UI interface for testing APIs
  • 🔧 Simple decorator-based API documentation
  • 📦 Zero config required - works out of the box
  • 🎯 Type-safe with full type hints support
  • 🔌 Easy integration with existing Flask apps

📦 Installation

pip install swagflask

🚀 Quick Start

from flask import Flask, jsonify
from swagflask import SwaggerUI

app = Flask(__name__)

# Initialize SwaggerUI
swagger = SwaggerUI(app, title="My API", version="1.0.0")

@app.route('/users', methods=['GET'])
@swagger.doc({
    'summary': 'Get all users',
    'responses': {
        '200': {'description': 'List of users'}
    }
})
def get_users():
    return jsonify([{'id': 1, 'name': 'John'}, {'id': 2, 'name': 'Jane'}])

if __name__ == '__main__':
    app.run(debug=True)

That's it! Now visit http://localhost:5000/docs to see your interactive API documentation! 🎊

📖 Usage

Basic Setup

from flask import Flask
from swagflask import SwaggerUI

app = Flask(__name__)
swagger = SwaggerUI(app)

Custom Configuration

swagger = SwaggerUI(
    app,
    title="My Awesome API",           # API title
    version="1.0.0",                   # API version
    description="API Description",     # API description
    docs_url="/docs",                  # Swagger UI URL (default: /docs)
    openapi_url="/openapi.json"        # OpenAPI spec URL (default: /openapi.json)
)

Documenting Endpoints

With the @swagger.doc() decorator:

@app.route('/users/<int:user_id>', methods=['GET'])
@swagger.doc({
    'summary': 'Get user by ID',
    'description': 'Returns a single user by their ID',
    'parameters': [{
        'name': 'user_id',
        'in': 'path',
        'required': True,
        'schema': {'type': 'integer'},
        'description': 'The ID of the user to retrieve'
    }],
    'responses': {
        '200': {
            'description': 'User found',
            'content': {
                'application/json': {
                    'schema': {
                        'type': 'object',
                        'properties': {
                            'id': {'type': 'integer'},
                            'name': {'type': 'string'},
                            'email': {'type': 'string'}
                        }
                    }
                }
            }
        },
        '404': {'description': 'User not found'}
    }
})
def get_user(user_id):
    # Your code here
    return jsonify({'id': user_id, 'name': 'John Doe'})

POST endpoints with request body:

@app.route('/users', methods=['POST'])
@swagger.doc({
    'summary': 'Create a new user',
    'requestBody': {
        'required': True,
        'content': {
            'application/json': {
                'schema': {
                    'type': 'object',
                    'required': ['name', 'email'],
                    'properties': {
                        'name': {'type': 'string', 'example': 'John Doe'},
                        'email': {'type': 'string', 'format': 'email'}
                    }
                }
            }
        }
    },
    'responses': {
        '201': {'description': 'User created successfully'},
        '400': {'description': 'Invalid input'}
    }
})
def create_user():
    data = request.get_json()
    # Your code here
    return jsonify(data), 201

Auto-documentation (without decorator):

SwagFlask can automatically generate basic documentation from your function signatures and docstrings:

@app.route('/products', methods=['GET'])
def get_products():
    """
    Get all products.
    This endpoint returns a list of all available products.
    """
    return jsonify([{'id': 1, 'name': 'Laptop'}])

📋 Examples

Check out the examples/ directory for complete working examples:

  • basic_app.py - Simple API with basic documentation
  • advanced_app.py - Advanced usage with custom configuration

To run the examples:

# Basic example
python examples/basic_app.py

# Advanced example
python examples/advanced_app.py

Then visit:

🎯 Why SwagFlask?

If you've used FastAPI, you know how amazing it is to have /docs built-in. But sometimes you need to use Flask for various reasons (existing codebase, specific requirements, etc.). SwagFlask brings that same documentation experience to Flask!

Comparison

FastAPI:

from fastapi import FastAPI
app = FastAPI()

@app.get("/users")
def get_users():
    return [{"id": 1, "name": "John"}]
# Visit /docs - it just works! ✨

Flask with SwagFlask:

from flask import Flask
from swagflask import SwaggerUI

app = Flask(__name__)
swagger = SwaggerUI(app)

@app.route('/users')
def get_users():
    return [{"id": 1, "name": "John"}]
# Visit /docs - it just works! ✨

🛠️ Development

Setup Development Environment

# Clone the repository
git clone https://github.com/rithwiksb/swagflask.git
cd swagflask

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode
pip install -e .

# Install development dependencies
pip install -e ".[dev]"

Running Tests

pytest

📝 Publishing to PyPI

Prerequisites

  1. Create accounts on PyPI and TestPyPI
  2. Install build tools:
pip install build twine

Build the Package

# Clean previous builds
rm -rf build/ dist/ *.egg-info

# Build the package
python -m build

This creates two files in dist/:

  • swagflask-0.1.0.tar.gz (source distribution)
  • swagflask-0.1.0-py3-none-any.whl (wheel distribution)

Test on TestPyPI (Recommended)

# Upload to TestPyPI
python -m twine upload --repository testpypi dist/*

# Install from TestPyPI to test
pip install --index-url https://test.pypi.org/simple/ swagflask

Publish to PyPI

# Upload to PyPI
python -m twine upload dist/*

Post-Publishing

After publishing, you can install your package with:

pip install swagflask

🤝 Contributing

Contributions are welcome! Here are some ways you can contribute:

  • 🐛 Report bugs
  • 💡 Suggest new features
  • 📝 Improve documentation
  • 🔧 Submit pull requests

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Inspired by FastAPI's excellent API documentation
  • Built with Flask
  • Uses Swagger UI for documentation interface

🔗 Links


Made with ❤️ for Flask developers who miss FastAPI's /docs

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

swagflask-0.1.0.tar.gz (11.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

swagflask-0.1.0-py3-none-any.whl (8.4 kB view details)

Uploaded Python 3

File details

Details for the file swagflask-0.1.0.tar.gz.

File metadata

  • Download URL: swagflask-0.1.0.tar.gz
  • Upload date:
  • Size: 11.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for swagflask-0.1.0.tar.gz
Algorithm Hash digest
SHA256 7ecfe29f866947f6e101ba6f422c6d259fb2e02035864c728150b19125d5a40c
MD5 01be6ce76f4c4c95034b705dbfc57eae
BLAKE2b-256 b863646598168426879cf570565f2e22752dff9872b4101fc03097af3a0f548c

See more details on using hashes here.

File details

Details for the file swagflask-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: swagflask-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 8.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.9

File hashes

Hashes for swagflask-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4e32e9a04e46b89d9da33c1a642204bea3c6da3cce1a6d01b468882613e6924e
MD5 171ad951786f573916c6049550c9fcb5
BLAKE2b-256 6846562c969a65fba033376fa19fb1104dbdf6cce363a9f528ca3c440c486692

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page