-
-
Notifications
You must be signed in to change notification settings - Fork 9k
Inconsistent add_api_route types #10236
Copy link
Copy link
Closed
Labels
bugSomething isn't workingSomething isn't workingconfirmedeasy closegood first issueGood for newcomersGood for newcomers
Description
Discussed in #10235
Originally posted by sidekick-eimantas September 12, 2023
First Check
- I added a very descriptive title here.
- I used the GitHub search to find a similar question and didn't find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google "How to X in FastAPI" and didn't find any information.
- I already read and followed all the tutorial in the docs and didn't find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
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)Description
First example produces a mypy error:
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.
The types of endpoint parameter in FastAPI.add_api_route and APIRouter.add_api_route are 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
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't workingconfirmedeasy closegood first issueGood for newcomersGood for newcomers