django-ninja
django-ninja copied to clipboard
How to set custom description for response status codes?
Possible solution, but not work:
@router.post('/confirm/task/{task_uuid}/', tags=['tasks'], response={200: 'Task confirmed', 404: 'Task not found'})
Can i do this with schemas?

@blohinn
Unfortunately overriding response descriptions currently not possible..
I think the best approach would be to add extra parameter:
@api.get('/some',
response={200: Schema1, 404: Schema2},
response_description={200: 'OK', 404: 'Task not found'}, # <-----
):
def some(...
What if instead an additional, dedicated, type was recognised when declaring responses? Which would be backwards compatible. What I'm saying is something like:
@api.get(
"...",
response={
200: Response(model=Schema1, description="Super successful"),
404: Response(model=Schema2, description="Task not found"),
}
):
def endpoint(...) -> ...:
...
@flaeppe not sure.. seems some extra thing that cognitively hard to keep in mind for users...
for now this is how it looks like people mainly add descriptions :
@api.get(
"/some",
response={
200: SomeSchema,
403: ForbiddenSchema
},
openapi_extra = {
"responses": {
200: {"description": "You will receive this response if everything is ok"},
403: {"description": "You don't have what it takes for this API"}
}
}
)
def some(request):
# ...
maybe the best way would be to use some thing from schema (like docstring or some extra parameter) that will automatically be copied to openapi descriptions... which seems the most intuitive.. but the docstirng of the Schema is acutally printed on schema spec it self... while on the other hand I think duplicating this description to extra is not a big problem
I wasn't aware of that there was a way to add response descriptions. Did I miss it in the documentation?
And I just want to clarify, in case it was unclear, that I still meant it'd be possible to pass on only a schema, like
response={
200: SomeSchema,
403: ForbiddenSchema,
}
Just as well as doing
response={
200: Response(model=SomeSchema, description="..."),
403: Response(model=ForbiddenSchema, description="..."),
}
maybe something like Annotated actually can look better here:
@api.get("...",
response={
200: Annotated[Schema1, "Super successful"],
404: Annotated[Schema2, "Task not found"],
}
):
def endpoint(...) -> ...:
which can be aliased to Description = Annotated
or even tuples
@api.get("...",
response={
200: (Schema1, "Super successful"),
404: (Schema2, "Task not found"),
}
):
def endpoint(...) -> ...: