Last active
April 13, 2023 15:14
-
-
Save odashi/0089fecfccbe17e12f80339921520a74 to your computer and use it in GitHub Desktop.
FastAPI server defined on a class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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