Description
How can I remove the media type from the main response?
@router.delete("/topics/{topic}",
summary="Delete topic",
response_class=None,
responses={
200: {"description": "Topic successfully deleted"},
404: {"description": "Topic not found"}
})
async def delete_topic(topic):
"""
Delete a topic with all of it's entries
"""
deleted = await delete_topic(topic)
if not deleted:
return Response(status_code=404)
return
In this example the open-api documentation will show no media type for the 404 response, but it will show application/json for the 200 response. How can I remove that. My response body is always empty.
When you return, implicitly you return None and FastAPI under the hood generates a JSONResponse by default.
Should you want to return nothing you have to explicitly specify it using Response(status_code=whatever status you want)
see also https://github.com/tiangolo/fastapi/issues/449 for alternatives, in particular @dmontagu's one using the decorator
Thank you for your answer. But if I do it like this
@router.delete("/topics/{topic}",
summary="Delete topic",
response_class=None,
responses={
200: {"description": "Topic successfully deleted"},
404: {"description": "Topic not found"}
})
async def delete_topic(topic, redis: Redis = Depends(get_redis)):
"""
Delete a topic with all of it's entries
"""
deleted = await redis.delete(get_topic_stream_key(topic))
if deleted == 0:
return Response(status_code=404)
return Response(status_code=200)
the documentaion still shows

And if I change response_class to response_class=Response I get "AssertionError: A response class with media_type is needed to generate OpenAPI"
Confirmed. The OpenAPI output is broken for 204 responses and the workaround mentioned above no longer works to return a blank body. Looks like a bug to me.
You now can use response_class=Response, I'm not sure since which version :shrug: (we are now on version 0.54.1).
But this seems to work as you expected:
from fastapi import FastAPI, Response
app = FastAPI()
@app.delete(
"/topics/{topic}",
summary="Delete topic",
response_class=Response,
responses={
200: {"description": "Topic successfully deleted"},
404: {"description": "Topic not found"},
},
)
async def delete_topic(topic: str):
"""
Delete a topic with all of it's entries
"""
return Response(status_code=200)
thanks
Most helpful comment
Thank you for your answer. But if I do it like this
the documentaion still shows

And if I change
response_classtoresponse_class=ResponseI get "AssertionError: A response class with media_type is needed to generate OpenAPI"