pythonpython-3.xclassselffastapi

How to create routes with FastAPI within a class


So I need to have some routes inside a class, but the route methods need to have the self attr (to access the class' attributes). However, FastAPI then assumes self is its own required argument and puts it in as a query param

This is what I've got:

app = FastAPI()
class Foo:
    def __init__(y: int):
        self.x = y

    @app.get("/somewhere")
    def bar(self): return self.x

However, this returns 422 unless you go to /somewhere?self=something. The issue with this, is that self is then str, and thus useless.

I need some way that I can still access self without having it as a required argument.


Solution

  • For creating class-based views you can use @cbv decorator from fastapi-utils. The motivation of using it:

    Stop repeating the same dependencies over and over in the signature of related endpoints.

    Your sample could be rewritten like this:

    from fastapi import Depends, FastAPI
    from fastapi_utils.cbv import cbv
    from fastapi_utils.inferring_router import InferringRouter
    
    
    def get_x():
        return 10
    
    
    app = FastAPI()
    router = InferringRouter()  # Step 1: Create a router
    
    
    @cbv(router)  # Step 2: Create and decorate a class to hold the endpoints
    class Foo:
        # Step 3: Add dependencies as class attributes
        x: int = Depends(get_x)
    
        @router.get("/somewhere")
        def bar(self) -> int:
            # Step 4: Use `self.<dependency_name>` to access shared dependencies
            return self.x
    
    
    app.include_router(router)