How can I see on the API docs what is the Schema being returned inside a list?

103 Views Asked by At

How can I see on the API docs what is the Schema being returned inside a list?

response={
    200: list[PersonSchema]
}

It troubles me that by looking the docs the information that the content of this response is a list of type PersonSchema is lost.


Example with code:

class PersonSchema(Schema):
  id: int
  name: str
  age: int

On an endpoint that returns a single object of the Schema above:

@playbook_routes_api.get(
    "/person/{person_id}",
    response={
        200: PersonSchema
    }
)
def get_person_by_id(request, person_id: int):
    return 200, PersonSchema(id=1, name='Brian', age=12)

The API explicity shows the Schema and its contents:

enter image description here

However. On an endpoint that returns a list of the same Schema:

@playbook_routes_api.get(
    "/person/",
    response={
        200: list[PersonSchema]
    }
)
def get_persons(request):
    return 200, [PersonSchema(id=1, name='Brian', age=12), PersonSchema(id=2, name='John', age=31)]

This time the API shows no information about the Schema at all. There is a general 'Response' and an 'items' atribute inside it. By looking just at this endpoint it is not possible to know what is the Schema being returned.

enter image description here

1

There are 1 best solutions below

4
VonC On BEST ANSWER

In Django-Ninja, the Schema classes do not natively support a title attribute directly within the class body. Instead, Django-Ninja schemas can include meta information through a Config inner class, which is a common pattern for Pydantic models (upon which Django-Ninja's schemas are based).

However, while Pydantic allows for a title attribute in the Config class to specify a title for the model in the generated schema, this title's visibility in the Swagger UI generated by Django-Ninja might not behave as one might intuitively expect.

from django_ninja import Schema

class PersonSchema(Schema):
    id: int
    name: str
    age: int

    class Config:
        title = "Person"  # Attempt to add a title for Swagger UI documentation

As Jeremy mentioned, whether the class name or the title attribute's value is used in the documentation is up to the framework's design. That means that even with the title specified, Django-Ninja (or more accurately, the Swagger UI it generates) may not consistently display this title in the way you expect across different contexts (e.g., single object vs. list of objects).

Adding a title in the Config might not have the intended effect on the Swagger UI documentation without explicit support or acknowledgment of this attribute by Django-Ninja for this specific purpose. It is beneficial for schema clarity in general (especially in the generated OpenAPI schema) but might not resolve the specific issue of schema visibility in lists.

That is why Jeremy suggests raising this as a question or feature request in the Django-Ninja GitHub repository.