FastAPI: JSON payload is missing unless run in debug mode

38 Views Asked by At

I'm using SQLModel and FastAPI, and testing with Pytest in VSCode. I have a post endpoint that is supposed to return a JSON representation of the model that's just been saved. This is specified using the response_model parameter:

@router.post("/foo/", response_model=Foo)
async def create_foo(f: Foo, 
                     session: Session = Depends(get_session)) -> Foo:
    try:
        obj = Foo(**f.model_dump())
    except ValueError as e:
        raise HTTPException(status_code=422, detail=str(e))
    session.add(obj)
    session.commit()
    return obj

The response_model part is supposed to handle serialising the outgoing object, so I shouldn't have to worry about constructing a JSONResponse - see the FastAPI docs.

When I run tests on this endpoint, or try out the API through the Swagger page, I get an empty JSON object - the response body is just {}.

Here's the strange part: if I add a breakpoint to the test on the line that sends the request or in my router code and step into the FastAPI routing methods line by line, the response comes back as expected. I pinned this down to a specific call to serialise_response on line 315 of fastapi/routing.py:

content = await serialize_response(
                        field=response_field,
                        response_content=raw_response,
                        include=response_model_include,
                        exclude=response_model_exclude,
                        by_alias=response_model_by_alias,
                        exclude_unset=response_model_exclude_unset,
                        exclude_defaults=response_model_exclude_defaults,
                        exclude_none=response_model_exclude_none,
                        is_coroutine=is_coroutine,
                    )

If I run in debug mode with a breakpoint on this line and step through each part, the response is built correctly and the test passes. If I hit continue when the breakpoint is reached, the content comes back empty and the test fails. What gives? Could this something to do with the fact that it's an async call?

Any suggestions very welcome!

0

There are 0 best solutions below