Skip to content

rithwiksb/swagflask

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

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 and auto-filled examples:

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

The SwaggerUI.schema() helper makes it easy to define schemas with examples that auto-fill in Swagger UI, just like FastAPI!

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

🀝 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

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages