### 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)
error: Argument 2 to "add_api_route" of "FastAPI" has incompatible type "Callable[[HelloRequest], Coroutine[Any, Any, HelloResponse]]"; expected "Callable[..., Coroutine[Any, Any, Response]]" [arg-type]
Second example does not.
Discussed in #10235
Originally posted by sidekick-eimantas September 12, 2023
First Check
Commit to Help
Example Code
Description
First example produces a mypy error:
Second example does not.
The types of
endpointparameter inFastAPI.add_api_routeandAPIRouter.add_api_routeare inconsistent.Operating System
macOS
Operating System Details
No response
FastAPI Version
0.103.1
Pydantic Version
2.3.0
Python Version
3.10.7
Additional Context
No response