mirror of
https://github.com/valitydev/openapi-generator.git
synced 2024-11-08 11:23:58 +00:00
Merge pull request #662 from xhh/ruby-module-structure
Organize the generated Ruby code into a module structure
This commit is contained in:
commit
deca6a0329
@ -165,6 +165,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
operation.putAll(config.additionalProperties());
|
||||
operation.put("classname", config.toApiName(tag));
|
||||
operation.put("classVarName", config.toApiVarName(tag));
|
||||
operation.put("importPath", config.toApiImport(tag));
|
||||
|
||||
allOperations.add(new HashMap<String, Object>(operation));
|
||||
for (int i = 0; i < allOperations.size(); i++) {
|
||||
@ -427,6 +428,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
|
||||
CodegenModel cm = config.fromModel(key, mm);
|
||||
Map<String, Object> mo = new HashMap<String, Object>();
|
||||
mo.put("model", cm);
|
||||
mo.put("importPath", config.toModelImport(key));
|
||||
models.add(mo);
|
||||
allImports.addAll(cm.imports);
|
||||
}
|
||||
|
@ -8,10 +8,9 @@ import java.util.*;
|
||||
import java.io.File;
|
||||
|
||||
public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
protected String invokerPackage = "com.wordnik.client";
|
||||
protected String groupId = "com.wordnik";
|
||||
protected String artifactId = "swagger-client";
|
||||
protected String artifactVersion = "1.0.0";
|
||||
protected String gemName = "swagger_client";
|
||||
protected String moduleName = null;
|
||||
protected String libFolder = "lib";
|
||||
|
||||
public CodegenType getTag() {
|
||||
return CodegenType.CLIENT;
|
||||
@ -25,10 +24,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
return "Generates a Ruby client library.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client".
|
||||
*/
|
||||
public String generateModuleName() {
|
||||
return camelize(gemName.replaceAll("[^\\w]+", "_"));
|
||||
}
|
||||
|
||||
public RubyClientCodegen() {
|
||||
super();
|
||||
modelPackage = "models";
|
||||
apiPackage = "lib";
|
||||
moduleName = generateModuleName();
|
||||
modelPackage = gemName + "/models";
|
||||
apiPackage = gemName + "/api";
|
||||
outputFolder = "generated-code/ruby";
|
||||
modelTemplateFiles.put("model.mustache", ".rb");
|
||||
apiTemplateFiles.put("api.mustache", ".rb");
|
||||
@ -39,17 +46,15 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
reservedWords = new HashSet<String> (
|
||||
Arrays.asList(
|
||||
"__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__",
|
||||
"__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__",
|
||||
"begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN",
|
||||
"break", "do", "false", "next", "rescue", "then", "when", "END", "case",
|
||||
"break", "do", "false", "next", "rescue", "then", "when", "END", "case",
|
||||
"else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif",
|
||||
"if", "not", "return", "undef", "yield")
|
||||
);
|
||||
|
||||
additionalProperties.put("invokerPackage", invokerPackage);
|
||||
additionalProperties.put("groupId", groupId);
|
||||
additionalProperties.put("artifactId", artifactId);
|
||||
additionalProperties.put("artifactVersion", artifactVersion);
|
||||
additionalProperties.put("gemName", gemName);
|
||||
additionalProperties.put("moduleName", moduleName);
|
||||
|
||||
languageSpecificPrimitives.add("int");
|
||||
languageSpecificPrimitives.add("array");
|
||||
@ -64,15 +69,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
typeMapping.put("List", "array");
|
||||
typeMapping.put("map", "map");
|
||||
|
||||
supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", "swagger-client.gemspec"));
|
||||
supportingFiles.add(new SupportingFile("swagger-client.mustache", "", "lib/swagger-client.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger.mustache", "", "lib/swagger.rb"));
|
||||
supportingFiles.add(new SupportingFile("monkey.mustache", "", "lib/monkey.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/request.mustache", "", "lib/swagger/request.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/response.mustache", "", "lib/swagger/response.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/version.mustache", "", "lib/swagger/version.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/configuration.mustache", "", "lib/swagger/configuration.rb"));
|
||||
supportingFiles.add(new SupportingFile("base_object.mustache", "", "models/base_object.rb"));
|
||||
String baseFolder = "lib/" + gemName;
|
||||
String swaggerFolder = baseFolder + "/swagger";
|
||||
String modelFolder = baseFolder + "/models";
|
||||
supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec"));
|
||||
supportingFiles.add(new SupportingFile("swagger_client.mustache", "lib", gemName + ".rb"));
|
||||
supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/request.mustache", swaggerFolder, "request.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/response.mustache", swaggerFolder, "response.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/version.mustache", swaggerFolder, "version.rb"));
|
||||
supportingFiles.add(new SupportingFile("swagger/configuration.mustache", swaggerFolder, "configuration.rb"));
|
||||
supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb"));
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -82,11 +90,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
|
||||
@Override
|
||||
public String apiFileFolder() {
|
||||
return outputFolder + "/" + apiPackage().replace('.', File.separatorChar);
|
||||
return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api";
|
||||
}
|
||||
|
||||
public String modelFileFolder() {
|
||||
return outputFolder + "/" + modelPackage().replace('.', File.separatorChar);
|
||||
return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models";
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -150,13 +158,13 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
// should be the same as variable name
|
||||
return toVarName(name);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public String toModelName(String name) {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
|
||||
|
||||
// camelize the model name
|
||||
// phone_number => PhoneNumber
|
||||
return camelize(name);
|
||||
@ -167,11 +175,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
// model name cannot use reserved keyword, e.g. return
|
||||
if(reservedWords.contains(name))
|
||||
throw new RuntimeException(name + " (reserved word) cannot be used as a model name");
|
||||
|
||||
|
||||
// underscore the model file name
|
||||
// PhoneNumber.rb => phone_number.rb
|
||||
return underscore(name);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiFilename(String name) {
|
||||
@ -186,7 +194,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
public String toApiName(String name) {
|
||||
if(name.length() == 0)
|
||||
return "DefaultApi";
|
||||
// e.g. phone_number_api => PhoneNumberApi
|
||||
// e.g. phone_number_api => PhoneNumberApi
|
||||
return camelize(name) + "Api";
|
||||
}
|
||||
|
||||
@ -196,8 +204,17 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
|
||||
if(reservedWords.contains(operationId))
|
||||
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
|
||||
|
||||
return underscore(operationId);
|
||||
return underscore(operationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toModelImport(String name) {
|
||||
return modelPackage() + "/" + toModelFilename(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toApiImport(String name) {
|
||||
return apiPackage() + "/" + toApiFilename(name);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,57 +1,59 @@
|
||||
require "uri"
|
||||
|
||||
module {{moduleName}}
|
||||
{{#operations}}
|
||||
class {{classname}}
|
||||
basePath = "{{basePath}}"
|
||||
# apiInvoker = APIInvoker
|
||||
class {{classname}}
|
||||
basePath = "{{basePath}}"
|
||||
# apiInvoker = APIInvoker
|
||||
{{#operation}}
|
||||
{{newline}}
|
||||
# {{summary}}
|
||||
# {{notes}}
|
||||
{{#allParams}}{{#required}} # @param {{paramName}} {{description}}
|
||||
{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters
|
||||
{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}}
|
||||
{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
||||
def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
|
||||
{{#allParams}}{{#required}}
|
||||
# verify the required parameter '{{paramName}}' is set
|
||||
raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil?
|
||||
{{/required}}{{/allParams}}
|
||||
# {{summary}}
|
||||
# {{notes}}
|
||||
{{#allParams}}{{#required}} # @param {{paramName}} {{description}}
|
||||
{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters
|
||||
{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}}
|
||||
{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
|
||||
def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
|
||||
{{#allParams}}{{#required}}
|
||||
# verify the required parameter '{{paramName}}' is set
|
||||
raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil?
|
||||
{{/required}}{{/allParams}}
|
||||
|
||||
# resource path
|
||||
path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}}
|
||||
# resource path
|
||||
path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}}
|
||||
|
||||
# query parameters
|
||||
query_params = {}{{#queryParams}}{{#required}}
|
||||
query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}}
|
||||
query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}}
|
||||
# query parameters
|
||||
query_params = {}{{#queryParams}}{{#required}}
|
||||
query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}}
|
||||
query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
# 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
|
||||
|
||||
# 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[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}}
|
||||
header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}}
|
||||
# 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[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}}
|
||||
header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}}
|
||||
|
||||
# form parameters
|
||||
form_params = {}{{#formParams}}{{#required}}
|
||||
form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}}
|
||||
form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}}
|
||||
# form parameters
|
||||
form_params = {}{{#formParams}}{{#required}}
|
||||
form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}}
|
||||
form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}}
|
||||
|
||||
# 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}}
|
||||
# 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}}
|
||||
|
||||
{{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
{{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}} Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make{{/returnType}}
|
||||
{{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
{{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}} Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make{{/returnType}}
|
||||
end
|
||||
{{/operation}}
|
||||
end
|
||||
end
|
||||
{{/operations}}
|
||||
end
|
||||
|
@ -1,83 +1,83 @@
|
||||
# base class containing fundamental method such as to_hash, build_from_hash and more
|
||||
class BaseObject
|
||||
module {{moduleName}}
|
||||
# base class containing fundamental method such as to_hash, build_from_hash and more
|
||||
class BaseObject
|
||||
|
||||
# return the object in the form of hash
|
||||
def to_body
|
||||
body = {}
|
||||
self.class.attribute_map.each_pair do |key, value|
|
||||
body[value] = self.send(key) unless self.send(key).nil?
|
||||
# return the object in the form of hash
|
||||
def to_body
|
||||
body = {}
|
||||
self.class.attribute_map.each_pair do |key, value|
|
||||
body[value] = self.send(key) unless self.send(key).nil?
|
||||
end
|
||||
body
|
||||
end
|
||||
body
|
||||
end
|
||||
|
||||
# build the object from hash
|
||||
def build_from_hash(attributes)
|
||||
return nil unless attributes.is_a?(Hash)
|
||||
self.class.swagger_types.each_pair do |key, type|
|
||||
if type =~ /^array\[(.*)\]/i
|
||||
if attributes[self.class.attribute_map[key]].is_a?(Array)
|
||||
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
|
||||
# build the object from hash
|
||||
def build_from_hash(attributes)
|
||||
return nil unless attributes.is_a?(Hash)
|
||||
self.class.swagger_types.each_pair do |key, type|
|
||||
if type =~ /^array\[(.*)\]/i
|
||||
if attributes[self.class.attribute_map[key]].is_a?(Array)
|
||||
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
|
||||
else
|
||||
#TODO show warning in debug mode
|
||||
end
|
||||
elsif !attributes[self.class.attribute_map[key]].nil?
|
||||
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
|
||||
else
|
||||
#TODO show warning in debug mode
|
||||
end
|
||||
elsif !attributes[self.class.attribute_map[key]].nil?
|
||||
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
|
||||
else
|
||||
# data not found in attributes(hash), not an issue as the data can be optional
|
||||
end
|
||||
end
|
||||
|
||||
self
|
||||
end
|
||||
|
||||
def _deserialize(type, value)
|
||||
case type.to_sym
|
||||
when :DateTime
|
||||
DateTime.parse(value)
|
||||
when :string
|
||||
value.to_s
|
||||
when :int
|
||||
value.to_i
|
||||
when :double
|
||||
value.to_f
|
||||
when :boolean
|
||||
if value =~ /^(true|t|yes|y|1)$/i
|
||||
true
|
||||
else
|
||||
false
|
||||
end
|
||||
else # model
|
||||
_model = Object.const_get(type).new
|
||||
_model.build_from_hash(value)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
|
||||
# to_body is an alias to to_body (backward compatibility)
|
||||
def to_hash
|
||||
hash = {}
|
||||
self.class.attribute_map.each_pair do |key, value|
|
||||
if self.send(key).is_a?(Array)
|
||||
next if self.send(key).empty?
|
||||
hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil?
|
||||
else
|
||||
unless (_tmp_value = _to_hash self.send(key)).nil?
|
||||
hash[value] = _tmp_value
|
||||
# data not found in attributes(hash), not an issue as the data can be optional
|
||||
end
|
||||
end
|
||||
end
|
||||
hash
|
||||
end
|
||||
|
||||
# Method to output non-array value in the form of hash
|
||||
# For object, use to_hash. Otherwise, just return the value
|
||||
def _to_hash(value)
|
||||
if value.respond_to? :to_hash
|
||||
value.to_hash
|
||||
else
|
||||
value
|
||||
self
|
||||
end
|
||||
end
|
||||
|
||||
def _deserialize(type, value)
|
||||
case type.to_sym
|
||||
when :DateTime
|
||||
DateTime.parse(value)
|
||||
when :string
|
||||
value.to_s
|
||||
when :int
|
||||
value.to_i
|
||||
when :double
|
||||
value.to_f
|
||||
when :boolean
|
||||
if value =~ /^(true|t|yes|y|1)$/i
|
||||
true
|
||||
else
|
||||
false
|
||||
end
|
||||
else # model
|
||||
_model = {{moduleName}}.const_get(type).new
|
||||
_model.build_from_hash(value)
|
||||
end
|
||||
end
|
||||
|
||||
# to_body is an alias to to_body (backward compatibility)
|
||||
def to_hash
|
||||
hash = {}
|
||||
self.class.attribute_map.each_pair do |key, value|
|
||||
if self.send(key).is_a?(Array)
|
||||
next if self.send(key).empty?
|
||||
hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil?
|
||||
else
|
||||
unless (_tmp_value = _to_hash self.send(key)).nil?
|
||||
hash[value] = _tmp_value
|
||||
end
|
||||
end
|
||||
end
|
||||
hash
|
||||
end
|
||||
|
||||
# Method to output non-array value in the form of hash
|
||||
# For object, use to_hash. Otherwise, just return the value
|
||||
def _to_hash(value)
|
||||
if value.respond_to? :to_hash
|
||||
value.to_hash
|
||||
else
|
||||
value
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
@ -1,41 +1,40 @@
|
||||
require_relative 'base_object'
|
||||
|
||||
{{#models}}#{{description}}
|
||||
{{#model}}class {{classname}} < BaseObject
|
||||
attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}}
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
{{#vars}}
|
||||
# {{description}}
|
||||
:'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}}
|
||||
{{/vars}}
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
{{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}}
|
||||
{{/vars}}
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
{{#vars}}
|
||||
if attributes[:'{{{baseName}}}']
|
||||
{{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array)
|
||||
@{{{name}}} = value
|
||||
end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}}
|
||||
module {{moduleName}}
|
||||
{{#models}} # {{description}}
|
||||
{{#model}} class {{classname}} < BaseObject
|
||||
attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}}
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
{{#vars}}
|
||||
# {{description}}
|
||||
:'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}}
|
||||
{{/vars}}
|
||||
}
|
||||
end
|
||||
{{/vars}}
|
||||
end
|
||||
|
||||
end
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
{{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}}
|
||||
{{/vars}}
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
{{#vars}}
|
||||
if attributes[:'{{{baseName}}}']
|
||||
{{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array)
|
||||
@{{{name}}} = value
|
||||
end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}}
|
||||
end
|
||||
{{/vars}}
|
||||
end
|
||||
end
|
||||
{{/model}}
|
||||
{{/models}}
|
||||
end
|
||||
|
@ -1,33 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
$:.push File.expand_path("../lib", __FILE__)
|
||||
require "swagger/version"
|
||||
|
||||
Gem::Specification.new do |s|
|
||||
s.name = "{{artifactId}}"
|
||||
s.version = Swagger::VERSION
|
||||
s.platform = Gem::Platform::RUBY
|
||||
s.authors = ["Zeke Sikelianos", "Tony Tam"]
|
||||
s.email = ["zeke@wordnik.com", "tony@wordnik.com"]
|
||||
s.homepage = "http://developer.wordnik.com"
|
||||
s.summary = %q{A ruby wrapper for the swagger APIs}
|
||||
s.description = %q{This gem maps to a swagger API}
|
||||
|
||||
s.rubyforge_project = "{{artifactId}}"
|
||||
|
||||
s.add_dependency 'typhoeus', '>=0.2.1'
|
||||
s.add_dependency 'addressable', '>=2.2.4'
|
||||
s.add_dependency 'json', '>=1.4.6'
|
||||
|
||||
s.add_development_dependency 'rspec', '>=2.5.0'
|
||||
s.add_development_dependency 'vcr', '>=1.5.1'
|
||||
s.add_development_dependency 'webmock', '>=1.6.2'
|
||||
s.add_development_dependency 'autotest'
|
||||
s.add_development_dependency 'autotest-rails-pure'
|
||||
s.add_development_dependency 'autotest-growl'
|
||||
s.add_development_dependency 'autotest-fsevent'
|
||||
|
||||
s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? }
|
||||
s.test_files = `find spec/*`.split("\n")
|
||||
s.executables = []
|
||||
s.require_paths = ["lib"]
|
||||
end
|
@ -1,5 +0,0 @@
|
||||
require 'monkey'
|
||||
require 'swagger'
|
||||
|
||||
Dir[File.join(File.dirname(__FILE__), "../lib/*.rb")].each {|file| require file if file !~ /swagger-client\.rb\z/ }
|
||||
Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file }
|
@ -1,86 +1,78 @@
|
||||
require 'monkey'
|
||||
require 'swagger/configuration'
|
||||
require 'swagger/request'
|
||||
require 'swagger/response'
|
||||
require 'swagger/version'
|
||||
require 'logger'
|
||||
require 'json'
|
||||
|
||||
module Swagger
|
||||
|
||||
@configuration = Configuration.new
|
||||
module {{moduleName}}
|
||||
module Swagger
|
||||
class << self
|
||||
attr_accessor :logger
|
||||
|
||||
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
|
||||
# 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 = '1234567890abcdef' # required
|
||||
# config.username = 'wordlover' # optional, but needed for user-related functions
|
||||
# config.password = 'i<3words' # optional, but needed for user-related functions
|
||||
# config.format = 'json' # optional, defaults to 'json'
|
||||
# end
|
||||
#
|
||||
def configure
|
||||
yield(configuration) if block_given?
|
||||
attr_accessor :resources
|
||||
|
||||
# Configure logger. Default to use Rails
|
||||
self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT))
|
||||
# Call this method to modify defaults in your initializers.
|
||||
#
|
||||
# @example
|
||||
# Swagger.configure do |config|
|
||||
# config.api_key = '1234567890abcdef' # required
|
||||
# config.username = 'wordlover' # optional, but needed for user-related functions
|
||||
# config.password = 'i<3words' # optional, but needed for user-related functions
|
||||
# config.format = 'json' # optional, defaults to 'json'
|
||||
# end
|
||||
#
|
||||
def configure
|
||||
yield(configuration) if block_given?
|
||||
|
||||
# remove :// from scheme
|
||||
configuration.scheme.sub!(/:\/\//, '')
|
||||
# Configure logger. Default to use Rails
|
||||
self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT))
|
||||
|
||||
# remove http(s):// and anything after a slash
|
||||
configuration.host.sub!(/https?:\/\//, '')
|
||||
configuration.host = configuration.host.split('/').first
|
||||
# remove :// from scheme
|
||||
configuration.scheme.sub!(/:\/\//, '')
|
||||
|
||||
# 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.present?
|
||||
end
|
||||
|
||||
def de_authenticate
|
||||
Swagger.configuration.auth_token = nil
|
||||
end
|
||||
|
||||
def authenticate
|
||||
return if Swagger.authenticated?
|
||||
|
||||
if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
|
||||
raise ClientError, "Username and password are required to authenticate."
|
||||
# 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.present?
|
||||
end
|
||||
|
||||
def de_authenticate
|
||||
Swagger.configuration.auth_token = nil
|
||||
end
|
||||
|
||||
def authenticate
|
||||
return if Swagger.authenticated?
|
||||
|
||||
if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
|
||||
raise ClientError, "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
|
||||
|
||||
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
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
class ServerError < StandardError
|
||||
end
|
||||
class ServerError < StandardError
|
||||
end
|
||||
|
||||
class ClientError < StandardError
|
||||
class ClientError < StandardError
|
||||
end
|
||||
end
|
||||
|
@ -1,22 +1,19 @@
|
||||
module Swagger
|
||||
|
||||
class Configuration
|
||||
require 'swagger/version'
|
||||
module {{moduleName}}
|
||||
module Swagger
|
||||
class Configuration
|
||||
attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent
|
||||
|
||||
attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent
|
||||
|
||||
# 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
|
||||
@camelize_params = true
|
||||
# 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
|
||||
@camelize_params = true
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
@ -1,263 +1,257 @@
|
||||
module Swagger
|
||||
module {{moduleName}}
|
||||
module Swagger
|
||||
class Request
|
||||
require 'uri'
|
||||
require 'addressable/uri'
|
||||
require 'typhoeus'
|
||||
|
||||
class Request
|
||||
require 'uri'
|
||||
require 'addressable/uri'
|
||||
require 'typhoeus'
|
||||
require "swagger/version"
|
||||
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params
|
||||
|
||||
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params
|
||||
# All requests must have an HTTP method and a path
|
||||
# Optionals parameters are :params, :headers, :body, :format, :host
|
||||
def initialize(http_method, path, attributes={})
|
||||
attributes[:format] ||= Swagger.configuration.format
|
||||
attributes[:params] ||= {}
|
||||
|
||||
# Set default headers
|
||||
default_headers = {
|
||||
'Content-Type' => "application/#{attributes[:format].downcase}",
|
||||
:api_key => Swagger.configuration.api_key,
|
||||
'User-Agent' => Swagger.configuration.user_agent
|
||||
}
|
||||
|
||||
# All requests must have an HTTP method and a path
|
||||
# Optionals parameters are :params, :headers, :body, :format, :host
|
||||
#
|
||||
def initialize(http_method, path, attributes={})
|
||||
attributes[:format] ||= Swagger.configuration.format
|
||||
attributes[:params] ||= {}
|
||||
# api_key from headers hash trumps the default, even if its value is blank
|
||||
if attributes[:headers].present? && attributes[:headers].has_key?(:api_key)
|
||||
default_headers.delete(:api_key)
|
||||
end
|
||||
|
||||
# Set default headers
|
||||
default_headers = {
|
||||
'Content-Type' => "application/#{attributes[:format].downcase}",
|
||||
:api_key => Swagger.configuration.api_key,
|
||||
'User-Agent' => Swagger.configuration.user_agent
|
||||
}
|
||||
# api_key from params hash trumps all others (headers and default_headers)
|
||||
if attributes[:params].present? && attributes[:params].has_key?(:api_key)
|
||||
default_headers.delete(:api_key)
|
||||
attributes[:headers].delete(:api_key) if attributes[:headers].present?
|
||||
end
|
||||
|
||||
# api_key from headers hash trumps the default, even if its value is blank
|
||||
if attributes[:headers].present? && attributes[:headers].has_key?(:api_key)
|
||||
default_headers.delete(:api_key)
|
||||
end
|
||||
|
||||
# api_key from params hash trumps all others (headers and default_headers)
|
||||
if attributes[:params].present? && attributes[:params].has_key?(:api_key)
|
||||
default_headers.delete(:api_key)
|
||||
attributes[:headers].delete(:api_key) if attributes[:headers].present?
|
||||
end
|
||||
|
||||
# Merge argument headers into defaults
|
||||
attributes[:headers] = default_headers.merge(attributes[:headers] || {})
|
||||
|
||||
# Stick in the auth token if there is one
|
||||
if Swagger.authenticated?
|
||||
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
|
||||
end
|
||||
|
||||
self.http_method = http_method.to_sym
|
||||
self.path = path
|
||||
attributes.each do |name, value|
|
||||
send("#{name.to_s.underscore.to_sym}=", value)
|
||||
end
|
||||
end
|
||||
# Merge argument headers into defaults
|
||||
attributes[:headers] = default_headers.merge(attributes[:headers] || {})
|
||||
|
||||
# Construct a base URL
|
||||
#
|
||||
def url(options = {})
|
||||
u = Addressable::URI.new(
|
||||
:scheme => Swagger.configuration.scheme,
|
||||
:host => Swagger.configuration.host,
|
||||
:path => self.interpreted_path,
|
||||
:query => self.query_string.sub(/\?/, '')
|
||||
).to_s
|
||||
|
||||
# Drop trailing question mark, if present
|
||||
u.sub! /\?$/, ''
|
||||
|
||||
# Obfuscate API key?
|
||||
u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated]
|
||||
|
||||
u
|
||||
end
|
||||
# Stick in the auth token if there is one
|
||||
if Swagger.authenticated?
|
||||
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
|
||||
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}")
|
||||
self.http_method = http_method.to_sym
|
||||
self.path = path
|
||||
attributes.each do |name, value|
|
||||
send("#{name.to_s.underscore.to_sym}=", value)
|
||||
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}"
|
||||
# Construct a base URL
|
||||
def url(options = {})
|
||||
u = Addressable::URI.new(
|
||||
:scheme => Swagger.configuration.scheme,
|
||||
:host => Swagger.configuration.host,
|
||||
:path => self.interpreted_path,
|
||||
:query => self.query_string.sub(/\?/, '')
|
||||
).to_s
|
||||
|
||||
# Drop trailing question mark, if present
|
||||
u.sub! /\?$/, ''
|
||||
|
||||
# Obfuscate API key?
|
||||
u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated]
|
||||
|
||||
u
|
||||
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
|
||||
|
||||
# Massage the request body into a state of readiness
|
||||
# If body is a hash, camelize all keys then convert to a json string
|
||||
def body=(value)
|
||||
if value.is_a?(Hash)
|
||||
value = value.inject({}) do |memo, (k,v)|
|
||||
memo[k.to_s.camelize(:lower).to_sym] = v
|
||||
memo
|
||||
end
|
||||
end
|
||||
@body = value
|
||||
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 @body.nil? && @form_params && !@form_params.empty?
|
||||
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
|
||||
data
|
||||
else # http body is JSON
|
||||
@body.is_a?(String) ? @body : @body.to_json
|
||||
end
|
||||
end
|
||||
|
||||
p = p.sub("{format}", self.format.to_s)
|
||||
|
||||
URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
|
||||
end
|
||||
|
||||
# Massage the request body into a state of readiness
|
||||
# If body is a hash, camelize all keys then convert to a json string
|
||||
#
|
||||
def body=(value)
|
||||
if value.is_a?(Hash)
|
||||
value = value.inject({}) do |memo, (k,v)|
|
||||
memo[k.to_s.camelize(:lower).to_sym] = v
|
||||
memo
|
||||
# Construct a query string from the query-string-type params
|
||||
def query_string
|
||||
# Iterate over all params,
|
||||
# .. removing the ones that are part of the path itself.
|
||||
# .. stringifying values so Addressable doesn't blow up.
|
||||
query_values = {}
|
||||
self.params.each_pair do |key, value|
|
||||
next if self.path.include? "{#{key}}" # skip path params
|
||||
next if value.blank? && value.class != FalseClass # skip empties
|
||||
if Swagger.configuration.camelize_params
|
||||
key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param
|
||||
end
|
||||
query_values[key] = value.to_s
|
||||
end
|
||||
|
||||
# We don't want to end up with '?' as our query string
|
||||
# if there aren't really any params
|
||||
return "" if query_values.blank?
|
||||
|
||||
# Addressable requires query_values to be set after initialization..
|
||||
qs = Addressable::URI.new
|
||||
qs.query_values = query_values
|
||||
qs.to_s
|
||||
end
|
||||
|
||||
def make
|
||||
#TODO use configuration setting to determine if debugging
|
||||
#logger = Logger.new STDOUT
|
||||
#logger.debug self.url
|
||||
response = case self.http_method.to_sym
|
||||
when :get,:GET
|
||||
Typhoeus::Request.get(
|
||||
self.url,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :post,:POST
|
||||
Typhoeus::Request.post(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :patch,:PATCH
|
||||
Typhoeus::Request.patch(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :put,:PUT
|
||||
Typhoeus::Request.put(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :delete,:DELETE
|
||||
Typhoeus::Request.delete(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
end
|
||||
Response.new(response)
|
||||
end
|
||||
|
||||
def response
|
||||
self.make
|
||||
end
|
||||
|
||||
def response_code_pretty
|
||||
return unless @response.present?
|
||||
@response.code.to_s
|
||||
end
|
||||
|
||||
def response_headers_pretty
|
||||
return unless @response.present?
|
||||
# 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
|
||||
@body = value
|
||||
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 @body.nil? && @form_params && !@form_params.empty?
|
||||
data = form_params.dup
|
||||
data.each do |key, value|
|
||||
data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter
|
||||
|
||||
# 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
|
||||
data
|
||||
else # http body is JSON
|
||||
@body.is_a?(String) ? @body : @body.to_json
|
||||
end
|
||||
end
|
||||
|
||||
# Construct a query string from the query-string-type params
|
||||
def query_string
|
||||
|
||||
# Iterate over all params,
|
||||
# .. removing the ones that are part of the path itself.
|
||||
# .. stringifying values so Addressable doesn't blow up.
|
||||
query_values = {}
|
||||
self.params.each_pair do |key, value|
|
||||
next if self.path.include? "{#{key}}" # skip path params
|
||||
next if value.blank? && value.class != FalseClass # skip empties
|
||||
if Swagger.configuration.camelize_params
|
||||
key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param
|
||||
# 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
|
||||
query_values[key] = value.to_s
|
||||
_body.to_json
|
||||
end
|
||||
|
||||
# We don't want to end up with '?' as our query string
|
||||
# if there aren't really any params
|
||||
return "" if query_values.blank?
|
||||
|
||||
# Addressable requires query_values to be set after initialization..
|
||||
qs = Addressable::URI.new
|
||||
qs.query_values = query_values
|
||||
qs.to_s
|
||||
end
|
||||
|
||||
def make
|
||||
#TODO use configuration setting to determine if debugging
|
||||
#logger = Logger.new STDOUT
|
||||
#logger.debug self.url
|
||||
response = case self.http_method.to_sym
|
||||
when :get,:GET
|
||||
Typhoeus::Request.get(
|
||||
self.url,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :post,:POST
|
||||
Typhoeus::Request.post(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :patch,:PATCH
|
||||
Typhoeus::Request.patch(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :put,:PUT
|
||||
Typhoeus::Request.put(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :delete,:DELETE
|
||||
Typhoeus::Request.delete(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
# 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
|
||||
Response.new(response)
|
||||
end
|
||||
|
||||
def response
|
||||
self.make
|
||||
end
|
||||
|
||||
def response_code_pretty
|
||||
return unless @response.present?
|
||||
@response.code.to_s
|
||||
end
|
||||
|
||||
def response_headers_pretty
|
||||
return unless @response.present?
|
||||
# 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
|
||||
|
@ -1,70 +1,70 @@
|
||||
module Swagger
|
||||
module {{moduleName}}
|
||||
module Swagger
|
||||
class Response
|
||||
require 'json'
|
||||
|
||||
class Response
|
||||
require 'json'
|
||||
attr_accessor :raw
|
||||
|
||||
attr_accessor :raw
|
||||
def initialize(raw)
|
||||
self.raw = raw
|
||||
|
||||
def initialize(raw)
|
||||
self.raw = raw
|
||||
case self.code
|
||||
when 500..510 then raise(ServerError, self.error_message)
|
||||
when 299..426 then raise(ClientError, self.error_message)
|
||||
end
|
||||
end
|
||||
|
||||
case self.code
|
||||
when 500..510 then raise(ServerError, self.error_message)
|
||||
when 299..426 then raise(ClientError, self.error_message)
|
||||
def code
|
||||
raw.code
|
||||
end
|
||||
|
||||
# Account for error messages that take different forms...
|
||||
def error_message
|
||||
body['message']
|
||||
rescue
|
||||
body
|
||||
end
|
||||
|
||||
# If body is JSON, parse it
|
||||
# Otherwise return raw string
|
||||
def body
|
||||
JSON.parse(raw.body, :symbolize_names => true)
|
||||
rescue
|
||||
raw.body
|
||||
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.present?
|
||||
case format
|
||||
when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
|
||||
end
|
||||
end
|
||||
|
||||
def pretty_headers
|
||||
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
|
||||
end
|
||||
end
|
||||
|
||||
def code
|
||||
raw.code
|
||||
end
|
||||
|
||||
# Account for error messages that take different forms...
|
||||
def error_message
|
||||
body['message']
|
||||
rescue
|
||||
body
|
||||
end
|
||||
|
||||
# If body is JSON, parse it
|
||||
# Otherwise return raw string
|
||||
def body
|
||||
JSON.parse(raw.body, :symbolize_names => true)
|
||||
rescue
|
||||
raw.body
|
||||
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.present?
|
||||
case format
|
||||
when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
|
||||
end
|
||||
end
|
||||
|
||||
def pretty_headers
|
||||
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
@ -1,4 +1,5 @@
|
||||
module Swagger
|
||||
VERSION = "4.06.08"
|
||||
module {{moduleName}}
|
||||
module Swagger
|
||||
VERSION = "{{appVersion}}"
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -0,0 +1,32 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
$:.push File.expand_path("../lib", __FILE__)
|
||||
require "{{gemName}}/swagger/version"
|
||||
|
||||
Gem::Specification.new do |s|
|
||||
s.name = "{{gemName}}"
|
||||
s.version = {{moduleName}}::Swagger::VERSION
|
||||
s.platform = Gem::Platform::RUBY
|
||||
s.authors = ["Zeke Sikelianos", "Tony Tam"]
|
||||
s.email = ["zeke@wordnik.com", "tony@wordnik.com"]
|
||||
s.homepage = "http://developer.wordnik.com"
|
||||
s.summary = %q{A ruby wrapper for the swagger APIs}
|
||||
s.description = %q{This gem maps to a swagger API}
|
||||
s.license = "Apache-2.0"
|
||||
|
||||
s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1'
|
||||
s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4'
|
||||
s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6'
|
||||
|
||||
s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0'
|
||||
s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3'
|
||||
s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2'
|
||||
s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6'
|
||||
s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2'
|
||||
s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16'
|
||||
s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10'
|
||||
|
||||
s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? }
|
||||
s.test_files = `find spec/*`.split("\n")
|
||||
s.executables = []
|
||||
s.require_paths = ["lib"]
|
||||
end
|
@ -0,0 +1,25 @@
|
||||
# Swagger common files
|
||||
require '{{gemName}}/monkey'
|
||||
require '{{gemName}}/swagger'
|
||||
require '{{gemName}}/swagger/configuration'
|
||||
require '{{gemName}}/swagger/request'
|
||||
require '{{gemName}}/swagger/response'
|
||||
require '{{gemName}}/swagger/version'
|
||||
|
||||
# Models
|
||||
require '{{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
|
||||
end
|
@ -1,10 +1,10 @@
|
||||
PATH
|
||||
remote: .
|
||||
specs:
|
||||
swagger-client (4.06.08)
|
||||
addressable (>= 2.2.4)
|
||||
json (>= 1.4.6)
|
||||
typhoeus (>= 0.2.1)
|
||||
swagger_client (1.0.0)
|
||||
addressable (~> 2.2, >= 2.2.4)
|
||||
json (~> 1.4, >= 1.4.6)
|
||||
typhoeus (~> 0.2, >= 0.2.1)
|
||||
|
||||
GEM
|
||||
remote: http://rubygems.org/
|
||||
@ -51,11 +51,11 @@ PLATFORMS
|
||||
ruby
|
||||
|
||||
DEPENDENCIES
|
||||
autotest
|
||||
autotest-fsevent
|
||||
autotest-growl
|
||||
autotest-rails-pure
|
||||
rspec (>= 2.5.0)
|
||||
swagger-client!
|
||||
vcr (>= 1.5.1)
|
||||
webmock (>= 1.6.2)
|
||||
autotest (~> 4.4, >= 4.4.6)
|
||||
autotest-fsevent (~> 0.2, >= 0.2.10)
|
||||
autotest-growl (~> 0.2, >= 0.2.16)
|
||||
autotest-rails-pure (~> 4.1, >= 4.1.2)
|
||||
rspec (~> 3.2, >= 3.2.0)
|
||||
swagger_client!
|
||||
vcr (~> 2.9, >= 2.9.3)
|
||||
webmock (~> 1.6, >= 1.6.2)
|
||||
|
@ -5,20 +5,20 @@
|
||||
You can build the generated client into a gem:
|
||||
|
||||
```shell
|
||||
gem build swagger-client.gemspec
|
||||
gem build swagger_client.gemspec
|
||||
```
|
||||
|
||||
Then you can either install the gem:
|
||||
|
||||
```shell
|
||||
gem install ./swagger-client-4.06.08.gem
|
||||
gem install ./swagger_client-1.0.0.gem
|
||||
```
|
||||
|
||||
or publish the gem to a gem server like [RubyGems](https://rubygems.org/).
|
||||
|
||||
Finally add this to your Gemfile:
|
||||
|
||||
gem 'swagger-client', '~> 4.06.08'
|
||||
gem 'swagger_client', '~> 1.0.0'
|
||||
|
||||
### Host as a git repository
|
||||
|
||||
@ -27,7 +27,7 @@ https://github.com/xhh/swagger-petstore-ruby
|
||||
|
||||
Then you can reference it in Gemfile:
|
||||
|
||||
gem 'swagger-client', :git => 'https://github.com/xhh/swagger-petstore-ruby.git'
|
||||
gem 'swagger_client', :git => 'https://github.com/xhh/swagger-petstore-ruby.git'
|
||||
|
||||
### Use without installation
|
||||
|
||||
@ -40,9 +40,9 @@ ruby -Ilib script.rb
|
||||
## Configuration
|
||||
|
||||
```ruby
|
||||
require 'swagger-client'
|
||||
require 'swagger_client'
|
||||
|
||||
Swagger.configure do |config|
|
||||
SwaggerClient::Swagger.configure do |config|
|
||||
config.api_key = 'special-key'
|
||||
config.host = 'petstore.swagger.io'
|
||||
config.base_path = '/v2'
|
||||
@ -52,6 +52,6 @@ end
|
||||
## Getting Started
|
||||
|
||||
```ruby
|
||||
pet = PetApi.getPetById(5)
|
||||
pet = SwaggerClient::PetApi.get_pet_by_id(5)
|
||||
puts pet.to_body
|
||||
```
|
||||
|
@ -1,313 +0,0 @@
|
||||
require "uri"
|
||||
|
||||
class PetApi
|
||||
basePath = "http://petstore.swagger.io/v2"
|
||||
# apiInvoker = APIInvoker
|
||||
|
||||
# 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 void
|
||||
def self.update_pet(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = ['application/json', 'application/xml', ]
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Add a new pet to the store
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [Pet] :body Pet object that needs to be added to the store
|
||||
# @return void
|
||||
def self.add_pet(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = ['application/json', 'application/xml', ]
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Finds Pets by status
|
||||
# Multiple status values can be provided with comma seperated strings
|
||||
# @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 = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/findByStatus".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
query_params[:'status'] = opts[:'status'] if opts[:'status']
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
response.map {|response| obj = Pet.new() and obj.build_from_hash(response) }
|
||||
end
|
||||
|
||||
# Finds Pets by tags
|
||||
# Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
|
||||
# @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 = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/findByTags".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
query_params[:'tags'] = opts[:'tags'] if opts[:'tags']
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
response.map {|response| obj = Pet.new() and obj.build_from_hash(response) }
|
||||
end
|
||||
|
||||
# Find pet by ID
|
||||
# Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
|
||||
# @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 = {})
|
||||
|
||||
# verify the required parameter 'pet_id' is set
|
||||
raise "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
obj = Pet.new() and obj.build_from_hash(response)
|
||||
end
|
||||
|
||||
# Updates a pet in the store with form data
|
||||
#
|
||||
# @param pet_id ID of pet that needs to be updated
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [string] :name Updated name of the pet
|
||||
# @option opts [string] :status Updated status of the pet
|
||||
# @return void
|
||||
def self.update_pet_with_form(pet_id, opts = {})
|
||||
|
||||
# verify the required parameter 'pet_id' is set
|
||||
raise "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# 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)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
form_params["name"] = opts[:'name'] if opts[:'name']
|
||||
form_params["status"] = opts[:'status'] if opts[:'status']
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Deletes a pet
|
||||
#
|
||||
# @param pet_id Pet id to delete
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [string] :api_key
|
||||
# @return void
|
||||
def self.delete_pet(pet_id, opts = {})
|
||||
|
||||
# verify the required parameter 'pet_id' is set
|
||||
raise "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key']
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# uploads an image
|
||||
#
|
||||
# @param pet_id ID of pet to update
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [string] :additional_metadata Additional data to pass to server
|
||||
# @option opts [file] :file file to upload
|
||||
# @return void
|
||||
def self.upload_file(pet_id, opts = {})
|
||||
|
||||
# verify the required parameter 'pet_id' is set
|
||||
raise "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = ['multipart/form-data', ]
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
form_params["additionalMetadata"] = opts[:'additional_metadata'] if opts[:'additional_metadata']
|
||||
form_params["file"] = opts[:'file'] if opts[:'file']
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
end
|
@ -1,154 +0,0 @@
|
||||
require "uri"
|
||||
|
||||
class StoreApi
|
||||
basePath = "http://petstore.swagger.io/v2"
|
||||
# apiInvoker = APIInvoker
|
||||
|
||||
# Returns pet inventories by status
|
||||
# Returns a map of status codes to quantities
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @return map[string,int]
|
||||
def self.get_inventory(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/store/inventory".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
response.map {|response| obj = map.new() and obj.build_from_hash(response) }
|
||||
end
|
||||
|
||||
# Place an order for a pet
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [Order] :body order placed for purchasing the pet
|
||||
# @return Order
|
||||
def self.place_order(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/store/order".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
obj = Order.new() and obj.build_from_hash(response)
|
||||
end
|
||||
|
||||
# Find purchase order by ID
|
||||
# For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
|
||||
# @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 = {})
|
||||
|
||||
# verify the required parameter 'order_id' is set
|
||||
raise "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
obj = Order.new() and obj.build_from_hash(response)
|
||||
end
|
||||
|
||||
# Delete purchase order by ID
|
||||
# For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
|
||||
# @param order_id ID of the order that needs to be deleted
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @return void
|
||||
def self.delete_order(order_id, opts = {})
|
||||
|
||||
# verify the required parameter 'order_id' is set
|
||||
raise "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
end
|
@ -1,5 +0,0 @@
|
||||
require 'monkey'
|
||||
require 'swagger'
|
||||
|
||||
Dir[File.join(File.dirname(__FILE__), "../lib/*.rb")].each {|file| require file if file !~ /swagger-client\.rb\z/ }
|
||||
Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file }
|
@ -1,86 +0,0 @@
|
||||
require 'monkey'
|
||||
require 'swagger/configuration'
|
||||
require 'swagger/request'
|
||||
require 'swagger/response'
|
||||
require 'swagger/version'
|
||||
require 'logger'
|
||||
require 'json'
|
||||
|
||||
module Swagger
|
||||
|
||||
@configuration = Configuration.new
|
||||
|
||||
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 = '1234567890abcdef' # required
|
||||
# config.username = 'wordlover' # optional, but needed for user-related functions
|
||||
# config.password = 'i<3words' # optional, but needed for user-related functions
|
||||
# config.format = 'json' # optional, defaults to 'json'
|
||||
# end
|
||||
#
|
||||
def configure
|
||||
yield(configuration) if block_given?
|
||||
|
||||
# Configure logger. Default to use Rails
|
||||
self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT))
|
||||
|
||||
# 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.present?
|
||||
end
|
||||
|
||||
def de_authenticate
|
||||
Swagger.configuration.auth_token = nil
|
||||
end
|
||||
|
||||
def authenticate
|
||||
return if Swagger.authenticated?
|
||||
|
||||
if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
|
||||
raise ClientError, "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
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
class ServerError < StandardError
|
||||
end
|
||||
|
||||
class ClientError < StandardError
|
||||
end
|
@ -1,22 +0,0 @@
|
||||
module Swagger
|
||||
|
||||
class Configuration
|
||||
require 'swagger/version'
|
||||
|
||||
attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent
|
||||
|
||||
# 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
|
||||
@camelize_params = true
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
@ -1,263 +0,0 @@
|
||||
module Swagger
|
||||
|
||||
class Request
|
||||
require 'uri'
|
||||
require 'addressable/uri'
|
||||
require 'typhoeus'
|
||||
require "swagger/version"
|
||||
|
||||
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params
|
||||
|
||||
|
||||
# All requests must have an HTTP method and a path
|
||||
# Optionals parameters are :params, :headers, :body, :format, :host
|
||||
#
|
||||
def initialize(http_method, path, attributes={})
|
||||
attributes[:format] ||= Swagger.configuration.format
|
||||
attributes[:params] ||= {}
|
||||
|
||||
# Set default headers
|
||||
default_headers = {
|
||||
'Content-Type' => "application/#{attributes[:format].downcase}",
|
||||
:api_key => Swagger.configuration.api_key,
|
||||
'User-Agent' => Swagger.configuration.user_agent
|
||||
}
|
||||
|
||||
# api_key from headers hash trumps the default, even if its value is blank
|
||||
if attributes[:headers].present? && attributes[:headers].has_key?(:api_key)
|
||||
default_headers.delete(:api_key)
|
||||
end
|
||||
|
||||
# api_key from params hash trumps all others (headers and default_headers)
|
||||
if attributes[:params].present? && attributes[:params].has_key?(:api_key)
|
||||
default_headers.delete(:api_key)
|
||||
attributes[:headers].delete(:api_key) if attributes[:headers].present?
|
||||
end
|
||||
|
||||
# Merge argument headers into defaults
|
||||
attributes[:headers] = default_headers.merge(attributes[:headers] || {})
|
||||
|
||||
# Stick in the auth token if there is one
|
||||
if Swagger.authenticated?
|
||||
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
|
||||
end
|
||||
|
||||
self.http_method = http_method.to_sym
|
||||
self.path = path
|
||||
attributes.each do |name, value|
|
||||
send("#{name.to_s.underscore.to_sym}=", value)
|
||||
end
|
||||
end
|
||||
|
||||
# Construct a base URL
|
||||
#
|
||||
def url(options = {})
|
||||
u = Addressable::URI.new(
|
||||
:scheme => Swagger.configuration.scheme,
|
||||
:host => Swagger.configuration.host,
|
||||
:path => self.interpreted_path,
|
||||
:query => self.query_string.sub(/\?/, '')
|
||||
).to_s
|
||||
|
||||
# Drop trailing question mark, if present
|
||||
u.sub! /\?$/, ''
|
||||
|
||||
# Obfuscate API key?
|
||||
u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated]
|
||||
|
||||
u
|
||||
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
|
||||
|
||||
# Massage the request body into a state of readiness
|
||||
# If body is a hash, camelize all keys then convert to a json string
|
||||
#
|
||||
def body=(value)
|
||||
if value.is_a?(Hash)
|
||||
value = value.inject({}) do |memo, (k,v)|
|
||||
memo[k.to_s.camelize(:lower).to_sym] = v
|
||||
memo
|
||||
end
|
||||
end
|
||||
@body = value
|
||||
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 @body.nil? && @form_params && !@form_params.empty?
|
||||
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
|
||||
data
|
||||
else # http body is JSON
|
||||
@body.is_a?(String) ? @body : @body.to_json
|
||||
end
|
||||
end
|
||||
|
||||
# Construct a query string from the query-string-type params
|
||||
def query_string
|
||||
|
||||
# Iterate over all params,
|
||||
# .. removing the ones that are part of the path itself.
|
||||
# .. stringifying values so Addressable doesn't blow up.
|
||||
query_values = {}
|
||||
self.params.each_pair do |key, value|
|
||||
next if self.path.include? "{#{key}}" # skip path params
|
||||
next if value.blank? && value.class != FalseClass # skip empties
|
||||
if Swagger.configuration.camelize_params
|
||||
key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param
|
||||
end
|
||||
query_values[key] = value.to_s
|
||||
end
|
||||
|
||||
# We don't want to end up with '?' as our query string
|
||||
# if there aren't really any params
|
||||
return "" if query_values.blank?
|
||||
|
||||
# Addressable requires query_values to be set after initialization..
|
||||
qs = Addressable::URI.new
|
||||
qs.query_values = query_values
|
||||
qs.to_s
|
||||
end
|
||||
|
||||
def make
|
||||
#TODO use configuration setting to determine if debugging
|
||||
#logger = Logger.new STDOUT
|
||||
#logger.debug self.url
|
||||
response = case self.http_method.to_sym
|
||||
when :get,:GET
|
||||
Typhoeus::Request.get(
|
||||
self.url,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :post,:POST
|
||||
Typhoeus::Request.post(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :patch,:PATCH
|
||||
Typhoeus::Request.patch(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :put,:PUT
|
||||
Typhoeus::Request.put(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :delete,:DELETE
|
||||
Typhoeus::Request.delete(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
end
|
||||
Response.new(response)
|
||||
end
|
||||
|
||||
def response
|
||||
self.make
|
||||
end
|
||||
|
||||
def response_code_pretty
|
||||
return unless @response.present?
|
||||
@response.code.to_s
|
||||
end
|
||||
|
||||
def response_headers_pretty
|
||||
return unless @response.present?
|
||||
# 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
|
@ -1,70 +0,0 @@
|
||||
module Swagger
|
||||
|
||||
class Response
|
||||
require 'json'
|
||||
|
||||
attr_accessor :raw
|
||||
|
||||
def initialize(raw)
|
||||
self.raw = raw
|
||||
|
||||
case self.code
|
||||
when 500..510 then raise(ServerError, self.error_message)
|
||||
when 299..426 then raise(ClientError, self.error_message)
|
||||
end
|
||||
end
|
||||
|
||||
def code
|
||||
raw.code
|
||||
end
|
||||
|
||||
# Account for error messages that take different forms...
|
||||
def error_message
|
||||
body['message']
|
||||
rescue
|
||||
body
|
||||
end
|
||||
|
||||
# If body is JSON, parse it
|
||||
# Otherwise return raw string
|
||||
def body
|
||||
JSON.parse(raw.body, :symbolize_names => true)
|
||||
rescue
|
||||
raw.body
|
||||
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.present?
|
||||
case format
|
||||
when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
|
||||
end
|
||||
end
|
||||
|
||||
def pretty_headers
|
||||
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
|
||||
end
|
||||
|
||||
end
|
||||
end
|
@ -1,4 +0,0 @@
|
||||
module Swagger
|
||||
VERSION = "4.06.08"
|
||||
end
|
||||
|
25
samples/client/petstore/ruby/lib/swagger_client.rb
Normal file
25
samples/client/petstore/ruby/lib/swagger_client.rb
Normal file
@ -0,0 +1,25 @@
|
||||
# Swagger common files
|
||||
require 'swagger_client/monkey'
|
||||
require 'swagger_client/swagger'
|
||||
require 'swagger_client/swagger/configuration'
|
||||
require 'swagger_client/swagger/request'
|
||||
require 'swagger_client/swagger/response'
|
||||
require 'swagger_client/swagger/version'
|
||||
|
||||
# Models
|
||||
require 'swagger_client/models/base_object'
|
||||
require 'swagger_client/models/user'
|
||||
require 'swagger_client/models/category'
|
||||
require 'swagger_client/models/pet'
|
||||
require 'swagger_client/models/tag'
|
||||
require 'swagger_client/models/order'
|
||||
|
||||
# APIs
|
||||
require 'swagger_client/api/user_api'
|
||||
require 'swagger_client/api/pet_api'
|
||||
require 'swagger_client/api/store_api'
|
||||
|
||||
module SwaggerClient
|
||||
# Initialize the default configuration
|
||||
Swagger.configuration ||= Swagger::Configuration.new
|
||||
end
|
315
samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb
Normal file
315
samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb
Normal file
@ -0,0 +1,315 @@
|
||||
require "uri"
|
||||
|
||||
module SwaggerClient
|
||||
class PetApi
|
||||
basePath = "http://petstore.swagger.io/v2"
|
||||
# apiInvoker = APIInvoker
|
||||
|
||||
# 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 void
|
||||
def self.update_pet(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = ['application/json', 'application/xml', ]
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Add a new pet to the store
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [Pet] :body Pet object that needs to be added to the store
|
||||
# @return void
|
||||
def self.add_pet(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = ['application/json', 'application/xml', ]
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Finds Pets by status
|
||||
# Multiple status values can be provided with comma seperated strings
|
||||
# @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 = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/findByStatus".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
query_params[:'status'] = opts[:'status'] if opts[:'status']
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
response.map {|response| obj = Pet.new() and obj.build_from_hash(response) }
|
||||
end
|
||||
|
||||
# Finds Pets by tags
|
||||
# Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
|
||||
# @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 = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/findByTags".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
query_params[:'tags'] = opts[:'tags'] if opts[:'tags']
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
response.map {|response| obj = Pet.new() and obj.build_from_hash(response) }
|
||||
end
|
||||
|
||||
# Find pet by ID
|
||||
# Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
|
||||
# @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 = {})
|
||||
|
||||
# verify the required parameter 'pet_id' is set
|
||||
raise "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
obj = Pet.new() and obj.build_from_hash(response)
|
||||
end
|
||||
|
||||
# Updates a pet in the store with form data
|
||||
#
|
||||
# @param pet_id ID of pet that needs to be updated
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [string] :name Updated name of the pet
|
||||
# @option opts [string] :status Updated status of the pet
|
||||
# @return void
|
||||
def self.update_pet_with_form(pet_id, opts = {})
|
||||
|
||||
# verify the required parameter 'pet_id' is set
|
||||
raise "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# 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)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
form_params["name"] = opts[:'name'] if opts[:'name']
|
||||
form_params["status"] = opts[:'status'] if opts[:'status']
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Deletes a pet
|
||||
#
|
||||
# @param pet_id Pet id to delete
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [string] :api_key
|
||||
# @return void
|
||||
def self.delete_pet(pet_id, opts = {})
|
||||
|
||||
# verify the required parameter 'pet_id' is set
|
||||
raise "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key']
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# uploads an image
|
||||
#
|
||||
# @param pet_id ID of pet to update
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [string] :additional_metadata Additional data to pass to server
|
||||
# @option opts [file] :file file to upload
|
||||
# @return void
|
||||
def self.upload_file(pet_id, opts = {})
|
||||
|
||||
# verify the required parameter 'pet_id' is set
|
||||
raise "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = ['multipart/form-data', ]
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
form_params["additionalMetadata"] = opts[:'additional_metadata'] if opts[:'additional_metadata']
|
||||
form_params["file"] = opts[:'file'] if opts[:'file']
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
end
|
||||
end
|
156
samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb
Normal file
156
samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb
Normal file
@ -0,0 +1,156 @@
|
||||
require "uri"
|
||||
|
||||
module SwaggerClient
|
||||
class StoreApi
|
||||
basePath = "http://petstore.swagger.io/v2"
|
||||
# apiInvoker = APIInvoker
|
||||
|
||||
# Returns pet inventories by status
|
||||
# Returns a map of status codes to quantities
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @return map[string,int]
|
||||
def self.get_inventory(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/store/inventory".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
response.map {|response| obj = map.new() and obj.build_from_hash(response) }
|
||||
end
|
||||
|
||||
# Place an order for a pet
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [Order] :body order placed for purchasing the pet
|
||||
# @return Order
|
||||
def self.place_order(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/store/order".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
obj = Order.new() and obj.build_from_hash(response)
|
||||
end
|
||||
|
||||
# Find purchase order by ID
|
||||
# For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
|
||||
# @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 = {})
|
||||
|
||||
# verify the required parameter 'order_id' is set
|
||||
raise "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
obj = Order.new() and obj.build_from_hash(response)
|
||||
end
|
||||
|
||||
# Delete purchase order by ID
|
||||
# For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
|
||||
# @param order_id ID of the order that needs to be deleted
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @return void
|
||||
def self.delete_order(order_id, opts = {})
|
||||
|
||||
# verify the required parameter 'order_id' is set
|
||||
raise "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
end
|
||||
end
|
302
samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb
Normal file
302
samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb
Normal file
@ -0,0 +1,302 @@
|
||||
require "uri"
|
||||
|
||||
module SwaggerClient
|
||||
class UserApi
|
||||
basePath = "http://petstore.swagger.io/v2"
|
||||
# apiInvoker = APIInvoker
|
||||
|
||||
# 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 void
|
||||
def self.create_user(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Creates list of users with given input array
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [array[User]] :body List of user object
|
||||
# @return void
|
||||
def self.create_users_with_array_input(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/createWithArray".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Creates list of users with given input array
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [array[User]] :body List of user object
|
||||
# @return void
|
||||
def self.create_users_with_list_input(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/createWithList".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Logs user into the system
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @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 = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/login".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
query_params[:'username'] = opts[:'username'] if opts[:'username']
|
||||
query_params[:'password'] = opts[:'password'] if opts[:'password']
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
obj = string.new() and obj.build_from_hash(response)
|
||||
end
|
||||
|
||||
# Logs out current logged in user session
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @return void
|
||||
def self.logout_user(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/logout".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Get user by user name
|
||||
#
|
||||
# @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 = {})
|
||||
|
||||
# verify the required parameter 'username' is set
|
||||
raise "Missing the required parameter 'username' when calling get_user_by_name" if username.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
obj = User.new() and obj.build_from_hash(response)
|
||||
end
|
||||
|
||||
# Updated user
|
||||
# This can only be done by the logged in user.
|
||||
# @param username name that need to be deleted
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [User] :body Updated user object
|
||||
# @return void
|
||||
def self.update_user(username, opts = {})
|
||||
|
||||
# verify the required parameter 'username' is set
|
||||
raise "Missing the required parameter 'username' when calling update_user" if username.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Delete user
|
||||
# This can only be done by the logged in user.
|
||||
# @param username The name that needs to be deleted
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @return void
|
||||
def self.delete_user(username, opts = {})
|
||||
|
||||
# verify the required parameter 'username' is set
|
||||
raise "Missing the required parameter 'username' when calling delete_user" if username.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
end
|
||||
end
|
@ -0,0 +1,83 @@
|
||||
module SwaggerClient
|
||||
# base class containing fundamental method such as to_hash, build_from_hash and more
|
||||
class BaseObject
|
||||
|
||||
# return the object in the form of hash
|
||||
def to_body
|
||||
body = {}
|
||||
self.class.attribute_map.each_pair do |key, value|
|
||||
body[value] = self.send(key) unless self.send(key).nil?
|
||||
end
|
||||
body
|
||||
end
|
||||
|
||||
# build the object from hash
|
||||
def build_from_hash(attributes)
|
||||
return nil unless attributes.is_a?(Hash)
|
||||
self.class.swagger_types.each_pair do |key, type|
|
||||
if type =~ /^array\[(.*)\]/i
|
||||
if attributes[self.class.attribute_map[key]].is_a?(Array)
|
||||
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
|
||||
else
|
||||
#TODO show warning in debug mode
|
||||
end
|
||||
elsif !attributes[self.class.attribute_map[key]].nil?
|
||||
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
|
||||
else
|
||||
# data not found in attributes(hash), not an issue as the data can be optional
|
||||
end
|
||||
end
|
||||
|
||||
self
|
||||
end
|
||||
|
||||
def _deserialize(type, value)
|
||||
case type.to_sym
|
||||
when :DateTime
|
||||
DateTime.parse(value)
|
||||
when :string
|
||||
value.to_s
|
||||
when :int
|
||||
value.to_i
|
||||
when :double
|
||||
value.to_f
|
||||
when :boolean
|
||||
if value =~ /^(true|t|yes|y|1)$/i
|
||||
true
|
||||
else
|
||||
false
|
||||
end
|
||||
else # model
|
||||
_model = SwaggerClient.const_get(type).new
|
||||
_model.build_from_hash(value)
|
||||
end
|
||||
end
|
||||
|
||||
# to_body is an alias to to_body (backward compatibility)
|
||||
def to_hash
|
||||
hash = {}
|
||||
self.class.attribute_map.each_pair do |key, value|
|
||||
if self.send(key).is_a?(Array)
|
||||
next if self.send(key).empty?
|
||||
hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil?
|
||||
else
|
||||
unless (_tmp_value = _to_hash self.send(key)).nil?
|
||||
hash[value] = _tmp_value
|
||||
end
|
||||
end
|
||||
end
|
||||
hash
|
||||
end
|
||||
|
||||
# Method to output non-array value in the form of hash
|
||||
# For object, use to_hash. Otherwise, just return the value
|
||||
def _to_hash(value)
|
||||
if value.respond_to? :to_hash
|
||||
value.to_hash
|
||||
else
|
||||
value
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
end
|
@ -0,0 +1,44 @@
|
||||
module SwaggerClient
|
||||
#
|
||||
class Category < BaseObject
|
||||
attr_accessor :id, :name
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
|
||||
#
|
||||
:'id' => :'id',
|
||||
|
||||
#
|
||||
:'name' => :'name'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
:'id' => :'int',
|
||||
:'name' => :'string'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
|
||||
if attributes[:'id']
|
||||
@id = attributes[:'id']
|
||||
end
|
||||
|
||||
if attributes[:'name']
|
||||
@name = attributes[:'name']
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
@ -0,0 +1,76 @@
|
||||
module SwaggerClient
|
||||
#
|
||||
class Order < BaseObject
|
||||
attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
|
||||
#
|
||||
:'id' => :'id',
|
||||
|
||||
#
|
||||
:'pet_id' => :'petId',
|
||||
|
||||
#
|
||||
:'quantity' => :'quantity',
|
||||
|
||||
#
|
||||
:'ship_date' => :'shipDate',
|
||||
|
||||
# Order Status
|
||||
:'status' => :'status',
|
||||
|
||||
#
|
||||
:'complete' => :'complete'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
:'id' => :'int',
|
||||
:'pet_id' => :'int',
|
||||
:'quantity' => :'int',
|
||||
:'ship_date' => :'DateTime',
|
||||
:'status' => :'string',
|
||||
:'complete' => :'boolean'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
|
||||
if attributes[:'id']
|
||||
@id = attributes[:'id']
|
||||
end
|
||||
|
||||
if attributes[:'petId']
|
||||
@pet_id = attributes[:'petId']
|
||||
end
|
||||
|
||||
if attributes[:'quantity']
|
||||
@quantity = attributes[:'quantity']
|
||||
end
|
||||
|
||||
if attributes[:'shipDate']
|
||||
@ship_date = attributes[:'shipDate']
|
||||
end
|
||||
|
||||
if attributes[:'status']
|
||||
@status = attributes[:'status']
|
||||
end
|
||||
|
||||
if attributes[:'complete']
|
||||
@complete = attributes[:'complete']
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
@ -0,0 +1,80 @@
|
||||
module SwaggerClient
|
||||
#
|
||||
class Pet < BaseObject
|
||||
attr_accessor :id, :category, :name, :photo_urls, :tags, :status
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
|
||||
#
|
||||
:'id' => :'id',
|
||||
|
||||
#
|
||||
:'category' => :'category',
|
||||
|
||||
#
|
||||
:'name' => :'name',
|
||||
|
||||
#
|
||||
:'photo_urls' => :'photoUrls',
|
||||
|
||||
#
|
||||
:'tags' => :'tags',
|
||||
|
||||
# pet status in the store
|
||||
:'status' => :'status'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
:'id' => :'int',
|
||||
:'category' => :'Category',
|
||||
:'name' => :'string',
|
||||
:'photo_urls' => :'array[string]',
|
||||
:'tags' => :'array[Tag]',
|
||||
:'status' => :'string'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
|
||||
if attributes[:'id']
|
||||
@id = attributes[:'id']
|
||||
end
|
||||
|
||||
if attributes[:'category']
|
||||
@category = attributes[:'category']
|
||||
end
|
||||
|
||||
if attributes[:'name']
|
||||
@name = attributes[:'name']
|
||||
end
|
||||
|
||||
if attributes[:'photoUrls']
|
||||
if (value = attributes[:'photoUrls']).is_a?(Array)
|
||||
@photo_urls = value
|
||||
end
|
||||
end
|
||||
|
||||
if attributes[:'tags']
|
||||
if (value = attributes[:'tags']).is_a?(Array)
|
||||
@tags = value
|
||||
end
|
||||
end
|
||||
|
||||
if attributes[:'status']
|
||||
@status = attributes[:'status']
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
@ -0,0 +1,44 @@
|
||||
module SwaggerClient
|
||||
#
|
||||
class Tag < BaseObject
|
||||
attr_accessor :id, :name
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
|
||||
#
|
||||
:'id' => :'id',
|
||||
|
||||
#
|
||||
:'name' => :'name'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
:'id' => :'int',
|
||||
:'name' => :'string'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
|
||||
if attributes[:'id']
|
||||
@id = attributes[:'id']
|
||||
end
|
||||
|
||||
if attributes[:'name']
|
||||
@name = attributes[:'name']
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
@ -0,0 +1,92 @@
|
||||
module SwaggerClient
|
||||
#
|
||||
class User < BaseObject
|
||||
attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
|
||||
#
|
||||
:'id' => :'id',
|
||||
|
||||
#
|
||||
:'username' => :'username',
|
||||
|
||||
#
|
||||
:'first_name' => :'firstName',
|
||||
|
||||
#
|
||||
:'last_name' => :'lastName',
|
||||
|
||||
#
|
||||
:'email' => :'email',
|
||||
|
||||
#
|
||||
:'password' => :'password',
|
||||
|
||||
#
|
||||
:'phone' => :'phone',
|
||||
|
||||
# User Status
|
||||
:'user_status' => :'userStatus'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
:'id' => :'int',
|
||||
:'username' => :'string',
|
||||
:'first_name' => :'string',
|
||||
:'last_name' => :'string',
|
||||
:'email' => :'string',
|
||||
:'password' => :'string',
|
||||
:'phone' => :'string',
|
||||
:'user_status' => :'int'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
|
||||
if attributes[:'id']
|
||||
@id = attributes[:'id']
|
||||
end
|
||||
|
||||
if attributes[:'username']
|
||||
@username = attributes[:'username']
|
||||
end
|
||||
|
||||
if attributes[:'firstName']
|
||||
@first_name = attributes[:'firstName']
|
||||
end
|
||||
|
||||
if attributes[:'lastName']
|
||||
@last_name = attributes[:'lastName']
|
||||
end
|
||||
|
||||
if attributes[:'email']
|
||||
@email = attributes[:'email']
|
||||
end
|
||||
|
||||
if attributes[:'password']
|
||||
@password = attributes[:'password']
|
||||
end
|
||||
|
||||
if attributes[:'phone']
|
||||
@phone = attributes[:'phone']
|
||||
end
|
||||
|
||||
if attributes[:'userStatus']
|
||||
@user_status = attributes[:'userStatus']
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
78
samples/client/petstore/ruby/lib/swagger_client/swagger.rb
Normal file
78
samples/client/petstore/ruby/lib/swagger_client/swagger.rb
Normal file
@ -0,0 +1,78 @@
|
||||
require 'logger'
|
||||
require 'json'
|
||||
|
||||
module SwaggerClient
|
||||
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 = '1234567890abcdef' # required
|
||||
# config.username = 'wordlover' # optional, but needed for user-related functions
|
||||
# config.password = 'i<3words' # optional, but needed for user-related functions
|
||||
# config.format = 'json' # optional, defaults to 'json'
|
||||
# end
|
||||
#
|
||||
def configure
|
||||
yield(configuration) if block_given?
|
||||
|
||||
# Configure logger. Default to use Rails
|
||||
self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT))
|
||||
|
||||
# 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.present?
|
||||
end
|
||||
|
||||
def de_authenticate
|
||||
Swagger.configuration.auth_token = nil
|
||||
end
|
||||
|
||||
def authenticate
|
||||
return if Swagger.authenticated?
|
||||
|
||||
if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
|
||||
raise ClientError, "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
|
||||
end
|
||||
end
|
||||
|
||||
class ServerError < StandardError
|
||||
end
|
||||
|
||||
class ClientError < StandardError
|
||||
end
|
||||
end
|
@ -0,0 +1,19 @@
|
||||
module SwaggerClient
|
||||
module Swagger
|
||||
class Configuration
|
||||
attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent
|
||||
|
||||
# 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
|
||||
@camelize_params = true
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
@ -0,0 +1,257 @@
|
||||
module SwaggerClient
|
||||
module Swagger
|
||||
class Request
|
||||
require 'uri'
|
||||
require 'addressable/uri'
|
||||
require 'typhoeus'
|
||||
|
||||
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params
|
||||
|
||||
# All requests must have an HTTP method and a path
|
||||
# Optionals parameters are :params, :headers, :body, :format, :host
|
||||
def initialize(http_method, path, attributes={})
|
||||
attributes[:format] ||= Swagger.configuration.format
|
||||
attributes[:params] ||= {}
|
||||
|
||||
# Set default headers
|
||||
default_headers = {
|
||||
'Content-Type' => "application/#{attributes[:format].downcase}",
|
||||
:api_key => Swagger.configuration.api_key,
|
||||
'User-Agent' => Swagger.configuration.user_agent
|
||||
}
|
||||
|
||||
# api_key from headers hash trumps the default, even if its value is blank
|
||||
if attributes[:headers].present? && attributes[:headers].has_key?(:api_key)
|
||||
default_headers.delete(:api_key)
|
||||
end
|
||||
|
||||
# api_key from params hash trumps all others (headers and default_headers)
|
||||
if attributes[:params].present? && attributes[:params].has_key?(:api_key)
|
||||
default_headers.delete(:api_key)
|
||||
attributes[:headers].delete(:api_key) if attributes[:headers].present?
|
||||
end
|
||||
|
||||
# Merge argument headers into defaults
|
||||
attributes[:headers] = default_headers.merge(attributes[:headers] || {})
|
||||
|
||||
# Stick in the auth token if there is one
|
||||
if Swagger.authenticated?
|
||||
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
|
||||
end
|
||||
|
||||
self.http_method = http_method.to_sym
|
||||
self.path = path
|
||||
attributes.each do |name, value|
|
||||
send("#{name.to_s.underscore.to_sym}=", value)
|
||||
end
|
||||
end
|
||||
|
||||
# Construct a base URL
|
||||
def url(options = {})
|
||||
u = Addressable::URI.new(
|
||||
:scheme => Swagger.configuration.scheme,
|
||||
:host => Swagger.configuration.host,
|
||||
:path => self.interpreted_path,
|
||||
:query => self.query_string.sub(/\?/, '')
|
||||
).to_s
|
||||
|
||||
# Drop trailing question mark, if present
|
||||
u.sub! /\?$/, ''
|
||||
|
||||
# Obfuscate API key?
|
||||
u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated]
|
||||
|
||||
u
|
||||
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
|
||||
|
||||
# Massage the request body into a state of readiness
|
||||
# If body is a hash, camelize all keys then convert to a json string
|
||||
def body=(value)
|
||||
if value.is_a?(Hash)
|
||||
value = value.inject({}) do |memo, (k,v)|
|
||||
memo[k.to_s.camelize(:lower).to_sym] = v
|
||||
memo
|
||||
end
|
||||
end
|
||||
@body = value
|
||||
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 @body.nil? && @form_params && !@form_params.empty?
|
||||
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
|
||||
data
|
||||
else # http body is JSON
|
||||
@body.is_a?(String) ? @body : @body.to_json
|
||||
end
|
||||
end
|
||||
|
||||
# Construct a query string from the query-string-type params
|
||||
def query_string
|
||||
# Iterate over all params,
|
||||
# .. removing the ones that are part of the path itself.
|
||||
# .. stringifying values so Addressable doesn't blow up.
|
||||
query_values = {}
|
||||
self.params.each_pair do |key, value|
|
||||
next if self.path.include? "{#{key}}" # skip path params
|
||||
next if value.blank? && value.class != FalseClass # skip empties
|
||||
if Swagger.configuration.camelize_params
|
||||
key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param
|
||||
end
|
||||
query_values[key] = value.to_s
|
||||
end
|
||||
|
||||
# We don't want to end up with '?' as our query string
|
||||
# if there aren't really any params
|
||||
return "" if query_values.blank?
|
||||
|
||||
# Addressable requires query_values to be set after initialization..
|
||||
qs = Addressable::URI.new
|
||||
qs.query_values = query_values
|
||||
qs.to_s
|
||||
end
|
||||
|
||||
def make
|
||||
#TODO use configuration setting to determine if debugging
|
||||
#logger = Logger.new STDOUT
|
||||
#logger.debug self.url
|
||||
response = case self.http_method.to_sym
|
||||
when :get,:GET
|
||||
Typhoeus::Request.get(
|
||||
self.url,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :post,:POST
|
||||
Typhoeus::Request.post(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :patch,:PATCH
|
||||
Typhoeus::Request.patch(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :put,:PUT
|
||||
Typhoeus::Request.put(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
|
||||
when :delete,:DELETE
|
||||
Typhoeus::Request.delete(
|
||||
self.url,
|
||||
:body => self.outgoing_body,
|
||||
:headers => self.headers.stringify_keys,
|
||||
)
|
||||
end
|
||||
Response.new(response)
|
||||
end
|
||||
|
||||
def response
|
||||
self.make
|
||||
end
|
||||
|
||||
def response_code_pretty
|
||||
return unless @response.present?
|
||||
@response.code.to_s
|
||||
end
|
||||
|
||||
def response_headers_pretty
|
||||
return unless @response.present?
|
||||
# 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
|
@ -0,0 +1,70 @@
|
||||
module SwaggerClient
|
||||
module Swagger
|
||||
class Response
|
||||
require 'json'
|
||||
|
||||
attr_accessor :raw
|
||||
|
||||
def initialize(raw)
|
||||
self.raw = raw
|
||||
|
||||
case self.code
|
||||
when 500..510 then raise(ServerError, self.error_message)
|
||||
when 299..426 then raise(ClientError, self.error_message)
|
||||
end
|
||||
end
|
||||
|
||||
def code
|
||||
raw.code
|
||||
end
|
||||
|
||||
# Account for error messages that take different forms...
|
||||
def error_message
|
||||
body['message']
|
||||
rescue
|
||||
body
|
||||
end
|
||||
|
||||
# If body is JSON, parse it
|
||||
# Otherwise return raw string
|
||||
def body
|
||||
JSON.parse(raw.body, :symbolize_names => true)
|
||||
rescue
|
||||
raw.body
|
||||
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.present?
|
||||
case format
|
||||
when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
|
||||
end
|
||||
end
|
||||
|
||||
def pretty_headers
|
||||
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
@ -0,0 +1,5 @@
|
||||
module SwaggerClient
|
||||
module Swagger
|
||||
VERSION = "1.0.0"
|
||||
end
|
||||
end
|
@ -1,300 +0,0 @@
|
||||
require "uri"
|
||||
|
||||
class UserApi
|
||||
basePath = "http://petstore.swagger.io/v2"
|
||||
# apiInvoker = APIInvoker
|
||||
|
||||
# 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 void
|
||||
def self.create_user(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Creates list of users with given input array
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [array[User]] :body List of user object
|
||||
# @return void
|
||||
def self.create_users_with_array_input(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/createWithArray".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Creates list of users with given input array
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [array[User]] :body List of user object
|
||||
# @return void
|
||||
def self.create_users_with_list_input(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/createWithList".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Logs user into the system
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @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 = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/login".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
query_params[:'username'] = opts[:'username'] if opts[:'username']
|
||||
query_params[:'password'] = opts[:'password'] if opts[:'password']
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
obj = string.new() and obj.build_from_hash(response)
|
||||
end
|
||||
|
||||
# Logs out current logged in user session
|
||||
#
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @return void
|
||||
def self.logout_user(opts = {})
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/logout".sub('{format}','json')
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Get user by user name
|
||||
#
|
||||
# @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 = {})
|
||||
|
||||
# verify the required parameter 'username' is set
|
||||
raise "Missing the required parameter 'username' when calling get_user_by_name" if username.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body
|
||||
obj = User.new() and obj.build_from_hash(response)
|
||||
end
|
||||
|
||||
# Updated user
|
||||
# This can only be done by the logged in user.
|
||||
# @param username name that need to be deleted
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @option opts [User] :body Updated user object
|
||||
# @return void
|
||||
def self.update_user(username, opts = {})
|
||||
|
||||
# verify the required parameter 'username' is set
|
||||
raise "Missing the required parameter 'username' when calling update_user" if username.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::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'])
|
||||
|
||||
|
||||
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
|
||||
# Delete user
|
||||
# This can only be done by the logged in user.
|
||||
# @param username The name that needs to be deleted
|
||||
# @param [Hash] opts the optional parameters
|
||||
# @return void
|
||||
def self.delete_user(username, opts = {})
|
||||
|
||||
# verify the required parameter 'username' is set
|
||||
raise "Missing the required parameter 'username' when calling delete_user" if username.nil?
|
||||
|
||||
|
||||
# resource path
|
||||
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
|
||||
|
||||
# query parameters
|
||||
query_params = {}
|
||||
|
||||
# header parameters
|
||||
header_params = {}
|
||||
|
||||
# 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
|
||||
|
||||
# HTTP header 'Content-Type'
|
||||
_header_content_type = []
|
||||
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
|
||||
|
||||
# form parameters
|
||||
form_params = {}
|
||||
|
||||
# http body (model)
|
||||
post_body = nil
|
||||
|
||||
|
||||
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make
|
||||
end
|
||||
end
|
@ -1,83 +0,0 @@
|
||||
# base class containing fundamental method such as to_hash, build_from_hash and more
|
||||
class BaseObject
|
||||
|
||||
# return the object in the form of hash
|
||||
def to_body
|
||||
body = {}
|
||||
self.class.attribute_map.each_pair do |key, value|
|
||||
body[value] = self.send(key) unless self.send(key).nil?
|
||||
end
|
||||
body
|
||||
end
|
||||
|
||||
# build the object from hash
|
||||
def build_from_hash(attributes)
|
||||
return nil unless attributes.is_a?(Hash)
|
||||
self.class.swagger_types.each_pair do |key, type|
|
||||
if type =~ /^array\[(.*)\]/i
|
||||
if attributes[self.class.attribute_map[key]].is_a?(Array)
|
||||
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
|
||||
else
|
||||
#TODO show warning in debug mode
|
||||
end
|
||||
elsif !attributes[self.class.attribute_map[key]].nil?
|
||||
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
|
||||
else
|
||||
# data not found in attributes(hash), not an issue as the data can be optional
|
||||
end
|
||||
end
|
||||
|
||||
self
|
||||
end
|
||||
|
||||
def _deserialize(type, value)
|
||||
case type.to_sym
|
||||
when :DateTime
|
||||
DateTime.parse(value)
|
||||
when :string
|
||||
value.to_s
|
||||
when :int
|
||||
value.to_i
|
||||
when :double
|
||||
value.to_f
|
||||
when :boolean
|
||||
if value =~ /^(true|t|yes|y|1)$/i
|
||||
true
|
||||
else
|
||||
false
|
||||
end
|
||||
else # model
|
||||
_model = Object.const_get(type).new
|
||||
_model.build_from_hash(value)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
|
||||
# to_body is an alias to to_body (backward compatibility)
|
||||
def to_hash
|
||||
hash = {}
|
||||
self.class.attribute_map.each_pair do |key, value|
|
||||
if self.send(key).is_a?(Array)
|
||||
next if self.send(key).empty?
|
||||
hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil?
|
||||
else
|
||||
unless (_tmp_value = _to_hash self.send(key)).nil?
|
||||
hash[value] = _tmp_value
|
||||
end
|
||||
end
|
||||
end
|
||||
hash
|
||||
end
|
||||
|
||||
# Method to output non-array value in the form of hash
|
||||
# For object, use to_hash. Otherwise, just return the value
|
||||
def _to_hash(value)
|
||||
if value.respond_to? :to_hash
|
||||
value.to_hash
|
||||
else
|
||||
value
|
||||
end
|
||||
end
|
||||
|
||||
end
|
@ -1,45 +0,0 @@
|
||||
require_relative 'base_object'
|
||||
|
||||
#
|
||||
class Category < BaseObject
|
||||
attr_accessor :id, :name
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
|
||||
#
|
||||
:'id' => :'id',
|
||||
|
||||
#
|
||||
:'name' => :'name'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
:'id' => :'int',
|
||||
:'name' => :'string'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
|
||||
if attributes[:'id']
|
||||
@id = attributes[:'id']
|
||||
end
|
||||
|
||||
if attributes[:'name']
|
||||
@name = attributes[:'name']
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
@ -1,77 +0,0 @@
|
||||
require_relative 'base_object'
|
||||
|
||||
#
|
||||
class Order < BaseObject
|
||||
attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
|
||||
#
|
||||
:'id' => :'id',
|
||||
|
||||
#
|
||||
:'pet_id' => :'petId',
|
||||
|
||||
#
|
||||
:'quantity' => :'quantity',
|
||||
|
||||
#
|
||||
:'ship_date' => :'shipDate',
|
||||
|
||||
# Order Status
|
||||
:'status' => :'status',
|
||||
|
||||
#
|
||||
:'complete' => :'complete'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
:'id' => :'int',
|
||||
:'pet_id' => :'int',
|
||||
:'quantity' => :'int',
|
||||
:'ship_date' => :'DateTime',
|
||||
:'status' => :'string',
|
||||
:'complete' => :'boolean'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
|
||||
if attributes[:'id']
|
||||
@id = attributes[:'id']
|
||||
end
|
||||
|
||||
if attributes[:'petId']
|
||||
@pet_id = attributes[:'petId']
|
||||
end
|
||||
|
||||
if attributes[:'quantity']
|
||||
@quantity = attributes[:'quantity']
|
||||
end
|
||||
|
||||
if attributes[:'shipDate']
|
||||
@ship_date = attributes[:'shipDate']
|
||||
end
|
||||
|
||||
if attributes[:'status']
|
||||
@status = attributes[:'status']
|
||||
end
|
||||
|
||||
if attributes[:'complete']
|
||||
@complete = attributes[:'complete']
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
@ -1,81 +0,0 @@
|
||||
require_relative 'base_object'
|
||||
|
||||
#
|
||||
class Pet < BaseObject
|
||||
attr_accessor :id, :category, :name, :photo_urls, :tags, :status
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
|
||||
#
|
||||
:'id' => :'id',
|
||||
|
||||
#
|
||||
:'category' => :'category',
|
||||
|
||||
#
|
||||
:'name' => :'name',
|
||||
|
||||
#
|
||||
:'photo_urls' => :'photoUrls',
|
||||
|
||||
#
|
||||
:'tags' => :'tags',
|
||||
|
||||
# pet status in the store
|
||||
:'status' => :'status'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
:'id' => :'int',
|
||||
:'category' => :'Category',
|
||||
:'name' => :'string',
|
||||
:'photo_urls' => :'array[string]',
|
||||
:'tags' => :'array[Tag]',
|
||||
:'status' => :'string'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
|
||||
if attributes[:'id']
|
||||
@id = attributes[:'id']
|
||||
end
|
||||
|
||||
if attributes[:'category']
|
||||
@category = attributes[:'category']
|
||||
end
|
||||
|
||||
if attributes[:'name']
|
||||
@name = attributes[:'name']
|
||||
end
|
||||
|
||||
if attributes[:'photoUrls']
|
||||
if (value = attributes[:'photoUrls']).is_a?(Array)
|
||||
@photo_urls = value
|
||||
end
|
||||
end
|
||||
|
||||
if attributes[:'tags']
|
||||
if (value = attributes[:'tags']).is_a?(Array)
|
||||
@tags = value
|
||||
end
|
||||
end
|
||||
|
||||
if attributes[:'status']
|
||||
@status = attributes[:'status']
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
@ -1,45 +0,0 @@
|
||||
require_relative 'base_object'
|
||||
|
||||
#
|
||||
class Tag < BaseObject
|
||||
attr_accessor :id, :name
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
|
||||
#
|
||||
:'id' => :'id',
|
||||
|
||||
#
|
||||
:'name' => :'name'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
:'id' => :'int',
|
||||
:'name' => :'string'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
|
||||
if attributes[:'id']
|
||||
@id = attributes[:'id']
|
||||
end
|
||||
|
||||
if attributes[:'name']
|
||||
@name = attributes[:'name']
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
@ -1,93 +0,0 @@
|
||||
require_relative 'base_object'
|
||||
|
||||
#
|
||||
class User < BaseObject
|
||||
attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status
|
||||
# attribute mapping from ruby-style variable name to JSON key
|
||||
def self.attribute_map
|
||||
{
|
||||
|
||||
#
|
||||
:'id' => :'id',
|
||||
|
||||
#
|
||||
:'username' => :'username',
|
||||
|
||||
#
|
||||
:'first_name' => :'firstName',
|
||||
|
||||
#
|
||||
:'last_name' => :'lastName',
|
||||
|
||||
#
|
||||
:'email' => :'email',
|
||||
|
||||
#
|
||||
:'password' => :'password',
|
||||
|
||||
#
|
||||
:'phone' => :'phone',
|
||||
|
||||
# User Status
|
||||
:'user_status' => :'userStatus'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
# attribute type
|
||||
def self.swagger_types
|
||||
{
|
||||
:'id' => :'int',
|
||||
:'username' => :'string',
|
||||
:'first_name' => :'string',
|
||||
:'last_name' => :'string',
|
||||
:'email' => :'string',
|
||||
:'password' => :'string',
|
||||
:'phone' => :'string',
|
||||
:'user_status' => :'int'
|
||||
|
||||
}
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
return if !attributes.is_a?(Hash) || attributes.empty?
|
||||
|
||||
# convert string to symbol for hash key
|
||||
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
|
||||
|
||||
|
||||
if attributes[:'id']
|
||||
@id = attributes[:'id']
|
||||
end
|
||||
|
||||
if attributes[:'username']
|
||||
@username = attributes[:'username']
|
||||
end
|
||||
|
||||
if attributes[:'firstName']
|
||||
@first_name = attributes[:'firstName']
|
||||
end
|
||||
|
||||
if attributes[:'lastName']
|
||||
@last_name = attributes[:'lastName']
|
||||
end
|
||||
|
||||
if attributes[:'email']
|
||||
@email = attributes[:'email']
|
||||
end
|
||||
|
||||
if attributes[:'password']
|
||||
@password = attributes[:'password']
|
||||
end
|
||||
|
||||
if attributes[:'phone']
|
||||
@phone = attributes[:'phone']
|
||||
end
|
||||
|
||||
if attributes[:'userStatus']
|
||||
@user_status = attributes[:'userStatus']
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
end
|
@ -6,17 +6,17 @@ describe "Pet" do
|
||||
configure_swagger
|
||||
prepare_pet
|
||||
end
|
||||
|
||||
|
||||
describe "pet methods" do
|
||||
it "should construct a new pet object" do
|
||||
tag1 = Tag.new({'id' => 1, 'name'=> 'tag1'})
|
||||
tag2 = Tag.new({'id' => 2, 'name'=> 'tag2'})
|
||||
category1 = Category.new({:id => 1, :name => 'category unknown'})
|
||||
tag1 = SwaggerClient::Tag.new({'id' => 1, 'name'=> 'tag1'})
|
||||
tag2 = SwaggerClient::Tag.new({'id' => 2, 'name'=> 'tag2'})
|
||||
category1 = SwaggerClient::Category.new({:id => 1, :name => 'category unknown'})
|
||||
# initalize using both string and symbol key
|
||||
pet_hash = {:'id' => 10002, :'name' => "RUBY UNIT TESTING", :'status' => "pending",
|
||||
:'photo_urls' => ["url1", "url2"], :'category' => category1,
|
||||
:'tags' => [tag1, tag2]}
|
||||
pet = Pet.new(pet_hash)
|
||||
pet = SwaggerClient::Pet.new(pet_hash)
|
||||
# test new
|
||||
pet.name.should == "RUBY UNIT TESTING"
|
||||
pet.status.should == "pending"
|
||||
@ -26,7 +26,7 @@ describe "Pet" do
|
||||
pet.category.name.should == 'category unknown'
|
||||
|
||||
# test build_from_hash
|
||||
pet2 = Pet.new
|
||||
pet2 = SwaggerClient::Pet.new
|
||||
pet2.build_from_hash(pet.to_hash)
|
||||
pet.to_hash.should == pet2.to_hash
|
||||
|
||||
@ -37,8 +37,8 @@ describe "Pet" do
|
||||
end
|
||||
|
||||
it "should fetch a pet object" do
|
||||
pet = PetApi.get_pet_by_id(10002)
|
||||
pet.should be_a(Pet)
|
||||
pet = SwaggerClient::PetApi.get_pet_by_id(10002)
|
||||
pet.should be_a(SwaggerClient::Pet)
|
||||
pet.id.should == 10002
|
||||
pet.name.should == "RUBY UNIT TESTING"
|
||||
pet.tags[0].name.should == "tag test"
|
||||
@ -46,38 +46,38 @@ describe "Pet" do
|
||||
end
|
||||
|
||||
it "should find pets by status" do
|
||||
pets = PetApi.find_pets_by_status(:status => 'available')
|
||||
pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'available')
|
||||
pets.length.should >= 3
|
||||
end
|
||||
|
||||
|
||||
it "should not find a pet with invalid status" do
|
||||
pets = PetApi.find_pets_by_status(:status => 'invalid-status')
|
||||
pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'invalid-status')
|
||||
pets.length.should == 0
|
||||
end
|
||||
|
||||
it "should find a pet by status" do
|
||||
pets = PetApi.find_pets_by_status(:status => "available,sold")
|
||||
pets.map {|pet|
|
||||
if(pet.status != 'available' && pet.status != 'sold')
|
||||
pets = SwaggerClient::PetApi.find_pets_by_status(:status => "available,sold")
|
||||
pets.map {|pet|
|
||||
if(pet.status != 'available' && pet.status != 'sold')
|
||||
raise "pet status wasn't right"
|
||||
end
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
it "should update a pet" do
|
||||
pet = Pet.new({'id' => 10002, 'status' => 'sold'})
|
||||
PetApi.add_pet(:body => pet)
|
||||
|
||||
fetched = PetApi.get_pet_by_id(10002)
|
||||
pet = SwaggerClient::Pet.new({'id' => 10002, 'status' => 'sold'})
|
||||
SwaggerClient::PetApi.add_pet(:body => pet)
|
||||
|
||||
fetched = SwaggerClient::PetApi.get_pet_by_id(10002)
|
||||
fetched.id.should == 10002
|
||||
fetched.status.should == 'sold'
|
||||
end
|
||||
|
||||
it "should create a pet" do
|
||||
pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING")
|
||||
PetApi.add_pet(:body => pet)
|
||||
it "should create a pet" do
|
||||
pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING")
|
||||
SwaggerClient::PetApi.add_pet(:body => pet)
|
||||
|
||||
pet = PetApi.get_pet_by_id(10002)
|
||||
pet = SwaggerClient::PetApi.get_pet_by_id(10002)
|
||||
pet.id.should == 10002
|
||||
pet.name.should == "RUBY UNIT TESTING"
|
||||
end
|
||||
|
@ -1,9 +1,9 @@
|
||||
require 'spec_helper'
|
||||
|
||||
describe Swagger::Request do
|
||||
describe SwaggerClient::Swagger::Request do
|
||||
|
||||
before(:each) do
|
||||
Swagger.configure do |config|
|
||||
SwaggerClient::Swagger.configure do |config|
|
||||
inject_format = true
|
||||
config.api_key = 'special-key'
|
||||
config.host = 'petstore.swagger.io'
|
||||
@ -15,7 +15,7 @@ describe Swagger::Request do
|
||||
@default_params = {
|
||||
:params => {:foo => "1", :bar => "2"}
|
||||
}
|
||||
@request = Swagger::Request.new(@default_http_method, @default_path, @default_params)
|
||||
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params)
|
||||
end
|
||||
|
||||
describe "initialization" do
|
||||
@ -24,7 +24,7 @@ describe Swagger::Request do
|
||||
end
|
||||
|
||||
it "allows params to be nil" do
|
||||
@request = Swagger::Request.new(@default_http_method, @default_path, :params => nil)
|
||||
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil)
|
||||
@request.query_string.should == ""
|
||||
end
|
||||
|
||||
@ -59,7 +59,7 @@ describe Swagger::Request do
|
||||
describe "body" do
|
||||
|
||||
it "camelCases parameters" do
|
||||
@request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({
|
||||
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({
|
||||
:body => {
|
||||
:bad_dog => 'bud',
|
||||
:goodDog => "dud"
|
||||
@ -73,7 +73,7 @@ describe Swagger::Request do
|
||||
describe "path" do
|
||||
|
||||
it "accounts for a total absence of format in the path string" do
|
||||
@request = Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({
|
||||
@request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({
|
||||
:format => "xml",
|
||||
:params => {
|
||||
}
|
||||
@ -82,7 +82,7 @@ describe Swagger::Request do
|
||||
end
|
||||
|
||||
it "does string substitution (format) on path params" do
|
||||
@request = Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({
|
||||
@request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({
|
||||
:format => "xml",
|
||||
:params => {
|
||||
}
|
||||
@ -91,7 +91,7 @@ describe Swagger::Request do
|
||||
end
|
||||
|
||||
it "leaves path-bound params out of the query string" do
|
||||
@request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({
|
||||
@request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({
|
||||
:params => {
|
||||
:word => "cat",
|
||||
:limit => 20
|
||||
@ -101,7 +101,7 @@ describe Swagger::Request do
|
||||
end
|
||||
|
||||
it "returns a question-mark free (blank) query string if no query params are present" do
|
||||
@request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({
|
||||
@request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({
|
||||
:params => {
|
||||
:word => "cat",
|
||||
}
|
||||
@ -110,7 +110,7 @@ describe Swagger::Request do
|
||||
end
|
||||
|
||||
it "removes blank params" do
|
||||
@request = Swagger::Request.new(:get, "words/fancy", @default_params.merge({
|
||||
@request = SwaggerClient::Swagger::Request.new(:get, "words/fancy", @default_params.merge({
|
||||
:params => {
|
||||
:word => "dog",
|
||||
:limit => "",
|
||||
@ -121,7 +121,7 @@ describe Swagger::Request do
|
||||
end
|
||||
|
||||
it "URI encodes the path" do
|
||||
@request = Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({
|
||||
@request = SwaggerClient::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({
|
||||
:params => {
|
||||
:word => "bill gates"
|
||||
}
|
||||
@ -130,7 +130,7 @@ describe Swagger::Request do
|
||||
end
|
||||
|
||||
it "converts numeric params to strings" do
|
||||
@request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({
|
||||
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({
|
||||
:params => {
|
||||
:limit => 100
|
||||
}
|
||||
@ -142,7 +142,7 @@ describe Swagger::Request do
|
||||
end
|
||||
|
||||
it "camelCases parameters" do
|
||||
@request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({
|
||||
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({
|
||||
:params => {
|
||||
:bad_dog => 'bud',
|
||||
:goodDog => "dud"
|
||||
@ -153,7 +153,7 @@ describe Swagger::Request do
|
||||
|
||||
it "converts boolean values to their string representation" do
|
||||
params = {:stringy => "fish", :truthy => true, :falsey => false}
|
||||
@request = Swagger::Request.new(:get, 'fakeMethod', :params => params)
|
||||
@request = SwaggerClient::Swagger::Request.new(:get, 'fakeMethod', :params => params)
|
||||
@request.query_string.should == "?falsey=false&stringy=fish&truthy=true"
|
||||
end
|
||||
|
||||
@ -162,12 +162,12 @@ describe Swagger::Request do
|
||||
describe "API key" do
|
||||
|
||||
it "is inferred from the Swagger base configuration by default" do
|
||||
Swagger.configure {|c| c.api_key = "xyz" }
|
||||
Swagger::Request.new(:get, "word/json").headers[:api_key].should == "xyz"
|
||||
SwaggerClient::Swagger.configure {|c| c.api_key = "xyz" }
|
||||
SwaggerClient::Swagger::Request.new(:get, "word/json").headers[:api_key].should == "xyz"
|
||||
end
|
||||
|
||||
it "can be obfuscated for public display" do
|
||||
@request = Swagger::Request.new(:get, "words/fancy", @default_params.merge({
|
||||
@request = SwaggerClient::Swagger::Request.new(:get, "words/fancy", @default_params.merge({
|
||||
:params => {
|
||||
:word => "dog",
|
||||
:api_key => "123456"
|
||||
@ -179,21 +179,21 @@ describe Swagger::Request do
|
||||
end
|
||||
|
||||
it "allows a key in the params to override the configuration-level key, even if it's blank" do
|
||||
Swagger.configure {|c| c.api_key = "abc" }
|
||||
@request_with_key = Swagger::Request.new(:get, "word/json", :params => {:api_key => "jkl"})
|
||||
SwaggerClient::Swagger.configure {|c| c.api_key = "abc" }
|
||||
@request_with_key = SwaggerClient::Swagger::Request.new(:get, "word/json", :params => {:api_key => "jkl"})
|
||||
@request_with_key.headers[:api_key].should be_nil
|
||||
@request_with_key.params[:api_key].should == "jkl"
|
||||
|
||||
@request_without_key = Swagger::Request.new(:get, "word/json", :params => {:api_key => nil})
|
||||
@request_without_key = SwaggerClient::Swagger::Request.new(:get, "word/json", :params => {:api_key => nil})
|
||||
@request_without_key.headers[:api_key].should be_nil
|
||||
@request_without_key.params[:api_key].should be_nil
|
||||
end
|
||||
|
||||
it "allows a key in the headers to override the configuration-level key, even if it's blank" do
|
||||
Swagger.configure {|c| c.api_key = "hij" }
|
||||
Swagger::Request.new(:get, "word/json").headers[:api_key].should == "hij"
|
||||
Swagger::Request.new(:get, "word/json", :headers => {:api_key => "jkl"}).headers[:api_key].should == "jkl"
|
||||
Swagger::Request.new(:get, "word/json", :headers => {:api_key => nil}).headers[:api_key].should be_nil
|
||||
SwaggerClient::Swagger.configure {|c| c.api_key = "hij" }
|
||||
SwaggerClient::Swagger::Request.new(:get, "word/json").headers[:api_key].should == "hij"
|
||||
SwaggerClient::Swagger::Request.new(:get, "word/json", :headers => {:api_key => "jkl"}).headers[:api_key].should == "jkl"
|
||||
SwaggerClient::Swagger::Request.new(:get, "word/json", :headers => {:api_key => nil}).headers[:api_key].should be_nil
|
||||
end
|
||||
|
||||
end
|
||||
|
@ -1,6 +1,6 @@
|
||||
require 'spec_helper'
|
||||
|
||||
describe Swagger::Response do
|
||||
describe SwaggerClient::Swagger::Response do
|
||||
|
||||
before do
|
||||
configure_swagger
|
||||
@ -13,7 +13,7 @@ describe Swagger::Response do
|
||||
@raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002")
|
||||
end
|
||||
|
||||
@response = Swagger::Response.new(@raw)
|
||||
@response = SwaggerClient::Swagger::Response.new(@raw)
|
||||
end
|
||||
|
||||
describe "initialization" do
|
||||
@ -43,7 +43,7 @@ describe Swagger::Response do
|
||||
@raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002",
|
||||
:headers => {'Accept'=> "application/xml"})
|
||||
end
|
||||
@response = Swagger::Response.new(@raw)
|
||||
@response = SwaggerClient::Swagger::Response.new(@raw)
|
||||
@response.format.should == 'xml'
|
||||
@response.xml?.should == true
|
||||
end
|
||||
|
@ -1,6 +1,6 @@
|
||||
require 'rubygems'
|
||||
require 'bundler/setup'
|
||||
require 'swagger-client'
|
||||
require 'swagger_client'
|
||||
require 'vcr'
|
||||
require 'typhoeus'
|
||||
require 'json'
|
||||
@ -37,7 +37,7 @@ end
|
||||
#end
|
||||
|
||||
def configure_swagger
|
||||
Swagger.configure do |config|
|
||||
SwaggerClient::Swagger.configure do |config|
|
||||
config.api_key = 'special-key'
|
||||
config.host = 'petstore.swagger.io'
|
||||
config.base_path = '/v2'
|
||||
@ -47,29 +47,29 @@ end
|
||||
# always delete and then re-create the pet object with 10002
|
||||
def prepare_pet
|
||||
# remove the pet
|
||||
PetApi.delete_pet(10002)
|
||||
SwaggerClient::PetApi.delete_pet(10002)
|
||||
# recreate the pet
|
||||
category = Category.new('id' => 20002, 'name' => 'category test')
|
||||
tag = Tag.new('id' => 30002, 'name' => 'tag test')
|
||||
pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url',
|
||||
'category' => category, 'tags' => [tag], 'status' => 'pending')
|
||||
category = SwaggerClient::Category.new('id' => 20002, 'name' => 'category test')
|
||||
tag = SwaggerClient::Tag.new('id' => 30002, 'name' => 'tag test')
|
||||
pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url',
|
||||
'category' => category, 'tags' => [tag], 'status' => 'pending')
|
||||
|
||||
PetApi.add_pet(:'body'=> pet)
|
||||
SwaggerClient::PetApi.add_pet(:'body'=> pet)
|
||||
end
|
||||
|
||||
# always delete and then re-create the store order
|
||||
# always delete and then re-create the store order
|
||||
def prepare_store
|
||||
order = Order.new("id" => 10002,
|
||||
order = SwaggerClient::Order.new("id" => 10002,
|
||||
"petId" => 10002,
|
||||
"quantity" => 789,
|
||||
"shipDate" => "2015-04-06T23:42:01.678Z",
|
||||
"status" => "placed",
|
||||
"complete" => false)
|
||||
StoreApi.place_order(:body => order)
|
||||
SwaggerClient::StoreApi.place_order(:body => order)
|
||||
end
|
||||
|
||||
configure_swagger
|
||||
|
||||
# A random string to tack onto stuff to ensure we're not seeing
|
||||
# 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
|
||||
|
@ -7,7 +7,7 @@ describe "Store" do
|
||||
end
|
||||
|
||||
it "should fetch an order" do
|
||||
item = StoreApi.get_order_by_id(10002)
|
||||
item = SwaggerClient::StoreApi.get_order_by_id(10002)
|
||||
item.id.should == 10002
|
||||
end
|
||||
end
|
||||
|
@ -1,7 +1,7 @@
|
||||
# require 'spec_helper'
|
||||
require File.dirname(__FILE__) + '/spec_helper'
|
||||
|
||||
describe Swagger do
|
||||
describe SwaggerClient::Swagger do
|
||||
|
||||
before(:each) do
|
||||
configure_swagger
|
||||
@ -16,35 +16,35 @@ describe Swagger do
|
||||
|
||||
context 'host' do
|
||||
it 'removes http from host' do
|
||||
Swagger.configure {|c| c.host = 'http://example.com' }
|
||||
Swagger.configuration.host.should == 'example.com'
|
||||
SwaggerClient::Swagger.configure {|c| c.host = 'http://example.com' }
|
||||
SwaggerClient::Swagger.configuration.host.should == 'example.com'
|
||||
end
|
||||
|
||||
it 'removes https from host' do
|
||||
Swagger.configure {|c| c.host = 'https://wookiee.com' }
|
||||
Swagger.configuration.host.should == 'wookiee.com'
|
||||
SwaggerClient::Swagger.configure {|c| c.host = 'https://wookiee.com' }
|
||||
SwaggerClient::Swagger.configuration.host.should == 'wookiee.com'
|
||||
end
|
||||
|
||||
it 'removes trailing path from host' do
|
||||
Swagger.configure {|c| c.host = 'hobo.com/v4' }
|
||||
Swagger.configuration.host.should == 'hobo.com'
|
||||
SwaggerClient::Swagger.configure {|c| c.host = 'hobo.com/v4' }
|
||||
SwaggerClient::Swagger.configuration.host.should == 'hobo.com'
|
||||
end
|
||||
end
|
||||
|
||||
context 'base_path' do
|
||||
it "prepends a slash to base_path" do
|
||||
Swagger.configure {|c| c.base_path = 'v4/dog' }
|
||||
Swagger.configuration.base_path.should == '/v4/dog'
|
||||
SwaggerClient::Swagger.configure {|c| c.base_path = 'v4/dog' }
|
||||
SwaggerClient::Swagger.configuration.base_path.should == '/v4/dog'
|
||||
end
|
||||
|
||||
it "doesn't prepend a slash if one is already there" do
|
||||
Swagger.configure {|c| c.base_path = '/v4/dog' }
|
||||
Swagger.configuration.base_path.should == '/v4/dog'
|
||||
SwaggerClient::Swagger.configure {|c| c.base_path = '/v4/dog' }
|
||||
SwaggerClient::Swagger.configuration.base_path.should == '/v4/dog'
|
||||
end
|
||||
|
||||
it "ends up as a blank string if nil" do
|
||||
Swagger.configure {|c| c.base_path = nil }
|
||||
Swagger.configuration.base_path.should == ''
|
||||
SwaggerClient::Swagger.configure {|c| c.base_path = nil }
|
||||
SwaggerClient::Swagger.configuration.base_path.should == ''
|
||||
end
|
||||
|
||||
end
|
||||
@ -53,4 +53,4 @@ describe Swagger do
|
||||
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
|
@ -1,33 +0,0 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
$:.push File.expand_path("../lib", __FILE__)
|
||||
require "swagger/version"
|
||||
|
||||
Gem::Specification.new do |s|
|
||||
s.name = "swagger-client"
|
||||
s.version = Swagger::VERSION
|
||||
s.platform = Gem::Platform::RUBY
|
||||
s.authors = ["Zeke Sikelianos", "Tony Tam"]
|
||||
s.email = ["zeke@wordnik.com", "tony@wordnik.com"]
|
||||
s.homepage = "http://developer.wordnik.com"
|
||||
s.summary = %q{A ruby wrapper for the swagger APIs}
|
||||
s.description = %q{This gem maps to a swagger API}
|
||||
|
||||
s.rubyforge_project = "swagger-client"
|
||||
|
||||
s.add_dependency 'typhoeus', '>=0.2.1'
|
||||
s.add_dependency 'addressable', '>=2.2.4'
|
||||
s.add_dependency 'json', '>=1.4.6'
|
||||
|
||||
s.add_development_dependency 'rspec', '>=2.5.0'
|
||||
s.add_development_dependency 'vcr', '>=1.5.1'
|
||||
s.add_development_dependency 'webmock', '>=1.6.2'
|
||||
s.add_development_dependency 'autotest'
|
||||
s.add_development_dependency 'autotest-rails-pure'
|
||||
s.add_development_dependency 'autotest-growl'
|
||||
s.add_development_dependency 'autotest-fsevent'
|
||||
|
||||
s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? }
|
||||
s.test_files = `find spec/*`.split("\n")
|
||||
s.executables = []
|
||||
s.require_paths = ["lib"]
|
||||
end
|
32
samples/client/petstore/ruby/swagger_client.gemspec
Normal file
32
samples/client/petstore/ruby/swagger_client.gemspec
Normal file
@ -0,0 +1,32 @@
|
||||
# -*- encoding: utf-8 -*-
|
||||
$:.push File.expand_path("../lib", __FILE__)
|
||||
require "swagger_client/swagger/version"
|
||||
|
||||
Gem::Specification.new do |s|
|
||||
s.name = "swagger_client"
|
||||
s.version = SwaggerClient::Swagger::VERSION
|
||||
s.platform = Gem::Platform::RUBY
|
||||
s.authors = ["Zeke Sikelianos", "Tony Tam"]
|
||||
s.email = ["zeke@wordnik.com", "tony@wordnik.com"]
|
||||
s.homepage = "http://developer.wordnik.com"
|
||||
s.summary = %q{A ruby wrapper for the swagger APIs}
|
||||
s.description = %q{This gem maps to a swagger API}
|
||||
s.license = "Apache-2.0"
|
||||
|
||||
s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1'
|
||||
s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4'
|
||||
s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6'
|
||||
|
||||
s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0'
|
||||
s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3'
|
||||
s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2'
|
||||
s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6'
|
||||
s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2'
|
||||
s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16'
|
||||
s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10'
|
||||
|
||||
s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? }
|
||||
s.test_files = `find spec/*`.split("\n")
|
||||
s.executables = []
|
||||
s.require_paths = ["lib"]
|
||||
end
|
Loading…
Reference in New Issue
Block a user