{"id":15529921,"url":"https://github.com/vivekkeshore/flask-dantic","last_synced_at":"2025-04-23T12:59:22.270Z","repository":{"id":40760000,"uuid":"506610219","full_name":"vivekkeshore/flask-dantic","owner":"vivekkeshore","description":"Flask-Dantic is a Python package that would enable users to use Pydantic models for validations and serialization.","archived":false,"fork":false,"pushed_at":"2023-07-04T04:25:32.000Z","size":75,"stargazers_count":8,"open_issues_count":2,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-29T23:51:09.652Z","etag":null,"topics":["alchemy","flask","orm","pydantic","serialization","sqlalchemy","validation"],"latest_commit_sha":null,"homepage":"https://pypi.org/project/flask-dantic/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/vivekkeshore.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-06-23T11:21:15.000Z","updated_at":"2024-07-25T03:40:56.000Z","dependencies_parsed_at":"2024-10-02T11:20:33.286Z","dependency_job_id":"a7cd0e36-cf88-429c-a94a-64fca3781123","html_url":"https://github.com/vivekkeshore/flask-dantic","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vivekkeshore%2Fflask-dantic","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vivekkeshore%2Fflask-dantic/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vivekkeshore%2Fflask-dantic/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vivekkeshore%2Fflask-dantic/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vivekkeshore","download_url":"https://codeload.github.com/vivekkeshore/flask-dantic/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250412532,"owners_count":21426285,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["alchemy","flask","orm","pydantic","serialization","sqlalchemy","validation"],"created_at":"2024-10-02T11:20:25.301Z","updated_at":"2025-04-23T12:59:22.250Z","avatar_url":"https://github.com/vivekkeshore.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🅕🅛🅐🅢🅚-🅓🅐🅝🅣🅘🅒\n\n*Flask-Dantic* is a Python package that would enable users to use Pydantic models for validations and serialization, thus making it easy to link Flask with Pydantic.\nIt can validate the request params, query args and path args.\n\nAlso, the package provides a serializer that serializes the database objects using the pydantic models. \nThis comes handy if you are using pydantic models for request and response in Flask.\n\nA single serialize call will take care of validating the returned response as well as serializing it. There are options to include or exclude certain fields or exclude/include fields with null values.\n\n[![PyPI](https://img.shields.io/pypi/v/flask-dantic?color=g)](https://pypi.org/project/flask-dantic/)\n![Codecov](https://img.shields.io/codecov/c/github/vivekkeshore/flask-dantic)\n[![Python package](https://github.com/vivekkeshore/flask-dantic/actions/workflows/python-package.yml/badge.svg)](https://github.com/vivekkeshore/flask-dantic/actions/workflows/python-package.yml)\n![LGTM Grade](https://img.shields.io/lgtm/grade/python/github/vivekkeshore/flask-dantic)\n[![GitHub license](https://img.shields.io/github/license/vivekkeshore/flask-dantic)](https://github.com/vivekkeshore/flask-dantic)\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/flask-dantic)\n![Snyk Vulnerabilities for GitHub Repo](https://img.shields.io/snyk/vulnerabilities/github/vivekkeshore/flask-dantic)\n![GitHub repo size](https://img.shields.io/github/repo-size/vivekkeshore/flask-dantic)\n\n----\n\n### Compatibility\n\n\nThis package is compatible with Python \u003e= 3.6\n\n## Installation\n\n\nInstall with pip:\n\n```bash\n    pip install flask-dantic\n```\n\n## Examples\n### Validating body parameters\n\n```python\n# Using the Pydantic model for request.\nfrom typing import Optional\n\nfrom flask import current_app as flask_app, request\nfrom pydantic import BaseModel\n\nfrom flask_dantic import pydantic_validator\n\n\nclass UserCreateModel(BaseModel):\n    username: str\n    age: Optional[int] = None\n    phone: Optional[str] = None\n\n\n@flask_app.route(\"/user/create\", methods=[\"POST\"])\n@pydantic_validator(body=UserCreateModel)  # Pass the model against body kwarg.\ndef create_user():\n    \"\"\"\n        Request Json to create user that will be validated against UserModel\n        {\n            \"username\": \"Foo\",\n            \"age\": 42,\n            \"phone\": \"123-456-7890\"\n        }\n    \"\"\"\n    user_model = request.body_model\n    print(user_model.username, user_model.age, user_model.phone)\n```\n\n### Change the default validation error status code. Default status code is 422\n```python\n\n@flask_app.route(\"/user/create\", methods=[\"POST\"])\n# Changing the default validation error status code from default 422 to 400\n@pydantic_validator(body=UserCreateModel, validation_error_status_code=400)\ndef create_user():\n    \"\"\"\n        Request Json to create user that will be validated against UserModel\n        {\n            \"username\": \"Foo\",\n            \"age\": 42,\n            \"phone\": \"123-456-7890\"\n        }\n    \"\"\"\n    user_model = request.body_model\n    print(user_model.username, user_model.age, user_model.phone)\n```\n\n### Validating Query args - request.args\n\n```python\n# Using the Pydantic model for request.\nfrom typing import Optional\n\nfrom flask import current_app as flask_app, request\nfrom pydantic import BaseModel\n\nfrom flask_dantic import pydantic_validator\n\n\n# Sample url - https://localhost:5000/user/get?username=Foo\u0026age=42\n# Here username and foo are pass are query args\n\nclass UserQueryModel(BaseModel):\n    username: str\n    age: Optional[int] = None\n\n\n@flask_app.route(\"/user/get\", methods=[\"GET\"])\n@pydantic_validator(query=UserQueryModel)  # Pass the model against query kwarg\ndef get_user():\n    user_query_model = request.query_model\n    print(user_query_model.username, user_query_model.age)\n```\n\n\n### Validating URL Path args\n\n```python\n# Using the Pydantic model for request.\n\nfrom flask import current_app as flask_app, request\nfrom pydantic import BaseModel, Field\n\nfrom flask_dantic import pydantic_validator\n\n# Sample url - https://localhost:5000/user/get/c55926d3-cbd0-4eea-963b-0bcfc5c40d46\n# Here the uuid is the dynamic path param.\n\nUUID_REGEX = \"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\"\n\n\nclass UserPathParamModel(BaseModel):\n    user_id: str = Field(..., regex=UUID_REGEX, description=\"ID of the user\")\n\n\n@flask_app.route(\"/user/get/\u003cstring:user_id\u003e\", methods=[\"GET\"])\n@pydantic_validator(path_params=UserPathParamModel)  # Pass the model against path_params\ndef get_user(user_id):\n    path_param_model = request.path_param_model\n    print(path_param_model.user_id)\n```\n\n\n### Serialization using Pydantic module and returning the response.\n\n\n```python\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import Session\n\n\ndb_engine = create_engine(DB_CONNECT_STRING)  # DB connection string, ex \"sqlite:///my_app.db\"\ndb = Session(db_engine)\n```\n\n```python\nfrom http import HTTPStatus\nfrom typing import Optional\n\nfrom flask import current_app as flask_app, jsonify\nfrom pydantic import BaseModel\n\nfrom flask_dantic import serialize, pydantic_validator\n\n\nclass UserResponseModel(BaseModel):  # Define the pydantic model for serialization.\n    username: str\n    age: Optional[int] = None\n    phone: Optional[str] = None\n\n\n@flask_app.route(\"/user/list\", methods=[\"GET\"])\ndef get_all_users():\n    users = get_all_users_from_db()\n\n    # Pass the db records and pydantic model to serialize method. Set many as True if there are multiple records.\n    serialized_users = serialize(users, UserResponseModel, many=True)  # Serialize call\n    return jsonify(serialized_users), HTTPStatus.OK\n\n\n@flask_app.route(\"/user/get/\u003cstring:user_id\u003e\", methods=[\"GET\"])\n@pydantic_validator(path_params=UserPathParamModel)  # Pass the model against path_params\ndef get_user(user_id):\n    user = get_single_user_by_id(user_id)\n    \n    # Pass the db record and pydantic model to serialize method. Many is set to False by default.\n    user = serialize(user, UserResponseModel)  # Serialize call\n    return jsonify(user), HTTPStatus.OK\n```\n\n### Serialization - Dump directly to json. This is useful when you want to return the response as json without flask jsonify.\n\n```python\nfrom flask_dantic import serialize\n\n# Taking the same example from above. Modifying the serialize call.\n@flask_app.route(\"/user/get/\u003cstring:user_id\u003e\", methods=[\"GET\"])\n@pydantic_validator(path_params=UserPathParamModel)  # Pass the model against path_params\ndef get_user(user_id):\n    user = get_single_user_by_id(user_id)\n    \n    # Pass the db record and pydantic model to serialize method. Many is set to False by default.\n      # Serialize call\n    return serialize(user, UserResponseModel, json_dump=True), HTTPStatus.OK\n```\n\nTests\n-----\n\nRun tests:\n\n```bash\n    pytest\n```\n\n\nLicense\n-------\n\nFlask-Dantic is released under the MIT License. See the bundled [`LICENSE`](https://github.com/vivekkeshore/flask-dantic/blob/main/LICENSE) file\nfor details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvivekkeshore%2Fflask-dantic","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvivekkeshore%2Fflask-dantic","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvivekkeshore%2Fflask-dantic/lists"}