最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

fastapi - How to set response body example - Stack Overflow

programmeradmin1浏览0评论

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"
            }
        }
    }
发布评论

评论列表(0)

  1. 暂无评论