fastapiswagger-ui

How to set response body example


I have a fastapi endpoint for which I am trying to set the example value:

enter image description here

The fastapi doc seems to indicate that you can add examples to request parameters but I cannot figure out how to set the response example.

My code:

from typing import Annotated

import structlog
from fastapi import (
    APIRouter, Body,
)
from openai import BaseModel
from pydantic import Field

logger = structlog.get_logger(__name__)
router = APIRouter(prefix="/ham")

class Ham(BaseModel):
    color: str = Field(..., description="What color?")

BetterHam = Annotated[Ham, Body(examples=[{"color": "pink"}])]

@router.get("/")
async def get_ham() -> BetterHam:
    return Ham(color="green")

This is setting an example in the openapi.json, but I think that this is at the wrong level. According to the swagger-ui doc, the example should be a sibling to schema not a child. Doc

   "/ham/": {
      "get": {
        "summary": "Get Ham",
        "operationId": "get_ham",
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Ham",
                  "examples": [ 
                    {
                      "color": "pink"
                    }
                  ]
                }
              }
            }
          }
        }
      }
    },

Solution

  • This is a pretty good solution:

    class Ham(BaseModel):
        color: str = Field(..., description="What color?")
    
        model_config = {
            "json_schema_extra": {
                "example": {
                    "color": "Red"
                }
            }
        }