asynchronouspython-asynciofastapipython-decorators

Is it okay to use a synchronous decorator on a FastAPI route?


I want to add a decorator on a FastAPI route like this:

/admin/verification.py

from functools import wraps
import json

def admin_required(admin_function):
    @wraps(admin_function)
    def check_admin(*args, **kwargs):
        print("Verifiy admin session")

        return admin_function(*args, **kwargs)
    
    return check_admin

/upload/review.py

@review_router.get("/review")
@admin_required
async def get_review():
    return "GET"

I have never tried to use a decorator on an asynchronous function so I am confused if it is going to affect asynchronous tasks. Is it okay to wrapping an asynchronous function with a synchronous decorator? If it is not, is there any recommended way to handle it?


Solution

  • Yes, it's Ok to use such decorators.

    This use-case is covered by tests in FastAPI repo: https://github.com/fastapi/fastapi/blob/6513d4daa16a536d17743de6a292f49bd06388a4/tests/test_dependency_wrapped.py#L183-L200