Skip to main content

Extra check using pydandic in flask application

Project description

Publish to PyPI Downloads

PyPI version License Swagger UI

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)
  • ✅ 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 route path and OpenAPI metadata
  • ✅ Configurable via FLASKNOVA_SWAGGER_ENABLED and FLASKNOVA_SWAGGER_ROUTE
  • ✅ Clean modular routing with NovaBlueprint
  • ✅ Built-in HTTP status codes (flasknova.status)
  • ✅ Optional JWT auth and dependency injection helpers
  • ✅ New: Form() parsing for form data
  • ✅ New: @guard() decorator for combining multiple decorators (e.g. JWT + roles)
  • ✅ Minimal boilerplate and highly extensible

📑 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 Swagger UI

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

Environment vars:

Variable Default Description
FLASKNOVA_SWAGGER_ENABLED True Disable Swagger UI if False
FLASKNOVA_SWAGGER_ROUTE /docs Change 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!")

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.1.tar.gz (16.3 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.1-py3-none-any.whl (17.1 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for flask_nova-0.1.1.tar.gz
Algorithm Hash digest
SHA256 c365a0ccaae4e126b420bc65a9a4c3d709b4d5e4bd7cd2f72ff1df75a3520b50
MD5 9d7aec2b01d4ff918f0749064e398bb9
BLAKE2b-256 3ae8d2bfc508fc0ad54dacdbc5a9df2544d72308baf714080f84db87dccc8f68

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for flask_nova-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 766cb6b33c141efc4443084b7c3520630158e80aa30ee1111ff7ccda54439eaf
MD5 4f969fed842de9a1eb27e3e91c57d2a3
BLAKE2b-256 237a79db77bfcba220d6034e53b4ab80e790f0a0ffd4816912fb18d5c440ab63

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