Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Declare Request Example Data

You can declare examples of the data your app can receive.

Here are several ways to do it.

Extra JSON Schema data in Pydantic models

You can declareexamples for a Pydantic model that will be added to the generated JSON Schema.

fromfastapiimportFastAPIfrompydanticimportBaseModelapp=FastAPI()classItem(BaseModel):name:strdescription:str|None=Noneprice:floattax:float|None=Nonemodel_config={"json_schema_extra":{"examples":[{"name":"Foo","description":"A very nice Item","price":35.4,"tax":3.2,}]}}@app.put("/items/{item_id}")asyncdefupdate_item(item_id:int,item:Item):results={"item_id":item_id,"item":item}returnresults

That extra info will be added as-is to the outputJSON Schema for that model, and it will be used in the API docs.

You can use the attributemodel_config that takes adict as described inPydantic's docs: Configuration.

You can set"json_schema_extra" with adict containing any additional data you would like to show up in the generated JSON Schema, includingexamples.

Tip

You could use the same technique to extend the JSON Schema and add your own custom extra info.

For example you could use it to add metadata for a frontend user interface, etc.

Info

OpenAPI 3.1.0 (used since FastAPI 0.99.0) added support forexamples, which is part of theJSON Schema standard.

Before that, it only supported the keywordexample with a single example. That is still supported by OpenAPI 3.1.0, but is deprecated and is not part of the JSON Schema standard. So you are encouraged to migrateexample toexamples. 🤓

You can read more at the end of this page.

Field additional arguments

When usingField() with Pydantic models, you can also declare additionalexamples:

fromfastapiimportFastAPIfrompydanticimportBaseModel,Fieldapp=FastAPI()classItem(BaseModel):name:str=Field(examples=["Foo"])description:str|None=Field(default=None,examples=["A very nice Item"])price:float=Field(examples=[35.4])tax:float|None=Field(default=None,examples=[3.2])@app.put("/items/{item_id}")asyncdefupdate_item(item_id:int,item:Item):results={"item_id":item_id,"item":item}returnresults

examples in JSON Schema - OpenAPI

When using any of:

  • Path()
  • Query()
  • Header()
  • Cookie()
  • Body()
  • Form()
  • File()

you can also declare a group ofexamples with additional information that will be added to theirJSON Schemas inside ofOpenAPI.

Body withexamples

Here we passexamples containing one example of the data expected inBody():

fromtypingimportAnnotatedfromfastapiimportBody,FastAPIfrompydanticimportBaseModelapp=FastAPI()classItem(BaseModel):name:strdescription:str|None=Noneprice:floattax:float|None=None@app.put("/items/{item_id}")asyncdefupdate_item(item_id:int,item:Annotated[Item,Body(examples=[{"name":"Foo","description":"A very nice Item","price":35.4,"tax":3.2,}],),],):results={"item_id":item_id,"item":item}returnresults
🤓 Other versions and variants

Tip

Prefer to use theAnnotated version if possible.

fromfastapiimportBody,FastAPIfrompydanticimportBaseModelapp=FastAPI()classItem(BaseModel):name:strdescription:str|None=Noneprice:floattax:float|None=None@app.put("/items/{item_id}")asyncdefupdate_item(item_id:int,item:Item=Body(examples=[{"name":"Foo","description":"A very nice Item","price":35.4,"tax":3.2,}],),):results={"item_id":item_id,"item":item}returnresults

Example in the docs UI

With any of the methods above it would look like this in the/docs:

Body with multipleexamples

You can of course also pass multipleexamples:

fromtypingimportAnnotatedfromfastapiimportBody,FastAPIfrompydanticimportBaseModelapp=FastAPI()classItem(BaseModel):name:strdescription:str|None=Noneprice:floattax:float|None=None@app.put("/items/{item_id}")asyncdefupdate_item(*,item_id:int,item:Annotated[Item,Body(examples=[{"name":"Foo","description":"A very nice Item","price":35.4,"tax":3.2,},{"name":"Bar","price":"35.4",},{"name":"Baz","price":"thirty five point four",},],),],):results={"item_id":item_id,"item":item}returnresults
🤓 Other versions and variants

Tip

Prefer to use theAnnotated version if possible.

fromfastapiimportBody,FastAPIfrompydanticimportBaseModelapp=FastAPI()classItem(BaseModel):name:strdescription:str|None=Noneprice:floattax:float|None=None@app.put("/items/{item_id}")asyncdefupdate_item(*,item_id:int,item:Item=Body(examples=[{"name":"Foo","description":"A very nice Item","price":35.4,"tax":3.2,},{"name":"Bar","price":"35.4",},{"name":"Baz","price":"thirty five point four",},],),):results={"item_id":item_id,"item":item}returnresults

When you do this, the examples will be part of the internalJSON Schema for that body data.

Nevertheless, at thetime of writing this, Swagger UI, the tool in charge of showing the docs UI, doesn't support showing multiple examples for the data inJSON Schema. But read below for a workaround.

OpenAPI-specificexamples

Since beforeJSON Schema supportedexamples OpenAPI had support for a different field also calledexamples.

ThisOpenAPI-specificexamples goes in another section in the OpenAPI specification. It goes in thedetails for eachpath operation, not inside each JSON Schema.

And Swagger UI has supported this particularexamples field for a while. So, you can use it toshow differentexamples in the docs UI.

The shape of this OpenAPI-specific fieldexamples is adict withmultiple examples (instead of alist), each with extra information that will be added toOpenAPI too.

This doesn't go inside of each JSON Schema contained in OpenAPI, this goes outside, in thepath operation directly.

