Validation

Clients, including the frontend you are writing, will often send the wrong data to the backend. The backend should therefore validate the structure and format of the data sent to it, and respond with a 400 response if it doesn't pass validation.

We'll use the Quart extension Quart-Schema to validate the structure (schema) of the data sent to the backend, first by installing,

Run this command in backend/

poetry add quart-schema

Then by activating the QuartSchema when creating the app in backend/src/backend/run.py,

from quart_schema import QuartSchema

schema = QuartSchema(convert_casing=True, openapi_path=None)

def create_app() -> None:
    ...
    schema.init_app(app)
    ...

We can then use Pydantic dataclasses to define and validate the data the backend expects to receive and to validate we send the correct data back to the frontend.

It would be useful to provide an informative response if the client sends the wrong data, we can do this by adding the following error handler to be backend/src/backend/run.py

...
from quart_schema import RequestSchemaValidationError

def create_app() -> Quart:
    ...

    @app.errorhandler(RequestSchemaValidationError)  # type: ignore
    async def handle_request_validation_error(
        error: RequestSchemaValidationError,
    ) -> ResponseReturnValue:
        if isinstance(error.validation_error, TypeError):
            return {"errors": str(error.validation_error)}, 400
        else:
            return {"errors": error.validation_error.json()}, 400