Merge pull request #1172 from xhh/ruby-apiclient

[Ruby] Implement API client structure for Ruby client
This commit is contained in:
wing328 2015-09-07 21:56:59 +08:00
commit 12190e0900
39 changed files with 1505 additions and 1707 deletions

View File

@ -107,17 +107,14 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
setModelPackage("models");
setApiPackage("api");
supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec"));
supportingFiles.add(new SupportingFile("swagger_client.mustache", libFolder, gemName + ".rb"));
String baseFolder = libFolder + File.separator + gemName;
supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb"));
String swaggerFolder = baseFolder + File.separator + "swagger";
supportingFiles.add(new SupportingFile("swagger" + File.separator + "request.mustache", swaggerFolder, "request.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "response.mustache", swaggerFolder, "response.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "api_error.mustache", swaggerFolder, "api_error.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "version.mustache", swaggerFolder, "version.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "configuration.mustache", swaggerFolder, "configuration.rb"));
String modelFolder = baseFolder + File.separator + modelPackage.replace("/", File.separator);
supportingFiles.add(new SupportingFile("gemspec.mustache", "", gemName + ".gemspec"));
supportingFiles.add(new SupportingFile("gem.mustache", libFolder, gemName + ".rb"));
String gemFolder = libFolder + File.separator + gemName;
supportingFiles.add(new SupportingFile("api_client.mustache", gemFolder, "api_client.rb"));
supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb"));
supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, "configuration.rb"));
supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb"));
String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator);
supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb"));
}

View File

