Helper for creating dynamic Ruby OpenAPI / Swagger client in REST API
I used Bravado to create a Python client for REST APIs for petstore .
I need to do the same to get a dynamic Ruby client in REST API.
-
I saw a list of tools in the Swagger OS Integration section , but most of them seem to automate tests using Swagger, or create Swagger / openapi APIs rather than create a client that uses Swagger APIs.
-
Svelte , is the Swagger JSON Spec "Dynamic Ruby API Client" in the above list. It might be a good candidate and is similar to the Bravado Python lib I'm already using, but:
- It seems that query parameter validation is only done for URL-based parameters, so it won't provide requests and response validation against the Swagger 2.0 Spec, for example.
- Svelte returns a Faraday :: Request object, not a model instance.
- The Ruby gem OpenAPI is officially a Ruby wrapper and this is what we are looking for, but there is no Cf documentation yet. main README: "The Active Dev documentation goes"
- Excon (thanks @ kevin-burnett for pointing this out) does not provide the automatic API wrapper described by Swagger, it is an HTTP client conforming to Python Requests , so the lib is for manual API use.
Here's the Python code that is the function we're looking for in Ruby:
To get a simple dict answer (no using models):
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)
provide:
>>> result
{'category': {'id': 42, 'name': 'string'},
'id': 42,
'name': 'doggie',
'photoUrls': ['string', 'string2'],
'status': 'available',
'tags': [{'id': 42, 'name': 'string'}]}
And even better, by default using a model:
> 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')])
>
source to share
There are many others , but excon is pretty sweet.
Include it in your Gemfile:
gem 'excon'
Then, to make a GET request like:
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)
Excon has a lot of neat features, such as an option expects
that lets you specify a list of http status codes that you expect. If the answer is not as expected, it is automatically raised.
source to share
You can use ruby-swagger to convert swagger.json client to API
You can watch this command:
rake swagger:generate_client:ruby
Also you can have a look at swagger-codegen
source to share