Skip to content

Instantly share code, notes, and snippets.

@odashi
Last active April 13, 2023 15:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odashi/0089fecfccbe17e12f80339921520a74 to your computer and use it in GitHub Desktop.
Save odashi/0089fecfccbe17e12f80339921520a74 to your computer and use it in GitHub Desktop.
FastAPI server defined on a class
# Sometimes you want to define your FastAPI app within a class for some reason, e.g.,
# you wanted to initialize the servers at the point you intended, not the point of import.
#
# In this case, @app.method decorator doesn't work as-is with instance methods due to the
# difference of its signature.
#
# You need to manually call the decorator as a usual function after obtaining self (e.g.,
# in the __init__ method like below) rather than using the decorator syntax.
class MyApp:
def __init__(self):
self._app = fastapi.FastAPI()
self._app.get("/hello")(self._hello) # Functional form to register the endpoint.
@property
def app(self) -> fastapi.FastAPI:
return self._app
async def _hello(self):
return {"hello": "world"}
if __name__ == "__main__":
# Obtains the ASGI interface of your app to pass it to the server process.
run_your_asgi_server(MyApp().app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment