use*_*834 8 ruby swagger apiclient openapi bravado
我使用Bravado为 petstore 创建 REST API 的 Python 客户端。
我需要执行相同的操作来获取 REST API 的动态 Ruby 客户端。
我在操作系统集成 Swagger 页面中看到了一系列工具,但其中大多数似乎是使用 Swagger 进行自动化测试或创建 Swagger/openapi API,而不是创建使用 Swagger API 的客户端。
Svelte是上面列表中的“来自 Swagger JSON 规范的动态 Ruby API 客户端”。它可能是一个很好的候选者,看起来与我已经使用的Bravado Python 库类似,但是:
下面是 Python 代码,这正是我们在 Ruby 中寻找的功能:
要获得简单的字典答案(不使用模型):
from bravado.client import SwaggerClient
from bravado.fido_client import FidoClient
client = SwaggerClient.from_url(
'http://petstore.swagger.io/v2/swagger.json',
config={'use_models': False}
)
result = client.pet.getPetById(petId=42).result(timeout=4)
Run Code Online (Sandbox Code Playgroud)
提供:
>>> result
{'category': {'id': 42, 'name': 'string'},
'id': 42,
'name': 'doggie',
'photoUrls': ['string', 'string2'],
'status': 'available',
'tags': [{'id': 42, 'name': 'string'}]}
Run Code Online (Sandbox Code Playgroud)
更好的是,默认使用该模型:
> from bravado.client import SwaggerClient
> client = SwaggerClient.from_url("http://petstore.swagger.io/v2/swagger.json")
> pet = client.pet.getPetById(petId=42).result()
> print(pet)
Pet(category=Category(id=42, name='string'), id=42,
name='doggie', photoUrls=['string', 'string2'],
status='available',
tags=[Tag(id=42, name='string')])
>
Run Code Online (Sandbox Code Playgroud)
将其包含在您的 Gemfile 中:
gem 'excon'
Run Code Online (Sandbox Code Playgroud)
然后,进行 GET 请求,例如:
require 'json'
require 'excon'
excon_result = Excon.get('http://petstore.swagger.io/v2/pet/findByStatus?status=pending')
response_body_as_string = excon_result.body
pets = JSON.parse(response_body_as_string)
pets.first['name'] # "hello kity with form updated" (sic)
Run Code Online (Sandbox Code Playgroud)
Excon 有许多简洁的功能,例如expects允许您指定所需的 http 状态代码列表的选项。如果响应超出预期,它将自动提高。
| 归档时间: |
|
| 查看次数: |
2719 次 |
| 最近记录: |