question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[FEATURE] Enable support for multiple request body "examples" in openapi / swagger ui docs

See original GitHub issue

This feature is related to issue #372

It appears to me in the Swagger UI documentation on adding examples that the ‘examples’ key belongs to ‘application/json’. It also appears to me that the key already exists in the MediaType model within fastapi.openapi.models but that only the ‘schema’ key is modified when writing the openapi spec through fastapi.openapi.utils.get_openapi_operation_request_body and then fastapi.openapi.utils.get_open_api_path and that the media type is nearly always passed around as a string rather than a dict or model object (please correct me if I’m wrong, I’ve only been using these particular tools for a few months.)

pydantic recently enabled schema_extra in samuelcolvin/pydantic#663 but I can’t seem to get it to work with the swagger docs. At this time it’s unclear to me if this is simply a part of the json schema spec that the swagger ui doesn’t recognize yet, or if it’s actually a deliberate deviation from the spec, or if I just can’t figure it out. From the JSON Schema documentation on “examples” it states that this field “MUST” be an array. The aforementioned pydantic PR#663 and the associated example adhere to the spec well, but I cannot seem to build a request model using this newly minted ability that is supported by the swagger docs.

Here’s a working reference swagger ui yaml file that builds the dropdown examples pick list in the swagger editor. I started with the fastapi.docs.body_fields.tutorial_002.py example and hand edited the swagger ui yaml to match the swagger examples docs for multiple examples:

openapi: 3.0.2
info:
  title: Fast API
  version: 0.1.0
paths:
  '/items/{item_id}':
    put:
      summary: Update Item
      operationId: update_item_items__item_id__put
      parameters:
        - required: true
          schema:
            title: Item Id
            type: integer
          name: item_id
          in: path
      requestBody:
        content:
          application/json:
            schema:
              title: Item
              allOf:
                - $ref: '#/components/schemas/Item'
            examples:
              test1:
                  summary: first test
                  value:
                    name: Foo
                    description: A very nice Item
                    price: 35.4
                    tax: 3.2
              test2:
                  summary: second test
                  value:
                    name: Bar
                    description: Another very nice Item
                    price: 30
                    tax: 1.1
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
components:
  schemas:
    HTTPValidationError:
      title: HTTPValidationError
      type: object
      properties:
        detail:
          title: Detail
          type: array
          items:
            $ref: '#/components/schemas/ValidationError'
    Item:
      title: Item
      required:
        - name
        - price
      type: object
      properties:
        name:
          title: Name
          type: string
        description:
          title: Description
          type: string
        price:
          title: Price
          type: number
        tax:
          title: Tax
          type: number
    ValidationError:
      title: ValidationError
      required:
        - loc
        - msg
        - type
      type: object
      properties:
        loc:
          title: Location
          type: array
          items:
            type: string
        msg:
          title: Message
          type: string
        type:
          title: Error Type
          type: string

My hope is that either 1) There is another way to add multiple examples for a request body that I am missing or that 2) we can build a means for adding the “examples” dictionary to the media type so it appears in the swagger ui per their documented format, preferably building from the recent pydantic PR referenced above.

I recognize that a few things complicate this effort, including the fact that a fastapi Route can include multiple Body objects. This might mean that if we support the documented swagger format linked above for multiple examples, the attribute might have to be moved out of the Body function/class so that only one “examples” dict can be specified per route, or better yet, per content media type somehow.

With some direction I think I would be able to help implement this, since it’s not a mission critical feature for the lead developers.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:7
  • Comments:14 (11 by maintainers)

github_iconTop GitHub Comments

5reactions
austinorrcommented, Apr 15, 2020

went ahead and opened a PR so the diff and example/tutorial is easier to review.

3reactions
tiangolocommented, May 5, 2021

Thanks for all the discussion and arguments here everyone! 🤓 ☕

It helped me to clarify and understand better all the context and everything.

And thanks @austinorr for the work on the PR! 🚀

I updated it a bit and added support for example and examples also in parameters like Path(), Query(), etc. A lot more of the technical details are in the comment: https://github.com/tiangolo/fastapi/pull/1267#issuecomment-832911064

This will be available in the next release of FastAPI, 0.64.0, in the next couple of days. 🎉

Read more comments on GitHub >

github_iconTop Results From Across the Web

OpenAPI Specification - Version 3.0.3 - Swagger
The OpenAPI Specification defines a standard interface to RESTful APIs which allows both humans and computers to understand service capabilities without ...
Read more >
Describing Request Body - Swagger
Differences From OpenAPI 2.0 · Body and form parameters are replaced with requestBody . · Operations can now consume both form data and...
Read more >
Links - Swagger
Links are one of the new features of OpenAPI 3.0. Using links, you can describe ... POST /users HTTP/1.1; Host: example.com; Content-Type: application/json ......
Read more >
Adding Examples - Swagger
Note for Swagger UI users: Support for multiple examples is available since Swagger UI 3.23.0 and Swagger Editor 3.6.31. Note: Do not confuse...
Read more >
Using OpenAPI and Swagger UI - Quarkus
By default, a request to /q/openapi will serve the combined OpenAPI document from the static file and the model generated from application endpoints...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found