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.
FastAPI performs significantly better in terms of efficiency. This happens as a result of asynchronous request processing. This makes FastAPI superior to Flask for larger-scale machine learning projects, especially enterprise ones, as it can handle requests much more efficiently.
I put routes to def __init__
. It works normally.
Example:
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
class CustomAPI(FastAPI):
def __init__(self, title: str = "CustomAPI") -> None:
super().__init__(title=title)
@self.get('/')
async def home():
"""
Home page
"""
return HTMLResponse("<h1>CustomAPI</h1><br/><a href='/docs'>Try api now!</a>", status_code=status.HTTP_200_OK)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With