fastapi-utils icon indicating copy to clipboard operation
fastapi-utils copied to clipboard

[BUG] InferringRouter, typing and response without body

Open Sanchoyzer opened this issue 4 years ago • 1 comments

Python 3.7 Fastapi and fastapi-utils the latest Ubuntu 18.04

It seems that InferringRouter create response_model in case when this model has not expected

Example, this code is ok:

from typing import NoReturn, Optional

from fastapi import APIRouter

router = APIRouter()

@router.delete('/{item_id}', status_code=status.HTTP_204_NO_CONTENT)
def delete_item(*, item_id: int) -> Optional[NoReturn]:
    resource.get_or_404(obj_id=item_id)
    resource.remove(obj_id=item_id)

let's use InferringRouter instead APIRouter

class InferringRouter(APIRouter):
    def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) -> None:
        if kwargs.get("response_model") is None:
            kwargs["response_model"] = get_type_hints(endpoint).get("return")
        return super().add_api_route(path, endpoint, **kwargs)
from fastapi_utils.inferring_router import InferringRouter

router = InferringRouter()

@router.delete('/{item_id}', status_code=status.HTTP_204_NO_CONTENT)
def delete_item(*, item_id: int) -> Optional[NoReturn]:
    ...

exception!

AssertionError: Status code 204 must not have a response body
class APIRoute(routing.Route):
    def __init__(
        ...
        response_model: Type[Any] = None,
        ...
    ) -> None:
        self.response_model = response_model
        if self.response_model:
            assert (
                status_code not in STATUS_CODES_WITH_NO_BODY
            ), f"Status code {status_code} must not have a response body"

all of this examples failed:

def delete_item(*, item_id: int) -> Optional[NoReturn]:

def delete_item(*, item_id: int) -> None:

but example without typing works:

def delete_item(*, item_id: int):

is it possible to use InferringRouter for STATUS_CODES_WITH_NO_BODY with typing result of method?

Sanchoyzer avatar Mar 12 '20 17:03 Sanchoyzer

@dmontagu what may you say about it?

Sanchoyzer avatar Mar 19 '20 06:03 Sanchoyzer