Skip to main content

Validate Flask requests effortlessly with Pydantic

Project description

CI pypi codecov 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.

TODOs:

Requirements

  • Python 3.10+
  • Pydantic 2.0+
  • Flask

Installation

To install flask_typed_routes using pip, run the following command:

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:

import flask
import flask_typed_routes as flask_tpr

app = flask.Flask(__name__)
flask_tpr.FlaskTypedRoutes(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:

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:

{
  "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:

{
  "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:

import pydantic
import flask
import flask_typed_routes as flask_tpr

app = flask.Flask(__name__)
flask_tpr.FlaskTypedRoutes(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:

import flask
import flask_typed_routes as flask_tpr

app = flask.Flask(__name__)
flask_tpr.FlaskTypedRoutes(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:

import flask
import flask.views

import flask_typed_routes as flask_tpr

app = flask.Flask(__name__)
flask_tpr.FlaskTypedRoutes(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

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.

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_typed_routes-0.0.4.tar.gz (11.5 kB view details)

Uploaded Source

Built Distribution

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

flask_typed_routes-0.0.4-py3-none-any.whl (10.6 kB view details)

Uploaded Python 3

File details

Details for the file flask_typed_routes-0.0.4.tar.gz.

File metadata

  • Download URL: flask_typed_routes-0.0.4.tar.gz
  • Upload date:
  • Size: 11.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.9.20

File hashes

Hashes for flask_typed_routes-0.0.4.tar.gz
Algorithm Hash digest
SHA256 efef703a6cbfaf2d6c71358a22487e7e515743e82c2dccec71a25b2e34ead73d
MD5 59231254390c7ba709aae746a5fcd201
BLAKE2b-256 d50d82fb7a227787cbf76d6e63e6df05c4ae5736d02e7161e7f2d0df9a37ded3

See more details on using hashes here.

File details

Details for the file flask_typed_routes-0.0.4-py3-none-any.whl.

File metadata

File hashes

Hashes for flask_typed_routes-0.0.4-py3-none-any.whl
Algorithm Hash digest
SHA256 7f0d5d45752d0825ec3a88addc3201a8b5571171b7ba1cb3fabf4b0878bdeb67
MD5 f50d51afdb81b2fa14a72b9280f92a81
BLAKE2b-256 b73199521fed14dd48a54aff461425eb259c30471eac3f96ad57e67a7dffdbbe

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