Skip to main content

Extra check using pydandic in flask application

Project description

Publish to PyPI Downloads

PyPI version License Swagger UI ReDoc

FlaskNova

A modern and lightweight extension for Flask that brings FastAPI-style features like automatic OpenAPI schema, Swagger UI, request validation, typed routing, and structured responses.


🚀 Features

  • ✅ Automatic OpenAPI 3.0 schema generation
  • ✅ Built-in Swagger UI at /docs (configurable), Redoc at /redoc
  • ✅ Request validation using Pydantic models
  • ✅ Response model serialization (Pydantic, dataclass, or custom class with to_dict)
  • ✅ Docstring-based or keyword-based summary and description for endpoints
  • ✅ Typed URL parameters (<int:id>, <uuid:id>, etc.)
  • ✅ Customizable Swagger UI and Redoc route path and OpenAPI metadata
  • ✅ Configurable via FLASKNOVA_ENABLED_DOCS and FLASKNOVA_SWAGGER_ROUTE and FLASKNOVA_REDOC_ROUTE
  • ✅ Clean modular routing with NovaBlueprint
  • ✅ Built-in HTTP status codes (flasknova.status)
  • ✅ New: Form() parsing for form data
  • ✅ New: @guard() decorator for combining multiple decorators (e.g. JWT + roles)
  • ✅ Minimal boilerplate and highly extensible
  • 65% type hints support

📑 Table of Contents


Why FlaskNova?

FlaskNova brings modern API development to Flask with a FastAPI-inspired design:

  • Automatic OpenAPI/Swagger UI: Instantly document and test your API.
  • Flexible serialization: Use Pydantic, dataclasses, or custom classes (with type hints).
  • Dependency injection: Cleaner, more testable route logic.
  • Unified error handling and status codes: Consistent and robust.
  • Production-ready logging: Built-in, unified logger.
  • Minimal boilerplate: Focus on your business logic, not plumbing.

Installation

pip install flask-nova

Quick Example

from flasknova import FlaskNova, NovaBlueprint, status
from pydantic import BaseModel

app = FlaskNova(__name__)
api = NovaBlueprint("api", __name__)

class User(BaseModel):
    username: str
    email: str

@api.route("/users", methods=["POST"], response_model=User, summary="Create a new user")
def create_user(data: User):
    return data, status.CREATED

app.register_blueprint(api)

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

Go to http://localhost:5000/docs to try it out in Swagger UI.


Route Documentation Options

Using summary and description:

@api.route("/hello", summary="Say hello", description="Returns a greeting message.")
def hello():
    return {"msg": "Hello!"}

Or using a docstring:

@api.route("/hello")
def hello():
    """Say hello.

    Returns a greeting message to the user.
    """
    return {"msg": "Hello!"}

Typed URL Parameters

@api.route("/users/<int:user_id>", methods=["GET"])
def get_user(user_id: int):
    ...

Supported: int, float, uuid, path, string (default).


Enabling Docs UI

Environment vars:

Variable Default Description
FLASKNOVA_ENABLED_DOCS True Disable Swagger UI if False
FLASKNOVA_SWAGGER_ROUTE /docs Change swagger UI path
FLASKNOVA_REDOC_ROUTE /redoc change redoc ui path

Response Models

  • ✅ Pydantic models
  • ✅ Dataclasses
  • ✅ Custom classes (to_dict, dict, or dump)
import dataclasses

@dataclasses.dataclass
class User:
    id: int
    name: str

@api.route("/me", response_model=User)
def get_profile():
    return {"id": 1, "name": "nova"}

Form Parsing

Use Form() to handle form data (like FastAPI’s Form).

from flasknova import FlaskNova, NovaBlueprint, Form, status
from pydantic import BaseModel

app = FlaskNova(__name__)
api = NovaBlueprint("api", __name__)

class LoginForm(BaseModel):
    username: str
    password: str

@api.route("/login", methods=["POST"])
def login(data: LoginForm = Form(LoginForm)):
    return {"msg": f"Welcome {data.username}"}, status.OK

app.register_blueprint(api)

Guard Decorator

Use @guard() to combine multiple decorators (e.g. JWT + roles).