@ -3,6 +3,11 @@ require "uri"
module {{moduleName}}
{{#operations}}
class {{classname}}
attr_accessor :api_client
def initialize(api_client = nil)
@api_client = api_client || Configuration.api_client
end
{{#operation}}
{{newline}}
# {{summary}}
@ -11,9 +16,9 @@ module {{moduleName}}
{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters
{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}}
{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}]
def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: {{classname}}#{{nickname}} ..."
def {{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: {{classname}}#{{nickname}} ..."
end
{{#allParams}}{{#required}}
# verify the required parameter '{{paramName}}' is set
@ -39,11 +44,11 @@ module {{moduleName}}
# HTTP header 'Accept' (if needed)
_header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}}
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type){{#headerParams}}{{#required}}
header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}}
header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}}
@ -54,22 +59,36 @@ module {{moduleName}}
# http body (model)
{{^bodyParam}}post_body = nil
{{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}})
{{/bodyParam}}{{#bodyParam}}post_body = @api_client.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}})
{{/bodyParam}}
auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]
{{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('{{{returnType}}}')
if Swagger.configuration.debug
Swagger.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}"
{{#returnType}}result = @api_client.call_api(:{{httpMethod}}, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => '{{{returnType}}}')
if Configuration.debugging
Configuration.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}"
end
result{{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: {{classname}}#{{nickname}}"
return result{{/returnType}}{{^returnType}}@api_client.call_api(:{{httpMethod}}, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: {{classname}}#{{nickname}}"
end
nil{{/returnType}}
return nil{{/returnType}}
end
{{/operation}}
end
{{/operations}}
end

View File

@ -0,0 +1,270 @@
require 'date'
require 'json'
require 'logger'
require 'tempfile'
require 'typhoeus'
require 'uri'
module {{moduleName}}
class ApiClient
attr_accessor :host
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Stores the HTTP response from the last API call using this API client.
attr_accessor :last_response
def initialize(host = nil)
@host = host || Configuration.base_url
@format = 'json'
@user_agent = "ruby-swagger-#{VERSION}"
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
end
def call_api(http_method, path, opts = {})
request = build_request(http_method, path, opts)
response = request.run
# record as last response
@last_response = response
if Configuration.debugging
Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
end
unless response.success?
fail ApiError.new(:code => response.code,
:response_headers => response.headers,
:response_body => response.body),
response.status_message
end
if opts[:return_type]
deserialize(response, opts[:return_type])
else
nil
end
end
def build_request(http_method, path, opts = {})
url = build_request_url(path)
http_method = http_method.to_sym.downcase
header_params = @default_headers.merge(opts[:header_params] || {})
query_params = opts[:query_params] || {}
form_params = opts[:form_params] || {}
{{#hasAuthMethods}}
update_params_for_auth! header_params, query_params, opts[:auth_names]
{{/hasAuthMethods}}
req_opts = {
:method => http_method,
:headers => header_params,
:params => query_params,
:ssl_verifypeer => Configuration.verify_ssl,
:cainfo => Configuration.ssl_ca_cert,
:verbose => Configuration.debugging
}
if [:post, :patch, :put, :delete].include?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update :body => req_body
if Configuration.debugging
Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
end
end
Typhoeus::Request.new(url, req_opts)
end
# Deserialize the response to the given return type.
#
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(response, return_type)
body = response.body
return nil if body.nil? || body.empty?
# handle file downloading - save response body into a tmp file and return the File instance
return download_file(response) if return_type == 'File'
# ensuring a default content type
content_type = response.headers['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}"
end
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object, return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet
{{moduleName}}.const_get(return_type).new.tap do |model|
model.build_from_hash data
end
end
end
# Save response body into a file in (the defined) temporary folder, using the filename
# from the "Content-Disposition" header if provided, otherwise a random filename.
#
# @see Configuration#temp_folder_path
# @return [File] the file downloaded
def download_file(response)
tmp_file = Tempfile.new '', @temp_folder_path
content_disposition = response.headers['Content-Disposition']
if content_disposition
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
path = File.join File.dirname(tmp_file), filename
else
path = tmp_file.path
end
# close and delete temp file
tmp_file.close!
File.open(path, 'w') { |file| file.write(response.body) }
logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards"
File.new(path)
end
def build_request_url(path)
# Add leading and trailing slashes to path
path = "/#{path}".gsub(/\/+/, '/')
URI.encode(host + path)
end
def build_request_body(header_params, form_params, body)
# http form
if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
header_params['Content-Type'] == 'multipart/form-data'
data = form_params.dup
data.each do |key, value|
data[key] = value.to_s if value && !value.is_a?(File)
end
elsif body
data = body.is_a?(String) ? body : body.to_json
else
data = nil
end
data
end
# Update hearder and query params based on authentication settings.
def update_params_for_auth!(header_params, query_params, auth_names)
Array(auth_names).each do |auth_name|
auth_setting = Configuration.auth_settings[auth_name]
next unless auth_setting
case auth_setting[:in]
when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
else fail ArgumentError, 'Authentication token must be in `query` of `header`'
end
end
end
def user_agent=(user_agent)
@user_agent = user_agent
@default_headers['User-Agent'] = @user_agent
end
# Return Accept header based on an array of accepts provided.
# @param [Array] accepts array for Accept
# @return [String] the Accept header (e.g. application/json)
def select_header_accept(accepts)
if accepts.empty?
return
elsif accepts.any?{ |s| s.casecmp('application/json') == 0 }
'application/json' # look for json data by default
else
accepts.join(',')
end
end
# Return Content-Type header based on an array of content types provided.
# @param [Array] content_types array for Content-Type
# @return [String] the Content-Type header (e.g. application/json)
def select_header_content_type(content_types)
if content_types.empty?
'application/json' # use application/json by default
elsif content_types.any?{ |s| s.casecmp('application/json')==0 }
'application/json' # use application/json if it's included
else
content_types[0] # otherwise, use the first one
end
end
# Convert object (array, hash, object, etc) to JSON string.
# @param [Object] model object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_http_body(model)
return if model.nil?
_body = nil
if model.is_a?(Array)
_body = model.map{|m| object_to_hash(m) }
else
_body = object_to_hash(model)
end
_body.to_json
end
# Convert object(non-array) to hash.
# @param [Object] obj object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_hash(obj)
if obj.respond_to?(:to_hash)
obj.to_hash
else
obj
end
end
end
end

View File

@ -0,0 +1,24 @@
module {{moduleName}}
class ApiError < StandardError
attr_reader :code, :response_headers, :response_body
# Usage examples:
# ApiError.new
# ApiError.new("message")
# ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
# ApiError.new(:code => 404, :message => "Not Found")
def initialize(arg = nil)
if arg.is_a? Hash
arg.each do |k, v|
if k.to_s == 'message'
super v
else
instance_variable_set "@#{k}", v
end
end
else
super arg
end
end
end
end

View File

@ -0,0 +1,177 @@
require 'uri'
require 'singleton'
module {{moduleName}}
class Configuration
include Singleton
# Default api client
attr_accessor :api_client
# Defines url scheme
attr_accessor :scheme
# Defines url host
attr_accessor :host
# Defines url base path
attr_accessor :base_path
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debugging
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
#
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
attr_accessor :ssl_ca_cert
attr_accessor :inject_format
attr_accessor :force_ending_format
class << self
def method_missing(method_name, *args, &block)
config = Configuration.instance
if config.respond_to?(method_name)
config.send(method_name, *args, &block)
else
super
end
end
end
def initialize
@scheme = '{{scheme}}'
@host = '{{host}}'
@base_path = '{{contextPath}}'
@api_key = {}
@api_key_prefix = {}
@verify_ssl = true
@debugging = false
@inject_format = false
@force_ending_format = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
end
def api_client
@api_client ||= ApiClient.new
end
def scheme=(scheme)
# remove :// from scheme
@scheme = scheme.sub(/:\/\//, '')
end
def host=(host)
# remove http(s):// and anything after a slash
@host = host.sub(/https?:\/\//, '').split('/').first
end
def base_path=(base_path)
# Add leading and trailing slashes to base_path
@base_path = "/#{base_path}".gsub(/\/+/, '/')
@base_path = "" if @base_path == "/"
end
def base_url
url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}"
URI.encode(url)
end
# Gets API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth
def api_key_with_prefix(param_name)
if @api_key_prefix[param_name]
"#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
else
@api_key[param_name]
end
end
# Gets Basic Auth token string
def basic_auth_token
'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
end
# Returns Auth Settings hash for api client.
def auth_settings
{
{{#authMethods}}
{{#isApiKey}}
'{{name}}' =>
{
type: 'api_key',
in: {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}},
key: '{{keyParamName}}',
value: api_key_with_prefix('{{keyParamName}}')
},
{{/isApiKey}}
{{#isBasic}}
'{{name}}' =>
{
type: 'basic',
in: 'header',
key: 'Authorization',
value: basic_auth_token
},
{{/isBasic}}
{{/authMethods}}
}
end
end
end

View File

@ -0,0 +1,36 @@
# Common files
require '{{gemName}}/api_client'
require '{{gemName}}/api_error'
require '{{gemName}}/version'
require '{{gemName}}/configuration'
# Models
require '{{gemName}}/{{modelPackage}}/base_object'
{{#models}}
require '{{importPath}}'
{{/models}}
# APIs
{{#apiInfo}}
{{#apis}}
require '{{importPath}}'
{{/apis}}
{{/apiInfo}}
module {{moduleName}}
class << self
# Configure sdk using block.
# {{moduleName}}.configure do |config|
# config.username = "xxx"
# config.password = "xxx"
# end
# If no block given, return the configuration singleton instance.
def configure
if block_given?
yield Configuration.instance
else
Configuration.instance
end
end
end
end

View File

@ -1,10 +1,10 @@
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "{{gemName}}/swagger/version"
require "{{gemName}}/version"
Gem::Specification.new do |s|
s.name = "{{gemName}}"
s.version = {{moduleName}}::Swagger::VERSION
s.version = {{moduleName}}::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Zeke Sikelianos", "Tony Tam"]
s.email = ["zeke@wordnik.com", "fehguy@gmail.com"]

View File

@ -1,76 +0,0 @@
module {{moduleName}}
module Swagger
class << self
attr_accessor :logger
# A Swagger configuration object. Must act like a hash and return sensible
# values for all Swagger configuration options. See Swagger::Configuration.
attr_accessor :configuration
attr_accessor :resources
# Call this method to modify defaults in your initializers.
#
# @example
# Swagger.configure do |config|
# config.api_key['api_key'] = '1234567890abcdef' # api key authentication
# config.username = 'wordlover' # http basic authentication
# config.password = 'i<3words' # http basic authentication
# config.format = 'json' # optional, defaults to 'json'
# end
#
def configure
yield(configuration) if block_given?
self.logger = configuration.logger
# remove :// from scheme
configuration.scheme.sub!(/:\/\//, '')
# remove http(s):// and anything after a slash
configuration.host.sub!(/https?:\/\//, '')
configuration.host = configuration.host.split('/').first
# Add leading and trailing slashes to base_path
configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/')
configuration.base_path = "" if configuration.base_path == "/"
end
def authenticated?
!Swagger.configuration.auth_token.nil?
end
def de_authenticate
Swagger.configuration.auth_token = nil
end
def authenticate
return if Swagger.authenticated?
if Swagger.configuration.username.nil? || Swagger.configuration.password.nil?
raise ApiError, "Username and password are required to authenticate."
end
request = Swagger::Request.new(
:get,
"account/authenticate/{username}",
:params => {
:username => Swagger.configuration.username,
:password => Swagger.configuration.password
}
)
response_body = request.response.body
Swagger.configuration.auth_token = response_body['token']
end
def last_response
Thread.current[:swagger_last_response]
end
def last_response=(response)
Thread.current[:swagger_last_response] = response
end
end
end
end

View File

@ -1,26 +0,0 @@
module {{moduleName}}
module Swagger
class ApiError < StandardError
attr_reader :code, :response_headers, :response_body
# Usage examples:
# ApiError.new
# ApiError.new("message")
# ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
# ApiError.new(:code => 404, :message => "Not Found")
def initialize(arg = nil)
if arg.is_a? Hash
arg.each do |k, v|
if k.to_s == 'message'
super v
else
instance_variable_set "@#{k}", v
end
end
else
super arg
end
end
end
end
end

View File

@ -1,101 +0,0 @@
require 'logger'
module {{moduleName}}
module Swagger
class Configuration
attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
#
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
attr_accessor :ssl_ca_cert
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debug
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Defaults go in here..
def initialize
@format = 'json'
@scheme = '{{scheme}}'
@host = '{{host}}'
@base_path = '{{contextPath}}'
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = false
@force_ending_format = false
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
# keys for API key authentication (param-name => api-key)
@api_key = {}
@api_key_prefix = {}
@verify_ssl = true
@debug = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
end
end
end
end

View File

@ -1,214 +0,0 @@
require 'uri'
require 'typhoeus'
module {{moduleName}}
module Swagger
class Request
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response
# All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes = {})
@http_method = http_method.to_sym.downcase
@path = path
attributes.each { |name, value| send "#{name}=", value }
@format ||= Swagger.configuration.format
@params ||= {}
# Apply default headers
@headers = Swagger.configuration.default_headers.merge(@headers || {})
# Stick in the auth token if there is one
if Swagger.authenticated?
@headers.merge!({:auth_token => Swagger.configuration.auth_token})
end
{{#hasAuthMethods}}
update_params_for_auth!
{{/hasAuthMethods}}
end
{{#hasAuthMethods}}
# Update hearder and query params based on authentication settings.
def update_params_for_auth!
(@auth_names || []).each do |auth_name|
case auth_name
{{#authMethods}}when '{{name}}'
{{#isApiKey}}{{#isKeyInHeader}}@headers ||= {}
@headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {}
@params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {}
http_auth_header = 'Basic ' + ["#{Swagger.configuration.username}:#{Swagger.configuration.password}"].pack('m').delete("\r\n")
@headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}}
{{/authMethods}}
end
end
end
{{/hasAuthMethods}}
# Get API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth
def get_api_key_with_prefix(param_name)
if Swagger.configuration.api_key_prefix[param_name]
"#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}"
else
Swagger.configuration.api_key[param_name]
end
end
# Construct the request URL.
def url(options = {})
_path = self.interpreted_path
_path = "/#{_path}" unless _path.start_with?('/')
"#{Swagger.configuration.scheme}://#{Swagger.configuration.host}#{_path}"
end
# Iterate over the params hash, injecting any path values into the path string
# e.g. /word.{format}/{word}/entries => /word.json/cat/entries
def interpreted_path
p = self.path.dup
# Stick a .{format} placeholder into the path if there isn't
# one already or an actual format like json or xml
# e.g. /words/blah => /words.{format}/blah
if Swagger.configuration.inject_format
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
p = p.sub(/^(\/?\w+)/, "\\1.#{format}")
end
end
# Stick a .{format} placeholder on the end of the path if there isn't
# one already or an actual format like json or xml
# e.g. /words/blah => /words/blah.{format}
if Swagger.configuration.force_ending_format
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
p = "#{p}.#{format}"
end
end
p = p.sub("{format}", self.format.to_s)
URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
end
# If body is an object, JSONify it before making the actual request.
# For form parameters, remove empty value
def outgoing_body
# http form
if headers['Content-Type'] == 'application/x-www-form-urlencoded'
data = form_params.dup
data.each do |key, value|
data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter
end
elsif @body # http body is JSON
data = @body.is_a?(String) ? @body : @body.to_json
else
data = nil
end
if Swagger.configuration.debug
Swagger.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n"
end
data
end
def make
request_options = {
:method => self.http_method,
:headers => self.headers,
:params => self.params,
:ssl_verifypeer => Swagger.configuration.verify_ssl,
:cainfo => Swagger.configuration.ssl_ca_cert,
:verbose => Swagger.configuration.debug
}
if [:post, :patch, :put, :delete].include?(self.http_method)
request_options.update :body => self.outgoing_body
end
raw = Typhoeus::Request.new(self.url, request_options).run
@response = Response.new(raw)
if Swagger.configuration.debug
Swagger.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n"
end
# record as last response
Swagger.last_response = @response
unless @response.success?
fail ApiError.new(:code => @response.code,
:response_headers => @response.headers,
:response_body => @response.body),
@response.status_message
end
@response
end
def response_code_pretty
return unless @response
@response.code.to_s
end
def response_headers_pretty
return unless @response
# JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end
# return 'Accept' based on an array of accept provided
# @param [Array] header_accept_array Array fo 'Accept'
# @return String Accept (e.g. application/json)
def self.select_header_accept header_accept_array
if header_accept_array.empty?
return
elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 }
'application/json' # look for json data by default
else
header_accept_array.join(',')
end
end
# return the content type based on an array of content-type provided
# @param [Array] content_type_array Array fo content-type
# @return String Content-Type (e.g. application/json)
def self.select_header_content_type content_type_array
if content_type_array.empty?
'application/json' # use application/json by default
elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 }
'application/json' # use application/json if it's included
else
content_type_array[0]; # otherwise, use the first one
end
end
# static method to convert object (array, hash, object, etc) to JSON string
# @param model object to be converted into JSON string
# @return string JSON string representation of the object
def self.object_to_http_body model
return if model.nil?
_body = nil
if model.is_a?(Array)
_body = model.map{|m| object_to_hash(m) }
else
_body = object_to_hash(model)
end
_body.to_json
end
# static method to convert object(non-array) to hash
# @param obj object to be converted into JSON string
# @return string JSON string representation of the object
def self.object_to_hash obj
if obj.respond_to?(:to_hash)
obj.to_hash
else
obj
end
end
end
end
end

View File

@ -1,156 +0,0 @@
module {{moduleName}}
module Swagger
class Response
require 'json'
require 'date'
require 'tempfile'
attr_accessor :raw
def initialize(raw)
self.raw = raw
end
def code
raw.code
end
def status_message
raw.status_message
end
def body
raw.body
end
def success?
raw.success?
end
# Deserialize the raw response body to the given return type.
#
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(return_type)
return nil if body.nil? || body.empty?
# handle file downloading - save response body into a tmp file and return the File instance
return download_file if return_type == 'File'
# ensuring a default content type
content_type = raw.headers['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}"
end
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object, return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet
{{moduleName}}.const_get(return_type).new.tap do |model|
model.build_from_hash data
end
end
end
# Save response body into a file in (the defined) temporary folder, using the filename
# from the "Content-Disposition" header if provided, otherwise a random filename.
#
# @see Configuration#temp_folder_path
# @return [File] the file downloaded
def download_file
tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path
content_disposition = raw.headers['Content-Disposition']
if content_disposition
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
path = File.join File.dirname(tmp_file), filename
else
path = tmp_file.path
end
# close and delete temp file
tmp_file.close!
File.open(path, 'w') { |file| file.write(raw.body) }
Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards"
return File.new(path)
end
# `headers_hash` is a Typhoeus-specific extension of Hash,
# so simplify it back into a regular old Hash.
def headers
h = {}
raw.headers_hash.each {|k,v| h[k] = v }
h
end
# Extract the response format from the header hash
# e.g. {'Content-Type' => 'application/json'}
def format
headers['Content-Type'].split("/").last.downcase
end
def json?
format == 'json'
end
def xml?
format == 'xml'
end
def pretty_body
return unless body
if format == 'json'
JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
else
body
end
end
def pretty_headers
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end
end
end
end

View File

@ -1,5 +0,0 @@
module {{moduleName}}
module Swagger
VERSION = "{{gemVersion}}"
end
end

View File

@ -1,26 +0,0 @@
# Swagger common files
require '{{gemName}}/swagger'
require '{{gemName}}/swagger/configuration'
require '{{gemName}}/swagger/api_error'
require '{{gemName}}/swagger/request'
require '{{gemName}}/swagger/response'
require '{{gemName}}/swagger/version'
# Models
require '{{gemName}}/{{modelPackage}}/base_object'
{{#models}}
require '{{importPath}}'
{{/models}}
# APIs
{{#apiInfo}}
{{#apis}}
require '{{importPath}}'
{{/apis}}
{{/apiInfo}}
module {{moduleName}}
# Initialize the default configuration
Swagger.configuration = Swagger::Configuration.new
Swagger.configure { |config| }
end

View File

@ -0,0 +1,3 @@
module {{moduleName}}
VERSION = "{{gemVersion}}"
end

View File

@ -37,23 +37,20 @@ You can also use the client directly like this:
ruby -Ilib script.rb
```
## Configuration
## Getting Started
```ruby
require 'petstore'
Petstore::Swagger.configure do |config|
Petstore.configure do |config|
config.api_key['api_key'] = 'special-key'
config.host = 'petstore.swagger.io'
config.base_path = '/v2'
# enable debugging (default is false)
config.debug = true
# enable debugging (default is disabled)
config.debugging = true
end
```
## Getting Started
```ruby
pet = Petstore::PetApi.get_pet_by_id(5)
pet_api = Petstore::PetApi.new
pet = pet_api.get_pet_by_id(5)
puts pet.to_body
```

View File

@ -0,0 +1 @@
Hello world!

View File

@ -1,10 +1,8 @@
# Swagger common files
require 'petstore/swagger'
require 'petstore/swagger/configuration'
require 'petstore/swagger/api_error'
require 'petstore/swagger/request'
require 'petstore/swagger/response'
require 'petstore/swagger/version'
# Common files
require 'petstore/api_client'
require 'petstore/api_error'
require 'petstore/version'
require 'petstore/configuration'
# Models
require 'petstore/models/base_object'
@ -16,11 +14,23 @@ require 'petstore/models/order'
# APIs
require 'petstore/api/user_api'
require 'petstore/api/pet_api'
require 'petstore/api/store_api'
require 'petstore/api/pet_api'
module Petstore
# Initialize the default configuration
Swagger.configuration = Swagger::Configuration.new
Swagger.configure { |config| }
class << self
# Configure sdk using block.
# Petstore.configure do |config|
# config.username = "xxx"
# config.password = "xxx"
# end
# If no block given, return the configuration singleton instance.
def configure
if block_given?
yield Configuration.instance
else
Configuration.instance
end
end
end
end

View File

@ -2,15 +2,20 @@ require "uri"
module Petstore
class PetApi
attr_accessor :api_client
def initialize(api_client = nil)
@api_client = api_client || Configuration.api_client
end
# Update an existing pet
#
# @param [Hash] opts the optional parameters
# @option opts [Pet] :body Pet object that needs to be added to the store
# @return [nil]
def self.update_pet(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#update_pet ..."
def update_pet(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: PetApi#update_pet ..."
end
# resource path
@ -24,25 +29,30 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = ['application/json', 'application/xml']
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
post_body = @api_client.object_to_http_body(opts[:'body'])
auth_names = ['petstore_auth']
Swagger::Request.new(:PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#update_pet"
@api_client.call_api(:PUT, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: PetApi#update_pet"
end
nil
return nil
end
# Add a new pet to the store
@ -50,9 +60,9 @@ module Petstore
# @param [Hash] opts the optional parameters
# @option opts [Pet] :body Pet object that needs to be added to the store
# @return [nil]
def self.add_pet(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#add_pet ..."
def add_pet(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: PetApi#add_pet ..."
end
# resource path
@ -66,25 +76,30 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = ['application/json', 'application/xml']
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
post_body = @api_client.object_to_http_body(opts[:'body'])
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#add_pet"
@api_client.call_api(:POST, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: PetApi#add_pet"
end
nil
return nil
end
# Finds Pets by status
@ -92,9 +107,9 @@ module Petstore
# @param [Hash] opts the optional parameters
# @option opts [Array<String>] :status Status values that need to be considered for filter
# @return [Array<Pet>]
def self.find_pets_by_status(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#find_pets_by_status ..."
def find_pets_by_status(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: PetApi#find_pets_by_status ..."
end
# resource path
@ -109,11 +124,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -123,12 +138,17 @@ module Petstore
auth_names = ['petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('Array<Pet>')
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}"
result = @api_client.call_api(:GET, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Array<Pet>')
if Configuration.debugging
Configuration.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}"
end
result
return result
end
# Finds Pets by tags
@ -136,9 +156,9 @@ module Petstore
# @param [Hash] opts the optional parameters
# @option opts [Array<String>] :tags Tags to filter by
# @return [Array<Pet>]
def self.find_pets_by_tags(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#find_pets_by_tags ..."
def find_pets_by_tags(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: PetApi#find_pets_by_tags ..."
end
# resource path
@ -153,11 +173,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -167,12 +187,17 @@ module Petstore
auth_names = ['petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('Array<Pet>')
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}"
result = @api_client.call_api(:GET, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Array<Pet>')
if Configuration.debugging
Configuration.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}"
end
result
return result
end
# Find pet by ID
@ -180,9 +205,9 @@ module Petstore
# @param pet_id ID of pet that needs to be fetched
# @param [Hash] opts the optional parameters
# @return [Pet]
def self.get_pet_by_id(pet_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#get_pet_by_id ..."
def get_pet_by_id(pet_id, opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: PetApi#get_pet_by_id ..."
end
# verify the required parameter 'pet_id' is set
@ -199,11 +224,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -212,13 +237,18 @@ module Petstore
post_body = nil
auth_names = ['api_key', 'petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('Pet')
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}"
auth_names = ['petstore_auth', 'api_key']
result = @api_client.call_api(:GET, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Pet')
if Configuration.debugging
Configuration.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}"
end
result
return result
end
# Updates a pet in the store with form data
@ -228,9 +258,9 @@ module Petstore
# @option opts [String] :name Updated name of the pet
# @option opts [String] :status Updated status of the pet
# @return [nil]
def self.update_pet_with_form(pet_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#update_pet_with_form ..."
def update_pet_with_form(pet_id, opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: PetApi#update_pet_with_form ..."
end
# verify the required parameter 'pet_id' is set
@ -247,11 +277,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = ['application/x-www-form-urlencoded']
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -263,11 +293,16 @@ module Petstore
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#update_pet_with_form"
@api_client.call_api(:POST, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: PetApi#update_pet_with_form"
end
nil
return nil
end
# Deletes a pet
@ -276,9 +311,9 @@ module Petstore
# @param [Hash] opts the optional parameters
# @option opts [String] :api_key
# @return [nil]
def self.delete_pet(pet_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#delete_pet ..."
def delete_pet(pet_id, opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: PetApi#delete_pet ..."
end
# verify the required parameter 'pet_id' is set
@ -295,11 +330,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key']
# form parameters
@ -310,11 +345,16 @@ module Petstore
auth_names = ['petstore_auth']
Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#delete_pet"
@api_client.call_api(:DELETE, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: PetApi#delete_pet"
end
nil
return nil
end
# uploads an image
@ -324,9 +364,9 @@ module Petstore
# @option opts [String] :additional_metadata Additional data to pass to server
# @option opts [File] :file file to upload
# @return [nil]
def self.upload_file(pet_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#upload_file ..."
def upload_file(pet_id, opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: PetApi#upload_file ..."
end
# verify the required parameter 'pet_id' is set
@ -343,11 +383,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = ['multipart/form-data']
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -359,11 +399,20 @@ module Petstore
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#upload_file"
@api_client.call_api(:POST, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: PetApi#upload_file"
end
nil
return nil
end
end
end

View File

@ -2,14 +2,19 @@ require "uri"
module Petstore
class StoreApi
attr_accessor :api_client
def initialize(api_client = nil)
@api_client = api_client || Configuration.api_client
end
# Returns pet inventories by status
# Returns a map of status codes to quantities
# @param [Hash] opts the optional parameters
# @return [Hash<String, Integer>]
def self.get_inventory(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: StoreApi#get_inventory ..."
def get_inventory(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: StoreApi#get_inventory ..."
end
# resource path
@ -23,11 +28,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -37,12 +42,17 @@ module Petstore
auth_names = ['api_key']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('Hash<String, Integer>')
if Swagger.configuration.debug
Swagger.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}"
result = @api_client.call_api(:GET, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Hash<String, Integer>')
if Configuration.debugging
Configuration.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}"
end
result
return result
end
# Place an order for a pet
@ -50,9 +60,9 @@ module Petstore
# @param [Hash] opts the optional parameters
# @option opts [Order] :body order placed for purchasing the pet
# @return [Order]
def self.place_order(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: StoreApi#place_order ..."
def place_order(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: StoreApi#place_order ..."
end
# resource path
@ -66,26 +76,31 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
post_body = @api_client.object_to_http_body(opts[:'body'])
auth_names = []
response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('Order')
if Swagger.configuration.debug
Swagger.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}"
result = @api_client.call_api(:POST, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Order')
if Configuration.debugging
Configuration.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}"
end
result
return result
end
# Find purchase order by ID
@ -93,9 +108,9 @@ module Petstore
# @param order_id ID of pet that needs to be fetched
# @param [Hash] opts the optional parameters
# @return [Order]
def self.get_order_by_id(order_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: StoreApi#get_order_by_id ..."
def get_order_by_id(order_id, opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: StoreApi#get_order_by_id ..."
end
# verify the required parameter 'order_id' is set
@ -112,11 +127,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -126,12 +141,17 @@ module Petstore
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('Order')
if Swagger.configuration.debug
Swagger.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}"
result = @api_client.call_api(:GET, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'Order')
if Configuration.debugging
Configuration.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}"
end
result
return result
end
# Delete purchase order by ID
@ -139,9 +159,9 @@ module Petstore
# @param order_id ID of the order that needs to be deleted
# @param [Hash] opts the optional parameters
# @return [nil]
def self.delete_order(order_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: StoreApi#delete_order ..."
def delete_order(order_id, opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: StoreApi#delete_order ..."
end
# verify the required parameter 'order_id' is set
@ -158,11 +178,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -172,11 +192,20 @@ module Petstore
auth_names = []
Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: StoreApi#delete_order"
@api_client.call_api(:DELETE, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: StoreApi#delete_order"
end
nil
return nil
end
end
end

View File

@ -2,15 +2,20 @@ require "uri"
module Petstore
class UserApi
attr_accessor :api_client
def initialize(api_client = nil)
@api_client = api_client || Configuration.api_client
end
# Create user
# This can only be done by the logged in user.
# @param [Hash] opts the optional parameters
# @option opts [User] :body Created user object
# @return [nil]
def self.create_user(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#create_user ..."
def create_user(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: UserApi#create_user ..."
end
# resource path
@ -24,25 +29,30 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
post_body = @api_client.object_to_http_body(opts[:'body'])
auth_names = []
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#create_user"
@api_client.call_api(:POST, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: UserApi#create_user"
end
nil
return nil
end
# Creates list of users with given input array
@ -50,9 +60,9 @@ module Petstore
# @param [Hash] opts the optional parameters
# @option opts [Array<User>] :body List of user object
# @return [nil]
def self.create_users_with_array_input(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#create_users_with_array_input ..."
def create_users_with_array_input(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: UserApi#create_users_with_array_input ..."
end
# resource path
@ -66,25 +76,30 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
post_body = @api_client.object_to_http_body(opts[:'body'])
auth_names = []
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#create_users_with_array_input"
@api_client.call_api(:POST, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: UserApi#create_users_with_array_input"
end
nil
return nil
end
# Creates list of users with given input array
@ -92,9 +107,9 @@ module Petstore
# @param [Hash] opts the optional parameters
# @option opts [Array<User>] :body List of user object
# @return [nil]
def self.create_users_with_list_input(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#create_users_with_list_input ..."
def create_users_with_list_input(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: UserApi#create_users_with_list_input ..."
end
# resource path
@ -108,25 +123,30 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
post_body = @api_client.object_to_http_body(opts[:'body'])
auth_names = []
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#create_users_with_list_input"
@api_client.call_api(:POST, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: UserApi#create_users_with_list_input"
end
nil
return nil
end
# Logs user into the system
@ -135,9 +155,9 @@ module Petstore
# @option opts [String] :username The user name for login
# @option opts [String] :password The password for login in clear text
# @return [String]
def self.login_user(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#login_user ..."
def login_user(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: UserApi#login_user ..."
end
# resource path
@ -153,11 +173,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -167,21 +187,26 @@ module Petstore
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('String')
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}"
result = @api_client.call_api(:GET, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'String')
if Configuration.debugging
Configuration.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}"
end
result
return result
end
# Logs out current logged in user session
#
# @param [Hash] opts the optional parameters
# @return [nil]
def self.logout_user(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#logout_user ..."
def logout_user(opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: UserApi#logout_user ..."
end
# resource path
@ -195,11 +220,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -209,11 +234,16 @@ module Petstore
auth_names = []
Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#logout_user"
@api_client.call_api(:GET, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: UserApi#logout_user"
end
nil
return nil
end
# Get user by user name
@ -221,9 +251,9 @@ module Petstore
# @param username The name that needs to be fetched. Use user1 for testing.
# @param [Hash] opts the optional parameters
# @return [User]
def self.get_user_by_name(username, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#get_user_by_name ..."
def get_user_by_name(username, opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: UserApi#get_user_by_name ..."
end
# verify the required parameter 'username' is set
@ -240,11 +270,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -254,12 +284,17 @@ module Petstore
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('User')
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}"
result = @api_client.call_api(:GET, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'User')
if Configuration.debugging
Configuration.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}"
end
result
return result
end
# Updated user
@ -268,9 +303,9 @@ module Petstore
# @param [Hash] opts the optional parameters
# @option opts [User] :body Updated user object
# @return [nil]
def self.update_user(username, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#update_user ..."
def update_user(username, opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: UserApi#update_user ..."
end
# verify the required parameter 'username' is set
@ -287,25 +322,30 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
post_body = @api_client.object_to_http_body(opts[:'body'])
auth_names = []
Swagger::Request.new(:PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#update_user"
@api_client.call_api(:PUT, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: UserApi#update_user"
end
nil
return nil
end
# Delete user
@ -313,9 +353,9 @@ module Petstore
# @param username The name that needs to be deleted
# @param [Hash] opts the optional parameters
# @return [nil]
def self.delete_user(username, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#delete_user ..."
def delete_user(username, opts = {})
if Configuration.debugging
Configuration.logger.debug "Calling API: UserApi#delete_user ..."
end
# verify the required parameter 'username' is set
@ -332,11 +372,11 @@ module Petstore
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
_header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
@ -346,11 +386,20 @@ module Petstore
auth_names = []
Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#delete_user"
@api_client.call_api(:DELETE, path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if Configuration.debugging
Configuration.logger.debug "API called: UserApi#delete_user"
end
nil
return nil
end
end
end

View File

@ -0,0 +1,270 @@
require 'date'
require 'json'
require 'logger'
require 'tempfile'
require 'typhoeus'
require 'uri'
module Petstore
class ApiClient
attr_accessor :host
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Stores the HTTP response from the last API call using this API client.
attr_accessor :last_response
def initialize(host = nil)
@host = host || Configuration.base_url
@format = 'json'
@user_agent = "ruby-swagger-#{VERSION}"
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
end
def call_api(http_method, path, opts = {})
request = build_request(http_method, path, opts)
response = request.run
# record as last response
@last_response = response
if Configuration.debugging
Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
end
unless response.success?
fail ApiError.new(:code => response.code,
:response_headers => response.headers,
:response_body => response.body),
response.status_message
end
if opts[:return_type]
deserialize(response, opts[:return_type])
else
nil
end
end
def build_request(http_method, path, opts = {})
url = build_request_url(path)
http_method = http_method.to_sym.downcase
header_params = @default_headers.merge(opts[:header_params] || {})
query_params = opts[:query_params] || {}
form_params = opts[:form_params] || {}
update_params_for_auth! header_params, query_params, opts[:auth_names]
req_opts = {
:method => http_method,
:headers => header_params,
:params => query_params,
:ssl_verifypeer => Configuration.verify_ssl,
:cainfo => Configuration.ssl_ca_cert,
:verbose => Configuration.debugging
}
if [:post, :patch, :put, :delete].include?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
req_opts.update :body => req_body
if Configuration.debugging
Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
end
end
Typhoeus::Request.new(url, req_opts)
end
# Deserialize the response to the given return type.
#
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(response, return_type)
body = response.body
return nil if body.nil? || body.empty?
# handle file downloading - save response body into a tmp file and return the File instance
return download_file(response) if return_type == 'File'
# ensuring a default content type
content_type = response.headers['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}"
end
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object, return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet
Petstore.const_get(return_type).new.tap do |model|
model.build_from_hash data
end
end
end
# Save response body into a file in (the defined) temporary folder, using the filename
# from the "Content-Disposition" header if provided, otherwise a random filename.
#
# @see Configuration#temp_folder_path
# @return [File] the file downloaded
def download_file(response)
tmp_file = Tempfile.new '', @temp_folder_path
content_disposition = response.headers['Content-Disposition']
if content_disposition
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
path = File.join File.dirname(tmp_file), filename
else
path = tmp_file.path
end
# close and delete temp file
tmp_file.close!
File.open(path, 'w') { |file| file.write(response.body) }
logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards"
File.new(path)
end
def build_request_url(path)
# Add leading and trailing slashes to path
path = "/#{path}".gsub(/\/+/, '/')
URI.encode(host + path)
end
def build_request_body(header_params, form_params, body)
# http form
if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
header_params['Content-Type'] == 'multipart/form-data'
data = form_params.dup
data.each do |key, value|
data[key] = value.to_s if value && !value.is_a?(File)
end
elsif body
data = body.is_a?(String) ? body : body.to_json
else
data = nil
end
data
end
# Update hearder and query params based on authentication settings.
def update_params_for_auth!(header_params, query_params, auth_names)
Array(auth_names).each do |auth_name|
auth_setting = Configuration.auth_settings[auth_name]
next unless auth_setting
case auth_setting[:in]
when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
else fail ArgumentError, 'Authentication token must be in `query` of `header`'
end
end
end
def user_agent=(user_agent)
@user_agent = user_agent
@default_headers['User-Agent'] = @user_agent
end
# Return Accept header based on an array of accepts provided.
# @param [Array] accepts array for Accept
# @return [String] the Accept header (e.g. application/json)
def select_header_accept(accepts)
if accepts.empty?
return
elsif accepts.any?{ |s| s.casecmp('application/json') == 0 }
'application/json' # look for json data by default
else
accepts.join(',')
end
end
# Return Content-Type header based on an array of content types provided.
# @param [Array] content_types array for Content-Type
# @return [String] the Content-Type header (e.g. application/json)
def select_header_content_type(content_types)
if content_types.empty?
'application/json' # use application/json by default
elsif content_types.any?{ |s| s.casecmp('application/json')==0 }
'application/json' # use application/json if it's included
else
content_types[0] # otherwise, use the first one
end
end
# Convert object (array, hash, object, etc) to JSON string.
# @param [Object] model object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_http_body(model)
return if model.nil?
_body = nil
if model.is_a?(Array)
_body = model.map{|m| object_to_hash(m) }
else
_body = object_to_hash(model)
end
_body.to_json
end
# Convert object(non-array) to hash.
# @param [Object] obj object to be converted into JSON string
# @return [String] JSON string representation of the object
def object_to_hash(obj)
if obj.respond_to?(:to_hash)
obj.to_hash
else
obj
end
end
end
end

View File

@ -0,0 +1,24 @@
module Petstore
class ApiError < StandardError
attr_reader :code, :response_headers, :response_body
# Usage examples:
# ApiError.new
# ApiError.new("message")
# ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
# ApiError.new(:code => 404, :message => "Not Found")
def initialize(arg = nil)
if arg.is_a? Hash
arg.each do |k, v|
if k.to_s == 'message'
super v
else
instance_variable_set "@#{k}", v
end
end
else
super arg
end
end
end
end

View File

@ -0,0 +1,164 @@
require 'uri'
require 'singleton'
module Petstore
class Configuration
include Singleton
# Default api client
attr_accessor :api_client
# Defines url scheme
attr_accessor :scheme
# Defines url host
attr_accessor :host
# Defines url base path
attr_accessor :base_path
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debugging
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
#
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
attr_accessor :ssl_ca_cert
attr_accessor :inject_format
attr_accessor :force_ending_format
class << self
def method_missing(method_name, *args, &block)
config = Configuration.instance
if config.respond_to?(method_name)
config.send(method_name, *args, &block)
else
super
end
end
end
def initialize
@scheme = 'http'
@host = 'petstore.swagger.io'
@base_path = '/v2'
@api_key = {}
@api_key_prefix = {}
@verify_ssl = true
@debugging = false
@inject_format = false
@force_ending_format = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
end
def api_client
@api_client ||= ApiClient.new
end
def scheme=(scheme)
# remove :// from scheme
@scheme = scheme.sub(/:\/\//, '')
end
def host=(host)
# remove http(s):// and anything after a slash
@host = host.sub(/https?:\/\//, '').split('/').first
end
def base_path=(base_path)
# Add leading and trailing slashes to base_path
@base_path = "/#{base_path}".gsub(/\/+/, '/')
@base_path = "" if @base_path == "/"
end
def base_url
url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}"
URI.encode(url)
end
# Gets API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth
def api_key_with_prefix(param_name)
if @api_key_prefix[param_name]
"#{@api_key_prefix[param_name]} #{@api_key[param_name]}"
else
@api_key[param_name]
end
end
# Gets Basic Auth token string
def basic_auth_token
'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
end
# Returns Auth Settings hash for api client.
def auth_settings
{
'api_key' =>
{
type: 'api_key',
in: 'header',
key: 'api_key',
value: api_key_with_prefix('api_key')
},
}
end
end
end

View File

@ -1,76 +0,0 @@
module Petstore
module Swagger
class << self
attr_accessor :logger
# A Swagger configuration object. Must act like a hash and return sensible
# values for all Swagger configuration options. See Swagger::Configuration.
attr_accessor :configuration
attr_accessor :resources
# Call this method to modify defaults in your initializers.
#
# @example
# Swagger.configure do |config|
# config.api_key['api_key'] = '1234567890abcdef' # api key authentication
# config.username = 'wordlover' # http basic authentication
# config.password = 'i<3words' # http basic authentication
# config.format = 'json' # optional, defaults to 'json'
# end
#
def configure
yield(configuration) if block_given?
self.logger = configuration.logger
# remove :// from scheme
configuration.scheme.sub!(/:\/\//, '')
# remove http(s):// and anything after a slash
configuration.host.sub!(/https?:\/\//, '')
configuration.host = configuration.host.split('/').first
# Add leading and trailing slashes to base_path
configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/')
configuration.base_path = "" if configuration.base_path == "/"
end
def authenticated?
!Swagger.configuration.auth_token.nil?
end
def de_authenticate
Swagger.configuration.auth_token = nil
end
def authenticate
return if Swagger.authenticated?
if Swagger.configuration.username.nil? || Swagger.configuration.password.nil?
raise ApiError, "Username and password are required to authenticate."
end
request = Swagger::Request.new(
:get,
"account/authenticate/{username}",
:params => {
:username => Swagger.configuration.username,
:password => Swagger.configuration.password
}
)
response_body = request.response.body
Swagger.configuration.auth_token = response_body['token']
end
def last_response
Thread.current[:swagger_last_response]
end
def last_response=(response)
Thread.current[:swagger_last_response] = response
end
end
end
end

View File

@ -1,26 +0,0 @@
module Petstore
module Swagger
class ApiError < StandardError
attr_reader :code, :response_headers, :response_body
# Usage examples:
# ApiError.new
# ApiError.new("message")
# ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
# ApiError.new(:code => 404, :message => "Not Found")
def initialize(arg = nil)
if arg.is_a? Hash
arg.each do |k, v|
if k.to_s == 'message'
super v
else
instance_variable_set "@#{k}", v
end
end
else
super arg
end
end
end
end
end

View File

@ -1,101 +0,0 @@
require 'logger'
module Petstore
module Swagger
class Configuration
attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
#
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
attr_accessor :ssl_ca_cert
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debug
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Defaults go in here..
def initialize
@format = 'json'
@scheme = 'http'
@host = 'petstore.swagger.io'
@base_path = '/v2'
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = false
@force_ending_format = false
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
# keys for API key authentication (param-name => api-key)
@api_key = {}
@api_key_prefix = {}
@verify_ssl = true
@debug = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
end
end
end
end

View File

@ -1,213 +0,0 @@
require 'uri'
require 'typhoeus'
module Petstore
module Swagger
class Request
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response
# All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes = {})
@http_method = http_method.to_sym.downcase
@path = path
attributes.each { |name, value| send "#{name}=", value }
@format ||= Swagger.configuration.format
@params ||= {}
# Apply default headers
@headers = Swagger.configuration.default_headers.merge(@headers || {})
# Stick in the auth token if there is one
if Swagger.authenticated?
@headers.merge!({:auth_token => Swagger.configuration.auth_token})
end
update_params_for_auth!
end
# Update hearder and query params based on authentication settings.
def update_params_for_auth!
(@auth_names || []).each do |auth_name|
case auth_name
when 'api_key'
@headers ||= {}
@headers['api_key'] = get_api_key_with_prefix('api_key')
when 'petstore_auth'
# TODO: support oauth
end
end
end
# Get API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth
def get_api_key_with_prefix(param_name)
if Swagger.configuration.api_key_prefix[param_name]
"#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}"
else
Swagger.configuration.api_key[param_name]
end
end
# Construct the request URL.
def url(options = {})
_path = self.interpreted_path
_path = "/#{_path}" unless _path.start_with?('/')
"#{Swagger.configuration.scheme}://#{Swagger.configuration.host}#{_path}"
end
# Iterate over the params hash, injecting any path values into the path string
# e.g. /word.{format}/{word}/entries => /word.json/cat/entries
def interpreted_path
p = self.path.dup
# Stick a .{format} placeholder into the path if there isn't
# one already or an actual format like json or xml
# e.g. /words/blah => /words.{format}/blah
if Swagger.configuration.inject_format
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
p = p.sub(/^(\/?\w+)/, "\\1.#{format}")
end
end
# Stick a .{format} placeholder on the end of the path if there isn't
# one already or an actual format like json or xml
# e.g. /words/blah => /words/blah.{format}
if Swagger.configuration.force_ending_format
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
p = "#{p}.#{format}"
end
end
p = p.sub("{format}", self.format.to_s)
URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
end
# If body is an object, JSONify it before making the actual request.
# For form parameters, remove empty value
def outgoing_body
# http form
if headers['Content-Type'] == 'application/x-www-form-urlencoded'
data = form_params.dup
data.each do |key, value|
data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter
end
elsif @body # http body is JSON
data = @body.is_a?(String) ? @body : @body.to_json
else
data = nil
end
if Swagger.configuration.debug
Swagger.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n"
end
data
end
def make
request_options = {
:method => self.http_method,
:headers => self.headers,
:params => self.params,
:ssl_verifypeer => Swagger.configuration.verify_ssl,
:cainfo => Swagger.configuration.ssl_ca_cert,
:verbose => Swagger.configuration.debug
}
if [:post, :patch, :put, :delete].include?(self.http_method)
request_options.update :body => self.outgoing_body
end
raw = Typhoeus::Request.new(self.url, request_options).run
@response = Response.new(raw)
if Swagger.configuration.debug
Swagger.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n"
end
# record as last response
Swagger.last_response = @response
unless @response.success?
fail ApiError.new(:code => @response.code,
:response_headers => @response.headers,
:response_body => @response.body),
@response.status_message
end
@response
end
def response_code_pretty
return unless @response
@response.code.to_s
end
def response_headers_pretty
return unless @response
# JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end
# return 'Accept' based on an array of accept provided
# @param [Array] header_accept_array Array fo 'Accept'
# @return String Accept (e.g. application/json)
def self.select_header_accept header_accept_array
if header_accept_array.empty?
return
elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 }
'application/json' # look for json data by default
else
header_accept_array.join(',')
end
end
# return the content type based on an array of content-type provided
# @param [Array] content_type_array Array fo content-type
# @return String Content-Type (e.g. application/json)
def self.select_header_content_type content_type_array
if content_type_array.empty?
'application/json' # use application/json by default
elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 }
'application/json' # use application/json if it's included
else
content_type_array[0]; # otherwise, use the first one
end
end
# static method to convert object (array, hash, object, etc) to JSON string
# @param model object to be converted into JSON string
# @return string JSON string representation of the object
def self.object_to_http_body model
return if model.nil?
_body = nil
if model.is_a?(Array)
_body = model.map{|m| object_to_hash(m) }
else
_body = object_to_hash(model)
end
_body.to_json
end
# static method to convert object(non-array) to hash
# @param obj object to be converted into JSON string
# @return string JSON string representation of the object
def self.object_to_hash obj
if obj.respond_to?(:to_hash)
obj.to_hash
else
obj
end
end
end
end
end

View File

@ -1,156 +0,0 @@
module Petstore
module Swagger
class Response
require 'json'
require 'date'
require 'tempfile'
attr_accessor :raw
def initialize(raw)
self.raw = raw
end
def code
raw.code
end
def status_message
raw.status_message
end
def body
raw.body
end
def success?
raw.success?
end
# Deserialize the raw response body to the given return type.
#
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(return_type)
return nil if body.nil? || body.empty?
# handle file downloading - save response body into a tmp file and return the File instance
return download_file if return_type == 'File'
# ensuring a default content type
content_type = raw.headers['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}"
end
begin
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
convert_to_type data, return_type
end
# Convert data to the given return type.
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object, return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet
Petstore.const_get(return_type).new.tap do |model|
model.build_from_hash data
end
end
end
# Save response body into a file in (the defined) temporary folder, using the filename
# from the "Content-Disposition" header if provided, otherwise a random filename.
#
# @see Configuration#temp_folder_path
# @return [File] the file downloaded
def download_file
tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path
content_disposition = raw.headers['Content-Disposition']
if content_disposition
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
path = File.join File.dirname(tmp_file), filename
else
path = tmp_file.path
end
# close and delete temp file
tmp_file.close!
File.open(path, 'w') { |file| file.write(raw.body) }
Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards"
return File.new(path)
end
# `headers_hash` is a Typhoeus-specific extension of Hash,
# so simplify it back into a regular old Hash.
def headers
h = {}
raw.headers_hash.each {|k,v| h[k] = v }
h
end
# Extract the response format from the header hash
# e.g. {'Content-Type' => 'application/json'}
def format
headers['Content-Type'].split("/").last.downcase
end
def json?
format == 'json'
end
def xml?
format == 'xml'
end
def pretty_body
return unless body
if format == 'json'
JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
else
body
end
end
def pretty_headers
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end
end
end
end

View File

@ -1,5 +0,0 @@
module Petstore
module Swagger
VERSION = "1.0.0"
end
end

View File

@ -0,0 +1,3 @@
module Petstore
VERSION = "1.0.0"
end

View File

@ -1,10 +1,10 @@
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "petstore/swagger/version"
require "petstore/version"
Gem::Specification.new do |s|
s.name = "petstore"
s.version = Petstore::Swagger::VERSION
s.version = Petstore::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Zeke Sikelianos", "Tony Tam"]
s.email = ["zeke@wordnik.com", "fehguy@gmail.com"]

View File

@ -0,0 +1,105 @@
# require 'spec_helper'
require File.dirname(__FILE__) + '/spec_helper'
describe Petstore::ApiClient do
context 'initialization' do
context 'URL stuff' do
context 'host' do
it 'removes http from host' do
Petstore.configure { |c| c.host = 'http://example.com' }
Petstore.configure.host.should == 'example.com'
end
it 'removes https from host' do
Petstore.configure { |c| c.host = 'https://wookiee.com' }
Petstore.configure.host.should == 'wookiee.com'
end
it 'removes trailing path from host' do
Petstore.configure { |c| c.host = 'hobo.com/v4' }
Petstore.configure.host.should == 'hobo.com'
end
end
context 'base_path' do
it "prepends a slash to base_path" do
Petstore.configure { |c| c.base_path = 'v4/dog' }
Petstore.configure.base_path.should == '/v4/dog'
end
it "doesn't prepend a slash if one is already there" do
Petstore.configure { |c| c.base_path = '/v4/dog' }
Petstore.configure.base_path.should == '/v4/dog'
end
it "ends up as a blank string if nil" do
Petstore.configure { |c| c.base_path = nil }
Petstore.configure.base_path.should == ''
end
end
end
end
describe "#update_params_for_auth!" do
it "sets header api-key parameter with prefix" do
Petstore.configure do |c|
c.api_key_prefix['api_key'] = 'PREFIX'
c.api_key['api_key'] = 'special-key'
end
api_client = Petstore::ApiClient.new
header_params = {}
query_params = {}
auth_names = ['api_key', 'unknown']
api_client.update_params_for_auth! header_params, query_params, auth_names
header_params.should == {'api_key' => 'PREFIX special-key'}
query_params.should == {}
end
it "sets header api-key parameter without prefix" do
Petstore.configure do |c|
c.api_key_prefix['api_key'] = nil
c.api_key['api_key'] = 'special-key'
end
api_client = Petstore::ApiClient.new
header_params = {}
query_params = {}
auth_names = ['api_key', 'unknown']
api_client.update_params_for_auth! header_params, query_params, auth_names
header_params.should == {'api_key' => 'special-key'}
query_params.should == {}
end
end
describe "#deserialize" do
it "handles Hash<String, String>" do
api_client = Petstore::ApiClient.new
headers = {'Content-Type' => 'application/json'}
response = double('response', headers: headers, body: '{"message": "Hello"}')
data = api_client.deserialize(response, 'Hash<String, String>')
data.should be_a(Hash)
data.should == {:message => 'Hello'}
end
it "handles Hash<String, Pet>" do
api_client = Petstore::ApiClient.new
headers = {'Content-Type' => 'application/json'}
response = double('response', headers: headers, body: '{"pet": {"id": 1}}')
data = api_client.deserialize(response, 'Hash<String, Pet>')
data.should be_a(Hash)
data.keys.should == [:pet]
pet = data[:pet]
pet.should be_a(Petstore::Pet)
pet.id.should == 1
end
end
end

View File

@ -3,8 +3,8 @@ require 'json'
describe "Pet" do
before do
configure_swagger
prepare_pet
@pet_api = Petstore::PetApi.new(API_CLIENT)
prepare_pet @pet_api
end
describe "pet methods" do
@ -42,7 +42,7 @@ describe "Pet" do
end
it "should fetch a pet object" do
pet = Petstore::PetApi.get_pet_by_id(10002)
pet = @pet_api.get_pet_by_id(10002)
pet.should be_a(Petstore::Pet)
pet.id.should == 10002
pet.name.should == "RUBY UNIT TESTING"
@ -52,9 +52,9 @@ describe "Pet" do
it "should not find a pet that does not exist" do
begin
Petstore::PetApi.get_pet_by_id(-10002)
@pet_api.get_pet_by_id(-10002)
fail 'it should raise error'
rescue Petstore::Swagger::ApiError => e
rescue Petstore::ApiError => e
e.code.should == 404
e.message.should == 'Not Found'
e.response_body.should == '{"code":1,"type":"error","message":"Pet not found"}'
@ -64,7 +64,7 @@ describe "Pet" do
end
it "should find pets by status" do
pets = Petstore::PetApi.find_pets_by_status(:status => 'available')
pets = @pet_api.find_pets_by_status(:status => 'available')
pets.length.should >= 3
pets.each do |pet|
pet.should be_a(Petstore::Pet)
@ -73,12 +73,12 @@ describe "Pet" do
end
it "should not find a pet with invalid status" do
pets = Petstore::PetApi.find_pets_by_status(:status => 'invalid-status')
pets = @pet_api.find_pets_by_status(:status => 'invalid-status')
pets.length.should == 0
end
it "should find a pet by status" do
pets = Petstore::PetApi.find_pets_by_status(:status => "available,sold")
pets = @pet_api.find_pets_by_status(:status => "available,sold")
pets.each do |pet|
if pet.status != 'available' && pet.status != 'sold'
raise "pet status wasn't right"
@ -88,22 +88,33 @@ describe "Pet" do
it "should update a pet" do
pet = Petstore::Pet.new({'id' => 10002, 'status' => 'sold'})
Petstore::PetApi.add_pet(:body => pet)
@pet_api.add_pet(:body => pet)
fetched = Petstore::PetApi.get_pet_by_id(10002)
fetched = @pet_api.get_pet_by_id(10002)
fetched.id.should == 10002
fetched.status.should == 'sold'
end
it "should create a pet" do
pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING")
result = Petstore::PetApi.add_pet(:body => pet)
result = @pet_api.add_pet(:body => pet)
# nothing is returned
result.should be_nil
pet = Petstore::PetApi.get_pet_by_id(10002)
pet = @pet_api.get_pet_by_id(10002)
pet.id.should == 10002
pet.name.should == "RUBY UNIT TESTING"
end
it "should upload a file to a pet" do
pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING")
result = @pet_api.add_pet(:body => pet)
# nothing is returned
result.should be_nil
result = @pet_api.upload_file(10002, file: File.new('hello.txt'))
# nothing is returned
result.should be_nil
end
end
end

View File

@ -1,113 +0,0 @@
require 'spec_helper'
describe Petstore::Swagger::Request do
before(:each) do
Petstore::Swagger.configure do |config|
inject_format = true
config.api_key['api_key'] = 'special-key'
config.host = 'petstore.swagger.io'
config.base_path = '/v2'
end
@default_http_method = :get
@default_path = "pet.{format}/fancy"
@default_params = {
:params => {:foo => "1", :bar => "2"}
}
@request = Petstore::Swagger::Request.new(@default_http_method, @default_path, @default_params)
end
describe "initialization" do
it "sets default response format to json" do
@request.format.should == 'json'
end
it "sets default headers correctly" do
@request.headers.should == {'Content-Type' => 'application/json', 'User-Agent' => 'ruby-swagger-1.0.0'}
end
it "allows params to be nil" do
@request = Petstore::Swagger::Request.new(@default_http_method, @default_path, :params => nil)
@request.params.should == {}
end
end
describe "attr_accessors" do
it "has working attributes" do
@request.format.to_s.should == 'json'
end
it "allows attributes to be overwritten" do
@request.http_method.should == :get
@request.http_method = "post"
@request.http_method.should == 'post'
end
end
describe "url" do
it "constructs a full url" do
@request.url.should == "http://petstore.swagger.io/v2/pet.json/fancy"
end
end
describe "path" do
it "accounts for a total absence of format in the path string" do
@request = Petstore::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({
:format => "xml",
:params => {
}
}))
@request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries"
end
it "does string substitution (format) on path params" do
@request = Petstore::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({
:format => "xml",
:params => {
}
}))
@request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries"
end
it "URI encodes the path" do
@request = Petstore::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({
:params => {
:word => "bill gates"
}
}))
@request.url.should =~ /word.json\/bill\%20gates\/definitions/
end
end
describe "#update_params_for_auth!" do
it "sets header api-key parameter with prefix" do
Petstore::Swagger.configure do |config|
inject_format = true
config.api_key_prefix['api_key'] = 'PREFIX'
end
@request.auth_names = ['api_key', 'unknown']
@request.update_params_for_auth!
@request.headers['api_key'].should == 'PREFIX special-key'
end
it "sets header api-key parameter without prefix" do
Petstore::Swagger.configure do |config|
inject_format = true
config.api_key_prefix['api_key'] = nil
end
@request.auth_names = ['api_key', 'unknown']
@request.update_params_for_auth!
@request.headers['api_key'].should == 'special-key'
end
end
end

View File

@ -1,82 +0,0 @@
require 'spec_helper'
describe Petstore::Swagger::Response do
before do
configure_swagger
prepare_pet
end
before(:each) do
VCR.use_cassette('pet_resource', :record => :new_episodes) do
@raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002")
end
@response = Petstore::Swagger::Response.new(@raw)
end
describe "initialization" do
it "sets body" do
@response.body.should be_a(String)
data = JSON.parse(@response.body)
data.should be_a(Hash)
data['id'].should == 10002
end
it "sets code" do
@response.code.should == 200
end
it "converts header string into a hash" do
@response.headers.class.should == Hash
end
end
describe "format" do
it "recognizes json" do
@response.format.should == 'json'
@response.json?.should == true
end
it "recognizes xml" do
VCR.use_cassette('xml_response_request', :record => :new_episodes) do
@raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002",
:headers => {'Accept'=> "application/xml"})
end
@response = Petstore::Swagger::Response.new(@raw)
@response.format.should == 'xml'
@response.xml?.should == true
end
end
describe "prettiness" do
it "has a pretty json body" do
@response.pretty_body.should =~ /\{.*\}/
end
it "has pretty headers" do
@response.pretty_headers.should =~ /\{.*\}/
end
end
describe "deserialize" do
it "handles Hash<String, String>" do
@response.stub(:body) { '{"message": "Hello"}' }
data = @response.deserialize('Hash<String, String>')
data.should be_a(Hash)
data.should == {:message => 'Hello'}
end
it "handles Hash<String, Pet>" do
json = @response.body
@response.stub(:body) { "{\"pet\": #{json}}" }
data = @response.deserialize('Hash<String, Pet>')
data.should be_a(Hash)
data.keys.should == [:pet]
pet = data[:pet]
pet.should be_a(Petstore::Pet)
pet.id.should == 10002
end
end
end

View File

@ -36,40 +36,32 @@ end
# help
#end
def configure_swagger
Petstore::Swagger.configure do |config|
config.api_key['api_key'] = 'special-key'
config.host = 'petstore.swagger.io'
config.base_path = '/v2'
end
end
API_CLIENT = Petstore::ApiClient.new
# always delete and then re-create the pet object with 10002
def prepare_pet
def prepare_pet(pet_api)
# remove the pet
Petstore::PetApi.delete_pet(10002)
pet_api.delete_pet(10002)
# recreate the pet
category = Petstore::Category.new('id' => 20002, 'name' => 'category test')
tag = Petstore::Tag.new('id' => 30002, 'name' => 'tag test')
pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url',
'category' => category, 'tags' => [tag], 'status' => 'pending')
Petstore::PetApi.add_pet(:'body'=> pet)
pet_api.add_pet(:'body'=> pet)
end
# always delete and then re-create the store order
def prepare_store
def prepare_store(store_api)
order = Petstore::Order.new("id" => 10002,
"petId" => 10002,
"quantity" => 789,
"shipDate" => "2015-04-06T23:42:01.678Z",
"status" => "placed",
"complete" => false)
Petstore::StoreApi.place_order(:body => order)
store_api.place_order(:body => order)
end
configure_swagger
# A random string to tack onto stuff to ensure we're not seeing
# data from a previous test run
RAND = ("a".."z").to_a.sample(8).join

View File

@ -2,17 +2,17 @@ require 'spec_helper'
describe "Store" do
before do
configure_swagger
prepare_store
@api = Petstore::StoreApi.new(API_CLIENT)
prepare_store @api
end
it "should fetch an order" do
item = Petstore::StoreApi.get_order_by_id(10002)
item = @api.get_order_by_id(10002)
item.id.should == 10002
end
it "should featch the inventory" do
result = Petstore::StoreApi.get_inventory
result = @api.get_inventory
result.should be_a(Hash)
result.should_not be_empty
result.each do |k, v|

View File

@ -1,56 +0,0 @@
# require 'spec_helper'
require File.dirname(__FILE__) + '/spec_helper'
describe Petstore::Swagger do
before(:each) do
configure_swagger
end
after(:each) do
end
context 'initialization' do
context 'URL stuff' do
context 'host' do
it 'removes http from host' do
Petstore::Swagger.configure {|c| c.host = 'http://example.com' }
Petstore::Swagger.configuration.host.should == 'example.com'
end
it 'removes https from host' do
Petstore::Swagger.configure {|c| c.host = 'https://wookiee.com' }
Petstore::Swagger.configuration.host.should == 'wookiee.com'
end
it 'removes trailing path from host' do
Petstore::Swagger.configure {|c| c.host = 'hobo.com/v4' }
Petstore::Swagger.configuration.host.should == 'hobo.com'
end
end
context 'base_path' do
it "prepends a slash to base_path" do
Petstore::Swagger.configure {|c| c.base_path = 'v4/dog' }
Petstore::Swagger.configuration.base_path.should == '/v4/dog'
end
it "doesn't prepend a slash if one is already there" do
Petstore::Swagger.configure {|c| c.base_path = '/v4/dog' }
Petstore::Swagger.configuration.base_path.should == '/v4/dog'
end
it "ends up as a blank string if nil" do
Petstore::Swagger.configure {|c| c.base_path = nil }
Petstore::Swagger.configuration.base_path.should == ''
end
end
end
end
end