vitalik / django-ninja

💨 Fast, Async-ready, Openapi, type hints based framework for building APIs
https://django-ninja.dev
MIT License
7.28k stars 433 forks source link

[Question] Header validation before schema validation for certain endpoints #1226

Open torx-cz opened 4 months ago

torx-cz commented 4 months ago

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.

vitalik commented 2 months ago

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)
    ...