Inconsistent add_api_route types #10235
Answered
by
Kludex
sidekick-eimantas
asked this question in
Questions
-
First Check
Commit to Help
Example Code### Direct mounting of routes
import pathlib
from fastapi import FastAPI, APIRouter
import uvicorn
import pydantic
class HelloRequest(pydantic.BaseModel):
id: str
class HelloResponse(pydantic.BaseModel):
hello: str
class Hello:
def __init__(self, name: str) -> None:
self.name = name
async def handle(self, request: HelloRequest) -> HelloResponse:
return HelloResponse(hello=self.name)
app = FastAPI()
hello_handler = Hello(name="test")
app.add_api_route("/hello", hello_handler.handle, methods=["POST"])
### Mounting of paths via Router
import pathlib
from fastapi import FastAPI, APIRouter
import uvicorn
import pydantic
class HelloRequest(pydantic.BaseModel):
id: str
class HelloResponse(pydantic.BaseModel):
hello: str
class Hello:
def __init__(self, name: str) -> None:
self.name = name
async def handle(self, request: HelloRequest) -> HelloResponse:
return HelloResponse(hello=self.name)
class RootRouter:
def __init__(self, name: str):
self.router = APIRouter()
hello_handler = Hello(name=name)
self.router.add_api_route("/hello", hello_handler.handle, methods=["POST"])
app = FastAPI()
root_router = RootRouter(name="test")
app.include_router(root_router.router) DescriptionFirst example produces a mypy error:
Second example does not. The types of Operating SystemmacOS Operating System DetailsNo response FastAPI Version0.103.1 Pydantic Version2.3.0 Python Version3.10.7 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Answered by
Kludex
Sep 12, 2023
Replies: 1 comment 2 replies
-
As much as simple, and trivial this is to fix, it's a valid thing to fix. 😅 Thanks. |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
sidekick-eimantas
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As much as simple, and trivial this is to fix, it's a valid thing to fix. 😅
Thanks.