django-ninja icon indicating copy to clipboard operation
django-ninja copied to clipboard

[Question] Header validation before schema validation for certain endpoints

Open torx-cz opened this issue 1 year ago • 1 comments

Hello, I'd like to ask for your opinion.

I need to do a header check (if the version is correct), but it needs to be before the input schema validation. The problem I'm having is that as soon as I use the decorator, a validation error (422) is thrown before my custom check, (it can throw 406 status code). I want a different order.

This would be fairly easy using Django-middleware however, I only need to do this on certain endpoints.

Example decorator:

router = Router()
...

@router.get(...)
@my_header_checker
def some_endpoint_handler(request: HttpRequest, data: SomeSchema)
...

I want to ask if there is any way to run some checks before input validation.

Thank you for your time and reply.

torx-cz avatar Jul 11 '24 12:07 torx-cz

Hi @torx-cz

You can do it with @decorate_view - which decorates your view function before any validation

from ninja.decorators import decorate_view


def my_header_checker(func):
    def wrapper(request, *a, **kw):
            # check here !<----
            return func(request, *a, **kw)
    return wrapper

@router.get(...)
@decorate_view(my_header_checker)
def some_endpoint_handler(request: HttpRequest, data: SomeSchema)
    ...

vitalik avatar Aug 20 '24 14:08 vitalik