Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 933
eek Avatar asked Sep 11 '20 20:09

eek


People also ask

Is FastAPI good for large projects?

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.


1 Answers

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)
like image 66
Khiem Tran Avatar answered Oct 07 '22 00:10

Khiem Tran