OpenAPI 3.0 - Как избежать добавления ключа «значение» при включении примеров по ссылке - PullRequest
1 голос
/ 28 января 2020

С OpenAPI Есть ли способ включить примеры по ссылке с тегом $ ref:, который не требует добавления ключа «value»?

См. Примеры, которые я добавил в petstore.yaml :

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Swagger Petstore
  license:
    name: MIT
servers:
  - url: http://petstore.swagger.io/v1
paths:

  /pets:
    get:
      summary: List all pets
      operationId: listPets
      tags:
        - pets
      parameters:
        - name: limit
          in: query
          description: How many items to return at one time (max 100)
          required: false
          schema:
            type: integer
            format: int32
      responses:
        '200':
          description: A paged array of pets
          headers:
            x-next:
              description: A link to the next page of responses
              schema:
                type: string
          content:
            application/json:    
              schema:
                $ref: "#/components/schemas/Pets"
              example:
                $ref: "#/components/examples/animals"

        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
    post:
      summary: Create a pet
      operationId: createPets
      tags:
        - pets
      responses:
        '201':
          description: Null response
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

  /pets/{petId}:
    get:
      summary: Info for a specific pet
      operationId: showPetById
      tags:
        - pets
      parameters:
        - name: petId
          in: path
          required: true
          description: The id of the pet to retrieve
          schema:
            type: string
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pet"
              example:
                $ref: "#/components/examples/garfield"
        default:
          description: unexpected error
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"

components:
  schemas:
    Pet:
      type: object
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        tag:
          type: string

    Pets:
      type: array
      items:
        $ref: "#/components/schemas/Pet"

    Error:
      type: object
      required:
        - code
        - message
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string

  examples:
    garfield:
      id: 1
      name: garfield
      tag: cat
    grumpycat:
      id: 2
      name: grumpycat
      tag: cat
    odie:
      id: 3
      name: odie
      tag: dog
    animals:
      - $ref: "#/components/examples/garfield"
      - $ref: "#/components/examples/grumpycat"
      - $ref: "#/components/examples/odie"

openapi-generator-cli validate говорит, что это недопустимый OpenAPI, как и мой плагин OpenAPI для VSCode. Вывод журнала ошибок:

Validating spec (/local/petstore.yaml)
Errors:
    -attribute components.examples.odie.name is unexpected
    -attribute components.examples.garfield.id is unexpected
    -attribute components.examples.grumpycat.name is unexpected
    -attribute components.examples.animals is not of type `object`
    -attribute components.examples.garfield.tag is unexpected
    -attribute components.examples.garfield.name is unexpected
    -attribute components.examples.odie.tag is unexpected
    -attribute components.examples.grumpycat.id is unexpected
    -attribute components.examples.grumpycat.tag is unexpected
    -attribute components.examples.odie.id is unexpected

[error] Spe c имеет 10 ошибок.

Я могу исправить ошибки, добавив ключ значения следующим образом:

  examples:
    garfield:
      value:
        id: 1
        name: garfield
        tag: cat
    grumpycat:
      value:
        id: 2
        name: grumpycat
        tag: cat
    odie:
      value:
        id: 3
        name: odie
        tag: dog
    animals:
      value:
        - $ref: "#/components/examples/garfield"
        - $ref: "#/components/examples/grumpycat"
        - $ref: "#/components/examples/odie"

Проблема в том, что мои примеры теперь включают свойство value, которое мне не нужно, поскольку оно не является частью схемы:

{
    "value": {
        "id": 1,
        "name": "garfield",
        "tag": "cat"
    }
}

Вопрос: Есть ли способ для меня определить примеры $ ref, как я сделал без использования свойства "value"?

1 Ответ

0 голосов
/ 28 января 2020

Правильный синтаксис выглядит следующим образом:

components:
  examples:
    garfield:
      value:
        id: 1
        name: garfield
        tag: cat
    grumpycat:
      value:
        id: 2
        name: grumpycat
        tag: cat
    odie:
      value:
        id: 3
        name: odie
        tag: dog
    animals:
      summary: An array of two animals
      value:
        - id: 1
          name: garfield
          tag: cat
        - id: 2
          name: grumpycat
          tag: cat

paths:
  /pets:
    get:
      ...
      responses:
        '200':
          description: A paged array of pets
          ...
          content:
            application/json:    
              schema:
                $ref: "#/components/schemas/Pets"
              examples:
                animals:
                  $ref: "#/components/examples/animals"

  /pets/{petId}:
    get:
      ...
      responses:
        '200':
          description: Expected response to a valid request
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Pet"
              examples:
                garfield:
                  $ref: "#/components/examples/garfield"
                grumpycat:
                  $ref: '#/components/examples/grumpycat'
                odie:
                  $ref: '#/components/examples/odie'

Объяснение:

  • В примерах в разделе components/examples должен использоваться Пример объекта синтаксис. То есть фактическое значение примера должно быть заключено в клавишу value.

  • Для ссылки на примеры из раздела components/examples необходимо использовать ключевое слово examples (множественное число; не единственное число example). examples поддерживается в параметрах и типах носителей, но не в схемах.

  • В буквальном значении примера $ref не поддерживается. То есть вы не можете $ref часть примера.

...