Name | flask-typed-routes JSON |
Version |
0.0.2
JSON |
| download |
home_page | None |
Summary | Validate Flask request parameters effortlessly with Pydantic |
upload_time | 2024-11-20 10:58:48 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.10 |
license | MIT License Copyright (c) 2024 Rolando Morales Perez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
keywords |
python
flask
pydantic
validation
routes
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
[![CI](https://github.com/rmoralespp/flask_typed_routes/workflows/CI/badge.svg)](https://github.com/rmoralespp/flask_typed_routes/actions?query=event%3Arelease+workflow%3ACI)
[![pypi](https://img.shields.io/pypi/v/flask_typed_routes.svg)](https://pypi.python.org/pypi/flask_typed_routes)
[![codecov](https://codecov.io/gh/rmoralespp/jsonl/branch/main/graph/badge.svg)](https://app.codecov.io/gh/rmoralespp/flask_typed_routes)
[![license](https://img.shields.io/github/license/rmoralespp/jsonl.svg)](https://github.com/rmoralespp/flask_typed_routes/blob/main/LICENSE)
## About
**flask_typed_routes** is a `Python` library designed to validate `Flask` requests effortlessly with `Pydantic`.
**Documentation**: https://rmoralespp.github.io/flask_typed_routes/
## Features
- 🎯 **Type Safety:** Automatically validates requests based on standard Python type hints.
- 🔌 **Easy Integration:** Simple Flask extension for applying validation to Flask routes.
- ⚠️ **Error Handling:** Automatically returns meaningful error responses for validation failures.
- ✨ **Autocomplete**: Excellent editor integration, offering comprehensive completion across all contexts.
## Requirements
- Python 3.10+
- Pydantic 2.0+
- Flask
## Installation
To install **flask_typed_routes** using `pip`, run the following command:
```bash
pip install flask_typed_routes
```
## Getting Started
This tool offers comprehensive validation for various types of request parameters,
including **Path, Query, JsonBody, Header, and Cookie** parameters.
Example of a simple Flask application using `flask_typed_routes`:
Create a file `items.py` with:
```python
import flask
import flask_typed_routes as flask_tpr
app = flask.Flask(__name__)
flask_tpr.FlaskTypeRoutes(app)
@app.get('/items/<user>/')
def get_items(user: str, skip: int = 0, limit: int = 10):
# Parameters not included in the "path" are automatically treated as "query" parameters.
data = {
'user': user,
'skip': skip,
'limit': limit,
}
return flask.jsonify(data)
```
**Run the server with:**
```bash
flask --app items run --debug
```
Open your browser and go to `http://127.0.0.1:5000/items/myuser/?skip=20`
You will see the JSON response as:
```json
{
"limit": 10,
"skip": 20,
"user": "myuser"
}
```
**Validation:** Open your browser and go to `http://127.0.0.1:5000/items/myuser/?skip=abc`
You will see the JSON response with the error details because the `skip` parameter is not an integer:
```json
{
"errors": [
{
"input": "abc",
"loc": [
"query",
"skip"
],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"type": "int_parsing",
"url": "https://errors.pydantic.dev/2.9/v/int_parsing"
}
]
}
```
### Example with Pydantic Models
You can also use Pydantic models to validate request data in Flask routes.
Now let's update the `items.py` file with:
```python
import pydantic
import flask
import flask_typed_routes as flask_tpr
app = flask.Flask(__name__)
flask_tpr.FlaskTypeRoutes(app)
class Item(pydantic.BaseModel):
name: str
description: str = None
price: float
@app.post('/items/')
def create_item(item: Item):
return flask.jsonify(item.model_dump())
@app.put('/items/<item_id>/')
def update_item(item_id: int, item: Item):
return flask.jsonify({'item_id': item_id, **item.model_dump()})
```
### Using Flask Blueprints
You can also use `flask_typed_routes` with Flask Blueprints.
Now let's update the `items.py` file with:
```python
import flask
import flask_typed_routes as flask_tpr
app = flask.Flask(__name__)
flask_tpr.FlaskTypeRoutes(app)
app_v2 = flask.Blueprint('items', __name__, url_prefix='/v2')
@app_v2.get('/items/')
def get_items_v2(skip: int = 0, limit: int = 10, country: str = 'US'):
data = {'skip': skip, 'limit': limit, 'country': country}
return flask.jsonify(data)
app.register_blueprint(app_v2)
```
### Using Flask Class-Based Views
You can also use `flask_typed_routes` with Flask Class-Based Views.
Now let's update the `items.py` file with:
```python
import flask
import flask.views
import flask_typed_routes as flask_tpr
app = flask.Flask(__name__)
flask_tpr.FlaskTypeRoutes(app)
class UserProducts(flask.views.View):
def dispatch_request(self, user: str, skip: int = 0, limit: int = 10):
data = {'user': user, 'skip': skip, 'limit': limit}
return flask.jsonify(data)
class UserOrders(flask.views.MethodView):
def get(self, user: str, skip: int = 0, limit: int = 10):
data = {'user': user, 'skip': skip, 'limit': limit}
return flask.jsonify(data)
app.add_url_rule('/products/<user>/all/', view_func=UserProducts.as_view('user_products'))
app.add_url_rule('/orders/<user>/all/', view_func=UserOrders.as_view('user_orders'))
```
## Documentation
For more detailed information and usage examples, refer to the
project [documentation](https://rmoralespp.github.io/flask_typed_routes/)
## Development
To contribute to the project, you can run the following commands for testing and documentation:
### Running Unit Tests
Install the development dependencies and run the tests:
```
(env)$ pip install -r requirements-dev.txt # Skip if already installed
(env)$ python -m pytest tests/
(env)$ python -m pytest --cov # Run tests with coverage
```
### Building the Documentation
To build the documentation locally, use the following commands:
```
(env)$ pip install -r requirements-doc.txt # Skip if already installed
(env)$ mkdocs serve # Start live-reloading docs server
(env)$ mkdocs build # Build the documentation site
```
## License
This project is licensed under the [MIT license](LICENSE).
Raw data
{
"_id": null,
"home_page": null,
"name": "flask-typed-routes",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": null,
"keywords": "python, flask, pydantic, validation, routes",
"author": null,
"author_email": "rmoralespp <rmoralespp@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/75/28/8a91549eb222bcad5f94a23b48de1f632ef9f91de2d25549a375800b32f8/flask_typed_routes-0.0.2.tar.gz",
"platform": null,
"description": "[![CI](https://github.com/rmoralespp/flask_typed_routes/workflows/CI/badge.svg)](https://github.com/rmoralespp/flask_typed_routes/actions?query=event%3Arelease+workflow%3ACI)\n[![pypi](https://img.shields.io/pypi/v/flask_typed_routes.svg)](https://pypi.python.org/pypi/flask_typed_routes)\n[![codecov](https://codecov.io/gh/rmoralespp/jsonl/branch/main/graph/badge.svg)](https://app.codecov.io/gh/rmoralespp/flask_typed_routes)\n[![license](https://img.shields.io/github/license/rmoralespp/jsonl.svg)](https://github.com/rmoralespp/flask_typed_routes/blob/main/LICENSE)\n\n## About\n\n**flask_typed_routes** is a `Python` library designed to validate `Flask` requests effortlessly with `Pydantic`.\n\n**Documentation**: https://rmoralespp.github.io/flask_typed_routes/\n\n## Features\n\n- \ud83c\udfaf **Type Safety:** Automatically validates requests based on standard Python type hints.\n- \ud83d\udd0c **Easy Integration:** Simple Flask extension for applying validation to Flask routes.\n- \u26a0\ufe0f **Error Handling:** Automatically returns meaningful error responses for validation failures.\n- \u2728 **Autocomplete**: Excellent editor integration, offering comprehensive completion across all contexts.\n\n## Requirements\n\n- Python 3.10+\n- Pydantic 2.0+\n- Flask\n\n## Installation\n\nTo install **flask_typed_routes** using `pip`, run the following command:\n\n```bash\npip install flask_typed_routes\n```\n\n## Getting Started\n\nThis tool offers comprehensive validation for various types of request parameters,\nincluding **Path, Query, JsonBody, Header, and Cookie** parameters.\n\nExample of a simple Flask application using `flask_typed_routes`:\n\nCreate a file `items.py` with:\n\n```python\nimport flask\nimport flask_typed_routes as flask_tpr\n\napp = flask.Flask(__name__)\nflask_tpr.FlaskTypeRoutes(app)\n\n\n@app.get('/items/<user>/')\ndef get_items(user: str, skip: int = 0, limit: int = 10):\n # Parameters not included in the \"path\" are automatically treated as \"query\" parameters.\n data = {\n 'user': user,\n 'skip': skip,\n 'limit': limit,\n }\n return flask.jsonify(data)\n```\n\n**Run the server with:**\n\n```bash\nflask --app items run --debug\n```\n\nOpen your browser and go to `http://127.0.0.1:5000/items/myuser/?skip=20`\nYou will see the JSON response as:\n\n```json\n{\n \"limit\": 10,\n \"skip\": 20,\n \"user\": \"myuser\"\n}\n```\n\n**Validation:** Open your browser and go to `http://127.0.0.1:5000/items/myuser/?skip=abc`\nYou will see the JSON response with the error details because the `skip` parameter is not an integer:\n\n```json\n{\n \"errors\": [\n {\n \"input\": \"abc\",\n \"loc\": [\n \"query\",\n \"skip\"\n ],\n \"msg\": \"Input should be a valid integer, unable to parse string as an integer\",\n \"type\": \"int_parsing\",\n \"url\": \"https://errors.pydantic.dev/2.9/v/int_parsing\"\n }\n ]\n}\n```\n\n### Example with Pydantic Models\n\nYou can also use Pydantic models to validate request data in Flask routes.\nNow let's update the `items.py` file with:\n\n```python\nimport pydantic\nimport flask\nimport flask_typed_routes as flask_tpr\n\napp = flask.Flask(__name__)\nflask_tpr.FlaskTypeRoutes(app)\n\n\nclass Item(pydantic.BaseModel):\n name: str\n description: str = None\n price: float\n\n\n@app.post('/items/')\ndef create_item(item: Item):\n return flask.jsonify(item.model_dump())\n\n\n@app.put('/items/<item_id>/')\ndef update_item(item_id: int, item: Item):\n return flask.jsonify({'item_id': item_id, **item.model_dump()})\n```\n\n### Using Flask Blueprints\n\nYou can also use `flask_typed_routes` with Flask Blueprints.\n\nNow let's update the `items.py` file with:\n\n```python\nimport flask\nimport flask_typed_routes as flask_tpr\n\napp = flask.Flask(__name__)\nflask_tpr.FlaskTypeRoutes(app)\napp_v2 = flask.Blueprint('items', __name__, url_prefix='/v2')\n\n\n@app_v2.get('/items/')\ndef get_items_v2(skip: int = 0, limit: int = 10, country: str = 'US'):\n data = {'skip': skip, 'limit': limit, 'country': country}\n return flask.jsonify(data)\n\n\napp.register_blueprint(app_v2)\n```\n\n### Using Flask Class-Based Views\n\nYou can also use `flask_typed_routes` with Flask Class-Based Views.\n\nNow let's update the `items.py` file with:\n\n```python\nimport flask\nimport flask.views\n\nimport flask_typed_routes as flask_tpr\n\napp = flask.Flask(__name__)\nflask_tpr.FlaskTypeRoutes(app)\n\n\nclass UserProducts(flask.views.View):\n\n def dispatch_request(self, user: str, skip: int = 0, limit: int = 10):\n data = {'user': user, 'skip': skip, 'limit': limit}\n return flask.jsonify(data)\n\n\nclass UserOrders(flask.views.MethodView):\n \n def get(self, user: str, skip: int = 0, limit: int = 10):\n data = {'user': user, 'skip': skip, 'limit': limit}\n return flask.jsonify(data)\n\n \napp.add_url_rule('/products/<user>/all/', view_func=UserProducts.as_view('user_products'))\napp.add_url_rule('/orders/<user>/all/', view_func=UserOrders.as_view('user_orders'))\n```\n\n## Documentation\n\nFor more detailed information and usage examples, refer to the\nproject [documentation](https://rmoralespp.github.io/flask_typed_routes/)\n\n## Development\n\nTo contribute to the project, you can run the following commands for testing and documentation:\n\n### Running Unit Tests\n\nInstall the development dependencies and run the tests:\n\n```\n(env)$ pip install -r requirements-dev.txt # Skip if already installed\n(env)$ python -m pytest tests/\n(env)$ python -m pytest --cov # Run tests with coverage\n```\n\n### Building the Documentation\n\nTo build the documentation locally, use the following commands:\n\n```\n(env)$ pip install -r requirements-doc.txt # Skip if already installed\n(env)$ mkdocs serve # Start live-reloading docs server\n(env)$ mkdocs build # Build the documentation site\n```\n\n## License\n\nThis project is licensed under the [MIT license](LICENSE).\n",
"bugtrack_url": null,
"license": "MIT License Copyright (c) 2024 Rolando Morales Perez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
"summary": "Validate Flask request parameters effortlessly with Pydantic",
"version": "0.0.2",
"project_urls": {
"Changelog": "https://github.com/rmoralespp/flask_typed_routes/blob/main/CHANGELOG.md",
"Documentation": "https://rmoralespp.github.io/flask_typed_routes/",
"Homepage": "https://github.com/rmoralespp/flask_typed_routes",
"Issues": "https://github.com/rmoralespp/flask_typed_routes/issues",
"Source": "https://github.com/rmoralespp/flask_typed_routes"
},
"split_keywords": [
"python",
" flask",
" pydantic",
" validation",
" routes"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "a2d471dee5d87d68fbd5a419f51b8a0bcfcfab18c615b8c754e4f21d44df7975",
"md5": "e1709f6fe684373a8398efb5190533bc",
"sha256": "e81f04ed33a634adcaf44eb31a6b5009dc7bbc8dae0aa63ee964d7d30b943e6e"
},
"downloads": -1,
"filename": "flask_typed_routes-0.0.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "e1709f6fe684373a8398efb5190533bc",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.10",
"size": 10312,
"upload_time": "2024-11-20T10:58:47",
"upload_time_iso_8601": "2024-11-20T10:58:47.284218Z",
"url": "https://files.pythonhosted.org/packages/a2/d4/71dee5d87d68fbd5a419f51b8a0bcfcfab18c615b8c754e4f21d44df7975/flask_typed_routes-0.0.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "75288a91549eb222bcad5f94a23b48de1f632ef9f91de2d25549a375800b32f8",
"md5": "95bb5c1d553f6bfc9e53fc2779f4f4e6",
"sha256": "db1f21fa3f5a91e1c29632de2606781d48b6dc337edbc9ff89204d6a7addfdaf"
},
"downloads": -1,
"filename": "flask_typed_routes-0.0.2.tar.gz",
"has_sig": false,
"md5_digest": "95bb5c1d553f6bfc9e53fc2779f4f4e6",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.10",
"size": 11259,
"upload_time": "2024-11-20T10:58:48",
"upload_time_iso_8601": "2024-11-20T10:58:48.822462Z",
"url": "https://files.pythonhosted.org/packages/75/28/8a91549eb222bcad5f94a23b48de1f632ef9f91de2d25549a375800b32f8/flask_typed_routes-0.0.2.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-11-20 10:58:48",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "rmoralespp",
"github_project": "flask_typed_routes",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "flask-typed-routes"
}