最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

fastapi - How to set response body example - Stack Overflow

matteradmin8PV0评论

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

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"
                    }
                  ]
                }
              }
            }
          }
        }
      }
    },

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

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"
                    }
                  ]
                }
              }
            }
          }
        }
      }
    },
Share Improve this question asked Nov 18, 2024 at 20:17 sixtyfootersdudesixtyfootersdude 27.3k45 gold badges154 silver badges223 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

This works but is very verbose:

@router.get("/", response_model=Ham, responses={
    200: {
        "content": {
            "application/json": {
                "example": {"color": "pink"}
            }
        }
    }
})
async def get_ham() -> Ham:
    return Ham(color="green")

This is a pretty good solution:

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

    model_config = {
        "json_schema_extra": {
            "example": {
                "color": "Red"
            }
        }
    }
Post a comment

comment list (0)

  1. No comments so far