Using theopenapi_examples Parameter

You can declare the OpenAPI-specificexamples in FastAPI with the parameteropenapi_examples for:

  • Path()
  • Query()
  • Header()
  • Cookie()
  • Body()
  • Form()
  • File()

The keys of thedict identify each example, and each value is anotherdict.

Each specific exampledict in theexamples can contain:

  • summary: Short description for the example.
  • description: A long description that can contain Markdown text.
  • value: This is the actual example shown, e.g. adict.
  • externalValue: alternative tovalue, a URL pointing to the example. Although this might not be supported by as many tools asvalue.

You can use it like this:

fromtypingimportAnnotatedfromfastapiimportBody,FastAPIfrompydanticimportBaseModelapp=FastAPI()classItem(BaseModel):name:strdescription:str|None=Noneprice:floattax:float|None=None@app.put("/items/{item_id}")asyncdefupdate_item(*,item_id:int,item:Annotated[Item,Body(openapi_examples={"normal":{"summary":"A normal example","description":"A **normal** item works correctly.","value":{"name":"Foo","description":"A very nice Item","price":35.4,"tax":3.2,},},"converted":{"summary":"An example with converted data","description":"FastAPI can convert price `strings` to actual `numbers` automatically","value":{"name":"Bar","price":"35.4",},},"invalid":{"summary":"Invalid data is rejected with an error","value":{"name":"Baz","price":"thirty five point four",},},},),],):results={"item_id":item_id,"item":item}returnresults
🤓 Other versions and variants

Tip

Prefer to use theAnnotated version if possible.

fromfastapiimportBody,FastAPIfrompydanticimportBaseModelapp=FastAPI()classItem(BaseModel):name:strdescription:str|None=Noneprice:floattax:float|None=None@app.put("/items/{item_id}")asyncdefupdate_item(*,item_id:int,item:Item=Body(openapi_examples={"normal":{"summary":"A normal example","description":"A **normal** item works correctly.","value":{"name":"Foo","description":"A very nice Item","price":35.4,"tax":3.2,},},"converted":{"summary":"An example with converted data","description":"FastAPI can convert price `strings` to actual `numbers` automatically","value":{"name":"Bar","price":"35.4",},},"invalid":{"summary":"Invalid data is rejected with an error","value":{"name":"Baz","price":"thirty five point four",},},},),):results={"item_id":item_id,"item":item}returnresults

OpenAPI Examples in the Docs UI

Withopenapi_examples added toBody() the/docs would look like:

Technical Details

Tip

If you are already usingFastAPI version0.99.0 or above, you can probablyskip these details.

They are more relevant for older versions, before OpenAPI 3.1.0 was available.

You can consider this a brief OpenAPI and JSON Schemahistory lesson. 🤓

Warning

These are very technical details about the standardsJSON Schema andOpenAPI.

If the ideas above already work for you, that might be enough, and you probably don't need these details, feel free to skip them.

Before OpenAPI 3.1.0, OpenAPI used an older and modified version ofJSON Schema.

JSON Schema didn't haveexamples, so OpenAPI added its ownexample field to its own modified version.

OpenAPI also addedexample andexamples fields to other parts of the specification:

Info

This old OpenAPI-specificexamples parameter is nowopenapi_examples since FastAPI0.103.0.

JSON Schema'sexamples field

But then JSON Schema added anexamples field to a new version of the specification.

And then the new OpenAPI 3.1.0 was based on the latest version (JSON Schema 2020-12) that included this new fieldexamples.

And now this newexamples field takes precedence over the old single (and custom)example field, that is now deprecated.

This newexamples field in JSON Schema isjust alist of examples, not a dict with extra metadata as in the other places in OpenAPI (described above).

Info

Even after OpenAPI 3.1.0 was released with this new simpler integration with JSON Schema, for a while, Swagger UI, the tool that provides the automatic docs, didn't support OpenAPI 3.1.0 (it does since version 5.0.0 🎉).

Because of that, versions of FastAPI previous to 0.99.0 still used versions of OpenAPI lower than 3.1.0.

Pydantic and FastAPIexamples

When you addexamples inside a Pydantic model, usingschema_extra orField(examples=["something"]) that example is added to theJSON Schema for that Pydantic model.

And thatJSON Schema of the Pydantic model is included in theOpenAPI of your API, and then it's used in the docs UI.

In versions of FastAPI before 0.99.0 (0.99.0 and above use the newer OpenAPI 3.1.0) when you usedexample orexamples with any of the other utilities (Query(),Body(), etc.) those examples were not added to the JSON Schema that describes that data (not even to OpenAPI's own version of JSON Schema), they were added directly to thepath operation declaration in OpenAPI (outside the parts of OpenAPI that use JSON Schema).

But now that FastAPI 0.99.0 and above uses OpenAPI 3.1.0, that uses JSON Schema 2020-12, and Swagger UI 5.0.0 and above, everything is more consistent and the examples are included in JSON Schema.

Swagger UI and OpenAPI-specificexamples

Now, as Swagger UI didn't support multiple JSON Schema examples (as of 2023-08-26), users didn't have a way to show multiple examples in the docs.

To solve that, FastAPI0.103.0added support for declaring the same oldOpenAPI-specificexamples field with the new parameteropenapi_examples. 🤓

Summary

I used to say I didn't like history that much... and look at me now giving "tech history" lessons. 😅

In short,upgrade to FastAPI 0.99.0 or above, and things are muchsimpler, consistent, and intuitive, and you don't have to know all these historic details. 😎


[8]ページ先頭

©2009-2026 Movatter.jp