diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index c98d79e5a89b..b251d14faf7f 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -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| - config.api_key['api_key'] = 'special-key' - config.host = 'petstore.swagger.io' - config.base_path = '/v2' - # enable debugging (default is false) - config.debug = true +api_client = Petstore::ApiClient.new do |client| + client.api_key['api_key'] = 'special-key' + client.host = 'petstore.swagger.io' + client.base_path = '/v2' + # enable debugging (default is disabled) + client.debugging = true end -``` -## Getting Started - -```ruby -pet = Petstore::PetApi.get_pet_by_id(5) +pet_api = Petstore::PetApi.new(api_client) +pet = pet_api.get_pet_by_id(5) puts pet.to_body ``` diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index a3f555c17651..f77710df1eab 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -1,10 +1,9 @@ -# 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/request' +require 'petstore/response' +require 'petstore/version' # Models require 'petstore/models/base_object' @@ -20,7 +19,4 @@ require 'petstore/api/pet_api' require 'petstore/api/store_api' module Petstore - # Initialize the default configuration - Swagger.configuration = Swagger::Configuration.new - Swagger.configure { |config| } end diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 51c3cec7fdeb..b50b56e63437 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -2,15 +2,21 @@ require "uri" module Petstore class PetApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = 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 @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#update_pet ..." end # resource path @@ -24,23 +30,23 @@ 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 = Request.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'] = Request.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 = Request.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" + Request.new(@api_client, :PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#update_pet" end nil end @@ -50,9 +56,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 @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#add_pet ..." end # resource path @@ -66,23 +72,23 @@ 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 = Request.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'] = Request.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 = Request.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" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#add_pet" end nil end @@ -92,9 +98,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [Array] :status Status values that need to be considered for filter # @return [Array] - 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 @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#find_pets_by_status ..." end # resource path @@ -109,11 +115,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -123,10 +129,10 @@ 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 + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Array') - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" end result end @@ -136,9 +142,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [Array] :tags Tags to filter by # @return [Array] - 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 @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#find_pets_by_tags ..." end # resource path @@ -153,11 +159,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -167,10 +173,10 @@ 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 + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Array') - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" end result end @@ -180,9 +186,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 @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#get_pet_by_id ..." end # verify the required parameter 'pet_id' is set @@ -199,11 +205,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -213,10 +219,10 @@ module Petstore 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 + response = Request.new(@api_client, :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}" + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" end result end @@ -228,9 +234,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 @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#update_pet_with_form ..." end # verify the required parameter 'pet_id' is set @@ -247,11 +253,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -263,9 +269,9 @@ 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" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#update_pet_with_form" end nil end @@ -276,9 +282,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 @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#delete_pet ..." end # verify the required parameter 'pet_id' is set @@ -295,11 +301,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 = Request.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'] = Request.select_header_content_type(_header_content_type) header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] # form parameters @@ -310,9 +316,9 @@ 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" + Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#delete_pet" end nil end @@ -324,9 +330,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 @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#upload_file ..." end # verify the required parameter 'pet_id' is set @@ -343,11 +349,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -359,9 +365,9 @@ 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" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#upload_file" end nil end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 78328f4b8329..3462cd8f7de3 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -2,14 +2,20 @@ require "uri" module Petstore class StoreApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = api_client + end + # Returns pet inventories by status # Returns a map of status codes to quantities # @param [Hash] opts the optional parameters # @return [Hash] - def self.get_inventory(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: StoreApi#get_inventory ..." + def get_inventory(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#get_inventory ..." end # resource path @@ -23,11 +29,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -37,10 +43,10 @@ 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 + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Hash') - if Swagger.configuration.debug - Swagger.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" end result end @@ -50,9 +56,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 @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#place_order ..." end # resource path @@ -66,24 +72,24 @@ 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 = Request.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'] = Request.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 = Request.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 + response = Request.new(@api_client, :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}" + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" end result end @@ -93,9 +99,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 @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#get_order_by_id ..." end # verify the required parameter 'order_id' is set @@ -112,11 +118,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -126,10 +132,10 @@ 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 + response = Request.new(@api_client, :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}" + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" end result end @@ -139,9 +145,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 @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#delete_order ..." end # verify the required parameter 'order_id' is set @@ -158,11 +164,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -172,9 +178,9 @@ 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" + Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#delete_order" end nil end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 532a9ffa5bf6..5664f735f01e 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -2,15 +2,21 @@ require "uri" module Petstore class UserApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = 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 @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#create_user ..." end # resource path @@ -24,23 +30,23 @@ 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 = Request.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'] = Request.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 = Request.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" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#create_user" end nil end @@ -50,9 +56,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [Array] :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 @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#create_users_with_array_input ..." end # resource path @@ -66,23 +72,23 @@ 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 = Request.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'] = Request.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 = Request.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" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#create_users_with_array_input" end nil end @@ -92,9 +98,9 @@ module Petstore # @param [Hash] opts the optional parameters # @option opts [Array] :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 @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#create_users_with_list_input ..." end # resource path @@ -108,23 +114,23 @@ 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 = Request.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'] = Request.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 = Request.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" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#create_users_with_list_input" end nil end @@ -135,9 +141,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 @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#login_user ..." end # resource path @@ -153,11 +159,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -167,10 +173,10 @@ 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 + response = Request.new(@api_client, :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}" + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" end result end @@ -179,9 +185,9 @@ module Petstore # # @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 @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#logout_user ..." end # resource path @@ -195,11 +201,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -209,9 +215,9 @@ 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" + Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#logout_user" end nil end @@ -221,9 +227,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 @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#get_user_by_name ..." end # verify the required parameter 'username' is set @@ -240,11 +246,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -254,10 +260,10 @@ 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 + response = Request.new(@api_client, :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}" + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" end result end @@ -268,9 +274,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 @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#update_user ..." end # verify the required parameter 'username' is set @@ -287,23 +293,23 @@ 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 = Request.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'] = Request.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 = Request.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" + Request.new(@api_client, :PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#update_user" end nil end @@ -313,9 +319,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 @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#delete_user ..." end # verify the required parameter 'username' is set @@ -332,11 +338,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 = Request.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'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -346,9 +352,9 @@ 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" + Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#delete_user" end nil end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb new file mode 100644 index 000000000000..569003fa133c --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -0,0 +1,134 @@ +require 'logger' +require 'json' + +module Petstore + class ApiClient + 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 :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 + + # 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 + + # The constructor accepts a optional block to configure the API client. + # + # @example + # Petstore::ApiClient.new do |client| + # client.api_key['api_key'] = 'your key' # api key authentication + # client.username = 'your username' # username for http basic authentication + # client.password = 'your password' # password for http basic authentication + # client.format = 'json' # optional, defaults to 'json' + # end + def initialize(&block) + @format = 'json' + @scheme = 'http' + @host = 'petstore.swagger.io' + @base_path = '/v2' + @user_agent = "ruby-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 + + @debugging = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + configure(&block) + end + + # Call this method to modify defaults in your initializers. + def configure + yield(self) if block_given? + + # remove :// from scheme + @scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + @host.sub!(/https?:\/\//, '') + @host = @host.split('/').first + + # Add leading and trailing slashes to base_path + @base_path = "/#{@base_path}".gsub(/\/+/, '/') + @base_path = "" if @base_path == "/" + end + + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers['User-Agent'] = @user_agent + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/api_error.rb b/samples/client/petstore/ruby/lib/petstore/api_error.rb new file mode 100644 index 000000000000..e1b6b3acfd6e --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/api_error.rb @@ -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 diff --git a/samples/client/petstore/ruby/lib/petstore/request.rb b/samples/client/petstore/ruby/lib/petstore/request.rb new file mode 100644 index 000000000000..af884537ff83 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/request.rb @@ -0,0 +1,207 @@ +require 'uri' +require 'typhoeus' + +module Petstore + 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(api_client, http_method, path, attributes = {}) + @api_client = api_client + + @http_method = http_method.to_sym.downcase + @path = path + + attributes.each { |name, value| send "#{name}=", value } + + @format ||= @api_client.format + @params ||= {} + + # Apply default headers + @headers = @api_client.default_headers.merge(@headers || {}) + + 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 @api_client.api_key_prefix[param_name] + "#{@api_client.api_key_prefix[param_name]} #{@api_client.api_key[param_name]}" + else + @api_client.api_key[param_name] + end + end + + # Construct the request URL. + def url(options = {}) + _path = self.interpreted_path + _path = "/#{_path}" unless _path.start_with?('/') + "#{@api_client.scheme}://#{@api_client.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 @api_client.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 @api_client.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 [@api_client.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 @api_client.debugging + @api_client.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 => @api_client.verify_ssl, + :cainfo => @api_client.ssl_ca_cert, + :verbose => @api_client.debugging + } + + 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(@api_client, raw) + + if @api_client.debugging + @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" + end + + # record as last response + @api_client.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/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- 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 diff --git a/samples/client/petstore/ruby/lib/petstore/response.rb b/samples/client/petstore/ruby/lib/petstore/response.rb new file mode 100644 index 000000000000..e54e13ac9515 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/response.rb @@ -0,0 +1,155 @@ +require 'json' +require 'date' +require 'tempfile' + +module Petstore + class Response + attr_accessor :raw + + def initialize(api_client, raw) + @api_client = api_client + @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 + sub_type = $1 + data.map {|item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + 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 '', @api_client.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) } + @api_client.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/, '
') + else + body + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger.rb b/samples/client/petstore/ruby/lib/petstore/swagger.rb deleted file mode 100644 index 4f1433d3286a..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger.rb +++ /dev/null @@ -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 diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb b/samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb deleted file mode 100644 index 9eab46b6eec7..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb +++ /dev/null @@ -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 diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/configuration.rb b/samples/client/petstore/ruby/lib/petstore/swagger/configuration.rb deleted file mode 100644 index d7cc3d734e0d..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/configuration.rb +++ /dev/null @@ -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 diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/request.rb b/samples/client/petstore/ruby/lib/petstore/swagger/request.rb deleted file mode 100644 index ecb8cff56435..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/request.rb +++ /dev/null @@ -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/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- 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 diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/response.rb b/samples/client/petstore/ruby/lib/petstore/swagger/response.rb deleted file mode 100644 index 2ab9be1a5b9e..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/response.rb +++ /dev/null @@ -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 - sub_type = $1 - data.map {|item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - 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/, '
') - else - body - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/version.rb b/samples/client/petstore/ruby/lib/petstore/swagger/version.rb deleted file mode 100644 index ff3c48bb59e6..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/version.rb +++ /dev/null @@ -1,5 +0,0 @@ -module Petstore - module Swagger - VERSION = "1.0.0" - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/version.rb b/samples/client/petstore/ruby/lib/petstore/version.rb new file mode 100644 index 000000000000..fed78553ed33 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/version.rb @@ -0,0 +1,3 @@ +module Petstore + VERSION = "1.0.0" +end diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index 40a169d1741a..6e41479fe466 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -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"]