[Python] How to create routes with FastAPI within a class

Discussão em 'Python' iniciado por Stack, Junho 30, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página