Синтаксис для методов HTTP в том же самом определении, используя Swagger

Я новичок в SwaggerUI. В моем коде Python у меня есть API под названием "работа", который поддерживает методы HTTP POST, PUT и DELETE.

Теперь я хочу создать Swagger Documentation для того же. Я использую следующий код:

@app.route('/work', methods=['POST', 'PUT', 'DELETE'])
def work():
"""
    Micro Service Based API for work operations
    This API is for work to task matching operations
    ---
    paths:
      /cv:
        put:
          parameters:
            - name: body
              in: body
              required: true
              schema:
                id: data
                properties:
                    _id:
                        type: string
              description: Id
          responses:
                    200:
                        description: Please wait the calculation, you'll receive an email with results
        delete:
          parameters:
            - name: body
              in: body
              required: true
              schema:
                id: data
                properties:
                    _id:
                        type: string
              description: Id
          responses:
                    200:
                        description: Please wait the calculation, you'll receive an email with results
        post:
          responses:
                    200:
                        description: done
"""

Тем не менее, это не похоже на работу.

Я попытался просмотреть следующую ссылку Документация, но не сильно помог https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#pathsObject

Не могли бы вы помочь мне?

Параметры каждого из запросов HTTP-методов различны, и я также хочу указать разные описания для каждого метода в моем HTTP-интерфейсе.

редактирует

Добавил это в файл index.yml.

swagger: "2.0"
info:
  description: "This is a sample server Petstore server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters."
  version: "1.0.0"
  title: "Swagger Petstore"
  schemes:
- "http"
paths:
  /work:
    put:
      tags:
  - "WORK"
  summary: "Update a Work Score"
  description: ""
  consumes:
  - "application/json"
  parameters:
  - in: "body"
    name: "body"
    description: "Work ID whose score needs to be updates"
    required: true
    schema:
      $ref: "#/definitions/Data"
  responses:
    200:
      description: "Invalid input"
  /scoreCompute:
    post:
  tags:
  - "ABCD"
  summary: "Compute ABCD"
  description: ""
  consumes:
  - "application/json"
  parameters:
  - in: "body"
    name: "body"
    description: "Compute ABCD"
    required: true
    schema:
      $ref: "#/definitions/TaskId"
  responses:
    200:
      description: "Invalid input"
definitions:
  Data:
type: object
properties:
  _id:
    type: string
    description: Enter ID
  TaskId:
type: object
properties:
  job_id:
    type: string
    description: Enter ID

Внесены вышеуказанные изменения в код Python.

@app.route('/work', methods=['POST', 'PUT', 'DELETE'])
@swag_from('index.yml')
def work():

Однако http://127.0.0.1:5000/apidocs/ вообще ничего не показывает.

1 ответ

Решение

Если вы используете Flasgger ( http://github.com/rochacbruno/flasgger) К сожалению, он пока не поддерживает определение различных методов HTTP в одной и той же строке документации, эта проблема открыта.

Тем не менее, есть обходной путь, чтобы заставить его работать.

1) Поместите свой YAML в отдельный файл
2) Загрузите его из файла Swagger

ФАЙЛ YAML, сохраняет как test.yaml:

definitions:
  Data:
    type: object
    properties:
      _id:
        type: string

paths:
  /cv:
    put:
      parameters:
        - name: body
          in: body
          required: true
          schema:
            $ref: '#/definitions/Data'
      responses:
        200:
          description: |
            Please wait the calculation, you'll receive an email with results
    delete:
      parameters:
        - name: body
          in: body
          required: true
          schema:
            $ref: '#/definitions/Data'
      responses:
        200:
          description: |
            Please wait the calculation, you'll receive an email with results
    post:
      responses:
        200:
          description: done

а затем test.py

from flask import Flask
from flasgger import Swagger


app = Flask(__name__)
Swagger(app, template_file='test.yaml')


@app.route('/cv', methods=['POST', 'PUT', 'DELETE'])
def cv():
    """
    Micro Service Based API for CV operations
    This API is for job to CVs matching operations
    """


app.run(debug=True)

И вы получаете

flasgger

Другие вопросы по тегам