首页 > 解决方案 > 如何从python中的api规范yaml文件中检索数据?

问题描述

我有明确定义 api 版本的 api 规范文件。我想从 yaml 文件访问 api 版本数据并将其返回到我的端点之一。为此,我尝试读取我的 yaml 文件,但无法正确访问和获取 api 版本数据。也许我可能会在我的代码中出现缺陷。谁能指出我如何做到这一点?任何可能的想法?如何以编程方式从 python 中的 yaml 文件中获取和检索 api 版本?

api 规范 yaml 定义

这是 openapi 规范字段的定义方式:

openapi: 3.0.0
    info:
      title: test REST API
      description: Test REST API
      license:
        name: Apache 2.0
        url: https://www.apache.org/licenses/LICENSE-2.0.html
      version: 1.0.0
    servers:
    - url: /api/v1/
      description: test

    paths:
      /about:
        get:
          summary: api System Version
          description: Obtain current version of test api
          operationId: about_get
          responses:
            "200":
              description: About information
              content:
                application/json:
                  schema:
                    $ref: '#/components/schemas/version'
            "401":
              description: Authorization information is missing or invalid.
          x-openapi-router-controller: test_server.controllers.default_controller
      /rsession:

    components:
      schemas:
        version:
          required:
          - mayor
          - minor
          - name
          - patch
          type: object
          properties:
            name:
              type: string
            mayor:
              type: number
            minor:
              type: number
            patch:
              type: number
          description: api Version
          example:
            name: api
            mayor: 1
            minor: 0
            patch: 0

我的尝试

import yaml

spec_yaml= 'apispec.yaml'
with open(spec_yaml, 'r') as f:
    data = yaml.load(f)

result = {}
for elem in data['info']:
    name = elem.pop('version')
    result[name] = elem

data['apiversion'] = result

print(data['version'])

更新:错误

在测试上面的代码后,我在下面遇到了这个错误:

AttributeError: 'str' object has no attribute 'pop'

这对我不起作用。有什么方法可以正确访问我的 api 规范 yaml 文件并在 python 函数中获取 api 版本?任何想法?

标签: pythonyaml

解决方案


我认为您可以这样做,这将为您提供 yaml 文件中的版本:

import yaml

spec_yaml= 'apispec.yaml'
with open(spec_yaml, 'r') as f:
    data = yaml.load(f)

print(data['info']['version'])

推荐阅读