from flasknova import FlaskNova, NovaBlueprint, guard, status
from flask_jwt_extended import jwt_required

app = FlaskNova(__name__)
api = NovaBlueprint("api", __name__)

@api.route("/secure", methods=["GET"])
@guard(jwt_required())
def secure_endpoint():
    return {"msg": "You are authenticated"}, status.OK

# Multiple decorators in one
@api.route("/admin", methods=["GET"])
@guard(jwt_required(), lambda fn: print("Extra check") or fn)
def admin_only():
    return {"msg": "Admin access granted"}, status.OK

Status Codes

from flasknova import status

print(status.OK)   # 200
print(status.CREATED)  # 201
print(status.UNPROCESSABLE_ENTITY)  # 422

Error Handling

from flasknova import HTTPException, status

raise HTTPException(
    status_code=status.NOT_FOUND,
    detail="User not found",
    title="Not Found"
)

Response Serialization & Custom Responses

from flask import make_response, jsonify

@api.route("/custom", methods=["GET"])
def custom():
    data = {"message": "Custom response"}
    response = make_response(jsonify(data), 201)
    response.headers['X-Custom-Header'] = 'Value'
    return response

Logging

from flasknova import logger
logger.info("FlaskNova app started!")

Cli

Flask-Nova provides a CLI tool to automatically generate HTTP request files (.http) and Python test scripts (.py) for your Flask routes.

Usage

Command

flask-nova gen --app <your_app_path> [OPTIONS]

Required Option

  • --app TEXT — Your Flask app import path, e.g. examples.form_ex:app

Optional Options

  • --format [http|py|all] — File format to generate (default: all)
  • --base-url TEXT — Base URL for requests (default: http://127.0.0.1:5000)
  • --output PATH — Directory to save generated files (default: current directory)

Examples

Generate HTTP requests only:

flask-nova gen --app examples.form_ex:app --format http

Generate Python requests only:

flask-nova gen --app examples.form_ex:app --format py

Generate both HTTP and Python requests:

flask-nova gen --app examples.form_ex:app --format all

The generated files will handle:

  • JSON for normal routes
  • multipart/form-data for routes using Form()

FAQ

Why don't my custom class fields appear in Swagger UI? You must add class-level type hints.
Why does my dataclass or custom class not validate requests? Only Pydantic models are used for request validation.
Can I use Marshmallow schemas for request validation? No, Marshmallow is only supported for response serialization.

Learn More


License

MIT License


Contributing

  • Fork the repo, create your branch from main
  • Write tests and keep code clean
  • Open a PR with explanation

Issues and features: GitHub Issues


PyPI Release

🔗 FlaskNova on PyPI 🔗 GitHub Release Notes

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

flask_nova-0.1.2.tar.gz (24.2 kB view details)

Uploaded Source

Built Distribution

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

flask_nova-0.1.2-py3-none-any.whl (27.2 kB view details)

Uploaded Python 3

File details

Details for the file flask_nova-0.1.2.tar.gz.

File metadata

  • Download URL: flask_nova-0.1.2.tar.gz
  • Upload date:
  • Size: 24.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.4 CPython/3.10.11 Windows/10

File hashes

Hashes for flask_nova-0.1.2.tar.gz
Algorithm Hash digest
SHA256 fed33a16ab379e00dcf590323045a3ac3885f383e6d5308a89955215ae7d7e00
MD5 1c7868548c29d0380665595ab8f80db8
BLAKE2b-256 8e8d3ed52c3f5f6705838dcedf2112f2ec8f56dd5df54ff545756a7cf3d895f9

See more details on using hashes here.

File details

Details for the file flask_nova-0.1.2-py3-none-any.whl.

File metadata

  • Download URL: flask_nova-0.1.2-py3-none-any.whl
  • Upload date:
  • Size: 27.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.4 CPython/3.10.11 Windows/10

File hashes

Hashes for flask_nova-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 d491d8191c36811c7fdb10fb92431a0364fc664b45f3461dbd612a8283911c71
MD5 1ccc88e42cdb5262cdf78f1da941d8d1
BLAKE2b-256 0896c94db918d32b42067d9a198f573d92e7958feba6735fc65a5a1f8249bdc2

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