首页 > 解决方案 > 使用 OpenAPI3 文档字符串中的 Flasgger 验证 POST 请求正文

问题描述

我有一个 Flask API,我用 OpenAPI3 文档字符串注释了每个端点。我现在想使用 Flasgger 的自动验证,但我不知道如何告诉 Flasgger 我想根据我在 requestBody 中定义的模式来验证请求。这是我尝试过的:

api = Blueprint('api', __name__,
            template_folder='templates')


@api.route("/apikey", methods=["POST"])
@swag.validate('apikeyrequest')
def generate_api_key():
    """Generate API key for user.
    This endpoint generates an API key for a user if provided with a valid password and username
    ---
    requestBody:
      content:
        'application/json':
          schema:
            id: apikeyrequest
            type: object
            required:
              - username
              - password
            properties:
              username:
                type: string
                example: "bob_andrews"
                description: The username of the user for which an API key is created.
              password:
                type: string
                example: "$k2%nvpdHS26!vEt"
                description: The users password
              twofa_token:
                type: string
                example: "425648"
                description: A one time password if the user has 2 factor authentication enabled.
    security: []
    responses:
      200:
        description: An API key for this user. The API key is stored as a hash, so it is only shown once.
        content:
          'application/json':
            schema:
              type: object
              properties:
                api_key:
                  type: string
                  description: 'The API key for the specified user.'
      401:
        description: Unauthorized, either due to wrong credentials or a missing two factor token if the user has
          two factor authentication enabled.
        content:
          'application/json':
            schema:
              type: object
              properties:
                error:
                  type: string
                  description: A string describing which part failed and (possibly) why.

      500:
        description: Server error, the error json will contain more details.
        content:
          'application/json':
            schema:
              type: object
              properties:
                error:
                  type: string
                  description: A string describing which part failed and (possibly) why.
    """

查看 Swagger UI 页面时收到的错误消息是:

Resolver error at paths./api/apikey.post.requestBody.content.application/json.schema.$ref
Could not resolve reference: Could not resolve pointer: /definitions/apikeyrequest does not exist in document

事实上,flasgger 生成的 apispec json 中的定义对象是空的。我想要验证的架构可以在paths/api/apikey/post/requestBody.

标签: flaskopenapiflasgger

解决方案


推荐阅读