This commit is contained in:
Tony Tam 2015-06-07 20:50:35 -07:00
parent aaa0603e29
commit 64ea3f8177
170 changed files with 18425 additions and 17288 deletions

View File

@ -7,133 +7,214 @@ using IO.Swagger.Model;
namespace IO.Swagger.Api { namespace IO.Swagger.Api {
public interface IPetApi { public interface IPetApi {
/// <summary> ///
<summary>
/// Update an existing pet /// Update an existing pet
/// </summary> ///
/// <param name="Body">Pet object that needs to be added to the store</param> </summary>
/// <returns></returns> ///
<param name="Body">Pet object that needs to be added to the store</param>
///
<returns></returns>
void UpdatePet (Pet Body); void UpdatePet (Pet Body);
/// <summary> ///
<summary>
/// Update an existing pet /// Update an existing pet
/// </summary> ///
/// <param name="Body">Pet object that needs to be added to the store</param> </summary>
/// <returns></returns> ///
<param name="Body">Pet object that needs to be added to the store</param>
///
<returns></returns>
Task UpdatePetAsync (Pet Body); Task UpdatePetAsync (Pet Body);
/// <summary> ///
<summary>
/// Add a new pet to the store /// Add a new pet to the store
/// </summary> ///
/// <param name="Body">Pet object that needs to be added to the store</param> </summary>
/// <returns></returns> ///
<param name="Body">Pet object that needs to be added to the store</param>
///
<returns></returns>
void AddPet (Pet Body); void AddPet (Pet Body);
/// <summary> ///
<summary>
/// Add a new pet to the store /// Add a new pet to the store
/// </summary> ///
/// <param name="Body">Pet object that needs to be added to the store</param> </summary>
/// <returns></returns> ///
<param name="Body">Pet object that needs to be added to the store</param>
///
<returns></returns>
Task AddPetAsync (Pet Body); Task AddPetAsync (Pet Body);
/// <summary> ///
<summary>
/// Finds Pets by status Multiple status values can be provided with comma seperated strings /// Finds Pets by status Multiple status values can be provided with comma seperated strings
/// </summary> ///
/// <param name="Status">Status values that need to be considered for filter</param> </summary>
/// <returns>List<Pet></returns> ///
<param name="Status">Status values that need to be considered for filter</param>
///
<returns>List<Pet></returns>
List<Pet> FindPetsByStatus (List<string> Status); List<Pet> FindPetsByStatus (List<string> Status);
/// <summary> ///
<summary>
/// Finds Pets by status Multiple status values can be provided with comma seperated strings /// Finds Pets by status Multiple status values can be provided with comma seperated strings
/// </summary> ///
/// <param name="Status">Status values that need to be considered for filter</param> </summary>
/// <returns>List<Pet></returns> ///
<param name="Status">Status values that need to be considered for filter</param>
///
<returns>List<Pet></returns>
Task<List<Pet>> FindPetsByStatusAsync (List<string> Status); Task<List<Pet>> FindPetsByStatusAsync (List<string> Status);
/// <summary> ///
<summary>
/// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
/// </summary> ///
/// <param name="Tags">Tags to filter by</param> </summary>
/// <returns>List<Pet></returns> ///
<param name="Tags">Tags to filter by</param>
///
<returns>List<Pet></returns>
List<Pet> FindPetsByTags (List<string> Tags); List<Pet> FindPetsByTags (List<string> Tags);
/// <summary> ///
<summary>
/// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
/// </summary> ///
/// <param name="Tags">Tags to filter by</param> </summary>
/// <returns>List<Pet></returns> ///
<param name="Tags">Tags to filter by</param>
///
<returns>List<Pet></returns>
Task<List<Pet>> FindPetsByTagsAsync (List<string> Tags); Task<List<Pet>> FindPetsByTagsAsync (List<string> Tags);
/// <summary> ///
<summary>
/// Find pet by ID Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions /// Find pet by ID Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
/// </summary> ///
/// <param name="PetId">ID of pet that needs to be fetched</param> </summary>
/// <returns>Pet</returns> ///
<param name="PetId">ID of pet that needs to be fetched</param>
///
<returns>Pet</returns>
Pet GetPetById (long? PetId); Pet GetPetById (long? PetId);
/// <summary> ///
<summary>
/// Find pet by ID Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions /// Find pet by ID Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
/// </summary> ///
/// <param name="PetId">ID of pet that needs to be fetched</param> </summary>
/// <returns>Pet</returns> ///
<param name="PetId">ID of pet that needs to be fetched</param>
///
<returns>Pet</returns>
Task<Pet> GetPetByIdAsync (long? PetId); Task<Pet> GetPetByIdAsync (long? PetId);
/// <summary> ///
<summary>
/// Updates a pet in the store with form data /// Updates a pet in the store with form data
/// </summary> ///
/// <param name="PetId">ID of pet that needs to be updated</param>/// <param name="Name">Updated name of the pet</param>/// <param name="Status">Updated status of the pet</param> </summary>
/// <returns></returns> ///
<param name="PetId">ID of pet that needs to be updated</param>///
<param name="Name">Updated name of the pet</param>///
<param name="Status">Updated status of the pet</param>
///
<returns></returns>
void UpdatePetWithForm (string PetId, string Name, string Status); void UpdatePetWithForm (string PetId, string Name, string Status);
/// <summary> ///
<summary>
/// Updates a pet in the store with form data /// Updates a pet in the store with form data
/// </summary> ///
/// <param name="PetId">ID of pet that needs to be updated</param>/// <param name="Name">Updated name of the pet</param>/// <param name="Status">Updated status of the pet</param> </summary>
/// <returns></returns> ///
<param name="PetId">ID of pet that needs to be updated</param>///
<param name="Name">Updated name of the pet</param>///
<param name="Status">Updated status of the pet</param>
///
<returns></returns>
Task UpdatePetWithFormAsync (string PetId, string Name, string Status); Task UpdatePetWithFormAsync (string PetId, string Name, string Status);
/// <summary> ///
<summary>
/// Deletes a pet /// Deletes a pet
/// </summary> ///
/// <param name="ApiKey"></param>/// <param name="PetId">Pet id to delete</param> </summary>
/// <returns></returns> ///
<param name="ApiKey"></param>///
<param name="PetId">Pet id to delete</param>
///
<returns></returns>
void DeletePet (string ApiKey, long? PetId); void DeletePet (string ApiKey, long? PetId);
/// <summary> ///
<summary>
/// Deletes a pet /// Deletes a pet
/// </summary> ///
/// <param name="ApiKey"></param>/// <param name="PetId">Pet id to delete</param> </summary>
/// <returns></returns> ///
<param name="ApiKey"></param>///
<param name="PetId">Pet id to delete</param>
///
<returns></returns>
Task DeletePetAsync (string ApiKey, long? PetId); Task DeletePetAsync (string ApiKey, long? PetId);
/// <summary> ///
<summary>
/// uploads an image /// uploads an image
/// </summary> ///
/// <param name="PetId">ID of pet to update</param>/// <param name="AdditionalMetadata">Additional data to pass to server</param>/// <param name="File">file to upload</param> </summary>
/// <returns></returns> ///
<param name="PetId">ID of pet to update</param>///
<param name="AdditionalMetadata">Additional data to pass to server</param>///
<param name="File">file to upload</param>
///
<returns></returns>
void UploadFile (long? PetId, string AdditionalMetadata, string File); void UploadFile (long? PetId, string AdditionalMetadata, string File);
/// <summary> ///
<summary>
/// uploads an image /// uploads an image
/// </summary> ///
/// <param name="PetId">ID of pet to update</param>/// <param name="AdditionalMetadata">Additional data to pass to server</param>/// <param name="File">file to upload</param> </summary>
/// <returns></returns> ///
<param name="PetId">ID of pet to update</param>///
<param name="AdditionalMetadata">Additional data to pass to server</param>///
<param name="File">file to upload</param>
///
<returns></returns>
Task UploadFileAsync (long? PetId, string AdditionalMetadata, string File); Task UploadFileAsync (long? PetId, string AdditionalMetadata, string File);
} }
/// <summary> ///
<summary>
/// Represents a collection of functions to interact with the API endpoints /// Represents a collection of functions to interact with the API endpoints
/// </summary> ///
</summary>
public class PetApi : IPetApi { public class PetApi : IPetApi {
/// <summary> ///
/// Initializes a new instance of the <see cref="PetApi"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <param name="apiClient"> an instance of ApiClient (optional) <see cref="PetApi"/>
/// <returns></returns> class.
///
</summary>
///
<param name="apiClient"> an instance of ApiClient (optional)
///
<returns></returns>
public PetApi(ApiClient apiClient = null) { public PetApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient; this.apiClient = Configuration.apiClient;
@ -142,44 +223,62 @@ namespace IO.Swagger.Api {
} }
} }
/// <summary> ///
/// Initializes a new instance of the <see cref="PetApi"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <returns></returns> <see cref="PetApi"/>
class.
///
</summary>
///
<returns></returns>
public PetApi(String basePath) public PetApi(String basePath)
{ {
this.apiClient = new ApiClient(basePath); this.apiClient = new ApiClient(basePath);
} }
/// <summary> ///
<summary>
/// Sets the base path of the API client. /// Sets the base path of the API client.
/// </summary> ///
/// <value>The base path</value> </summary>
///
<value>The base path</value>
public void SetBasePath(String basePath) { public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath; this.apiClient.basePath = basePath;
} }
/// <summary> ///
<summary>
/// Gets the base path of the API client. /// Gets the base path of the API client.
/// </summary> ///
/// <value>The base path</value> </summary>
///
<value>The base path</value>
public String GetBasePath(String basePath) { public String GetBasePath(String basePath) {
return this.apiClient.basePath; return this.apiClient.basePath;
} }
/// <summary> ///
<summary>
/// Gets or sets the API client. /// Gets or sets the API client.
/// </summary> ///
/// <value>The API client</value> </summary>
///
<value>The API client</value>
public ApiClient apiClient {get; set;} public ApiClient apiClient {get; set;}
/// <summary> ///
<summary>
/// Update an existing pet /// Update an existing pet
/// </summary> ///
/// <param name="Body">Pet object that needs to be added to the store</param> </summary>
/// <returns></returns> ///
<param name="Body">Pet object that needs to be added to the store</param>
///
<returns></returns>
public void UpdatePet (Pet Body) { public void UpdatePet (Pet Body) {
@ -188,10 +287,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -213,11 +316,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Update an existing pet /// Update an existing pet
/// </summary> ///
/// <param name="Body">Pet object that needs to be added to the store</param> </summary>
/// <returns></returns> ///
<param name="Body">Pet object that needs to be added to the store</param>
///
<returns></returns>
public async Task UpdatePetAsync (Pet Body) { public async Task UpdatePetAsync (Pet Body) {
@ -226,10 +333,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -250,11 +361,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Add a new pet to the store /// Add a new pet to the store
/// </summary> ///
/// <param name="Body">Pet object that needs to be added to the store</param> </summary>
/// <returns></returns> ///
<param name="Body">Pet object that needs to be added to the store</param>
///
<returns></returns>
public void AddPet (Pet Body) { public void AddPet (Pet Body) {
@ -263,10 +378,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -288,11 +407,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Add a new pet to the store /// Add a new pet to the store
/// </summary> ///
/// <param name="Body">Pet object that needs to be added to the store</param> </summary>
/// <returns></returns> ///
<param name="Body">Pet object that needs to be added to the store</param>
///
<returns></returns>
public async Task AddPetAsync (Pet Body) { public async Task AddPetAsync (Pet Body) {
@ -301,10 +424,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -325,11 +452,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Finds Pets by status Multiple status values can be provided with comma seperated strings /// Finds Pets by status Multiple status values can be provided with comma seperated strings
/// </summary> ///
/// <param name="Status">Status values that need to be considered for filter</param> </summary>
/// <returns>List<Pet></returns> ///
<param name="Status">Status values that need to be considered for filter</param>
///
<returns>List<Pet></returns>
public List<Pet> FindPetsByStatus (List<string> Status) { public List<Pet> FindPetsByStatus (List<string> Status) {
@ -338,10 +469,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
if (Status != null) queryParams.Add("status", apiClient.ParameterToString(Status)); // query parameter if (Status != null) queryParams.Add("status", apiClient.ParameterToString(Status)); // query parameter
@ -362,11 +497,15 @@ namespace IO.Swagger.Api {
return (List<Pet>) apiClient.Deserialize(response.Content, typeof(List<Pet>)); return (List<Pet>) apiClient.Deserialize(response.Content, typeof(List<Pet>));
} }
/// <summary> ///
<summary>
/// Finds Pets by status Multiple status values can be provided with comma seperated strings /// Finds Pets by status Multiple status values can be provided with comma seperated strings
/// </summary> ///
/// <param name="Status">Status values that need to be considered for filter</param> </summary>
/// <returns>List<Pet></returns> ///
<param name="Status">Status values that need to be considered for filter</param>
///
<returns>List<Pet></returns>
public async Task<List<Pet>> FindPetsByStatusAsync (List<string> Status) { public async Task<List<Pet>> FindPetsByStatusAsync (List<string> Status) {
@ -375,10 +514,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
if (Status != null) queryParams.Add("status", apiClient.ParameterToString(Status)); // query parameter if (Status != null) queryParams.Add("status", apiClient.ParameterToString(Status)); // query parameter
@ -398,11 +541,15 @@ namespace IO.Swagger.Api {
return (List<Pet>) ApiInvoker.Deserialize(response.Content, typeof(List<Pet>)); return (List<Pet>) ApiInvoker.Deserialize(response.Content, typeof(List<Pet>));
} }
/// <summary> ///
<summary>
/// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
/// </summary> ///
/// <param name="Tags">Tags to filter by</param> </summary>
/// <returns>List<Pet></returns> ///
<param name="Tags">Tags to filter by</param>
///
<returns>List<Pet></returns>
public List<Pet> FindPetsByTags (List<string> Tags) { public List<Pet> FindPetsByTags (List<string> Tags) {
@ -411,10 +558,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
if (Tags != null) queryParams.Add("tags", apiClient.ParameterToString(Tags)); // query parameter if (Tags != null) queryParams.Add("tags", apiClient.ParameterToString(Tags)); // query parameter
@ -435,11 +586,15 @@ namespace IO.Swagger.Api {
return (List<Pet>) apiClient.Deserialize(response.Content, typeof(List<Pet>)); return (List<Pet>) apiClient.Deserialize(response.Content, typeof(List<Pet>));
} }
/// <summary> ///
<summary>
/// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
/// </summary> ///
/// <param name="Tags">Tags to filter by</param> </summary>
/// <returns>List<Pet></returns> ///
<param name="Tags">Tags to filter by</param>
///
<returns>List<Pet></returns>
public async Task<List<Pet>> FindPetsByTagsAsync (List<string> Tags) { public async Task<List<Pet>> FindPetsByTagsAsync (List<string> Tags) {
@ -448,10 +603,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
if (Tags != null) queryParams.Add("tags", apiClient.ParameterToString(Tags)); // query parameter if (Tags != null) queryParams.Add("tags", apiClient.ParameterToString(Tags)); // query parameter
@ -471,11 +630,15 @@ namespace IO.Swagger.Api {
return (List<Pet>) ApiInvoker.Deserialize(response.Content, typeof(List<Pet>)); return (List<Pet>) ApiInvoker.Deserialize(response.Content, typeof(List<Pet>));
} }
/// <summary> ///
<summary>
/// Find pet by ID Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions /// Find pet by ID Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
/// </summary> ///
/// <param name="PetId">ID of pet that needs to be fetched</param> </summary>
/// <returns>Pet</returns> ///
<param name="PetId">ID of pet that needs to be fetched</param>
///
<returns>Pet</returns>
public Pet GetPetById (long? PetId) { public Pet GetPetById (long? PetId) {
@ -488,10 +651,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -511,11 +678,15 @@ namespace IO.Swagger.Api {
return (Pet) apiClient.Deserialize(response.Content, typeof(Pet)); return (Pet) apiClient.Deserialize(response.Content, typeof(Pet));
} }
/// <summary> ///
<summary>
/// Find pet by ID Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions /// Find pet by ID Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
/// </summary> ///
/// <param name="PetId">ID of pet that needs to be fetched</param> </summary>
/// <returns>Pet</returns> ///
<param name="PetId">ID of pet that needs to be fetched</param>
///
<returns>Pet</returns>
public async Task<Pet> GetPetByIdAsync (long? PetId) { public async Task<Pet> GetPetByIdAsync (long? PetId) {
@ -528,10 +699,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -550,11 +725,17 @@ namespace IO.Swagger.Api {
return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet));
} }
/// <summary> ///
<summary>
/// Updates a pet in the store with form data /// Updates a pet in the store with form data
/// </summary> ///
/// <param name="PetId">ID of pet that needs to be updated</param>/// <param name="Name">Updated name of the pet</param>/// <param name="Status">Updated status of the pet</param> </summary>
/// <returns></returns> ///
<param name="PetId">ID of pet that needs to be updated</param>///
<param name="Name">Updated name of the pet</param>///
<param name="Status">Updated status of the pet</param>
///
<returns></returns>
public void UpdatePetWithForm (string PetId, string Name, string Status) { public void UpdatePetWithForm (string PetId, string Name, string Status) {
@ -567,10 +748,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -593,11 +778,17 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Updates a pet in the store with form data /// Updates a pet in the store with form data
/// </summary> ///
/// <param name="PetId">ID of pet that needs to be updated</param>/// <param name="Name">Updated name of the pet</param>/// <param name="Status">Updated status of the pet</param> </summary>
/// <returns></returns> ///
<param name="PetId">ID of pet that needs to be updated</param>///
<param name="Name">Updated name of the pet</param>///
<param name="Status">Updated status of the pet</param>
///
<returns></returns>
public async Task UpdatePetWithFormAsync (string PetId, string Name, string Status) { public async Task UpdatePetWithFormAsync (string PetId, string Name, string Status) {
@ -610,10 +801,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -635,11 +830,16 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Deletes a pet /// Deletes a pet
/// </summary> ///
/// <param name="ApiKey"></param>/// <param name="PetId">Pet id to delete</param> </summary>
/// <returns></returns> ///
<param name="ApiKey"></param>///
<param name="PetId">Pet id to delete</param>
///
<returns></returns>
public void DeletePet (string ApiKey, long? PetId) { public void DeletePet (string ApiKey, long? PetId) {
@ -652,10 +852,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -677,11 +881,16 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Deletes a pet /// Deletes a pet
/// </summary> ///
/// <param name="ApiKey"></param>/// <param name="PetId">Pet id to delete</param> </summary>
/// <returns></returns> ///
<param name="ApiKey"></param>///
<param name="PetId">Pet id to delete</param>
///
<returns></returns>
public async Task DeletePetAsync (string ApiKey, long? PetId) { public async Task DeletePetAsync (string ApiKey, long? PetId) {
@ -694,10 +903,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -718,11 +931,17 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// uploads an image /// uploads an image
/// </summary> ///
/// <param name="PetId">ID of pet to update</param>/// <param name="AdditionalMetadata">Additional data to pass to server</param>/// <param name="File">file to upload</param> </summary>
/// <returns></returns> ///
<param name="PetId">ID of pet to update</param>///
<param name="AdditionalMetadata">Additional data to pass to server</param>///
<param name="File">file to upload</param>
///
<returns></returns>
public void UploadFile (long? PetId, string AdditionalMetadata, string File) { public void UploadFile (long? PetId, string AdditionalMetadata, string File) {
@ -735,10 +954,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -761,11 +984,17 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// uploads an image /// uploads an image
/// </summary> ///
/// <param name="PetId">ID of pet to update</param>/// <param name="AdditionalMetadata">Additional data to pass to server</param>/// <param name="File">file to upload</param> </summary>
/// <returns></returns> ///
<param name="PetId">ID of pet to update</param>///
<param name="AdditionalMetadata">Additional data to pass to server</param>///
<param name="File">file to upload</param>
///
<returns></returns>
public async Task UploadFileAsync (long? PetId, string AdditionalMetadata, string File) { public async Task UploadFileAsync (long? PetId, string AdditionalMetadata, string File) {
@ -778,10 +1007,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId)); path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -804,5 +1037,4 @@ namespace IO.Swagger.Api {
} }
} }
} }

View File

@ -7,77 +7,114 @@ using IO.Swagger.Model;
namespace IO.Swagger.Api { namespace IO.Swagger.Api {
public interface IStoreApi { public interface IStoreApi {
/// <summary> ///
<summary>
/// Returns pet inventories by status Returns a map of status codes to quantities /// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary> ///
</summary>
/// <returns>Dictionary<String, int?></returns> ///
<returns>Dictionary<String, int?></returns>
Dictionary<String, int?> GetInventory (); Dictionary<String, int?> GetInventory ();
/// <summary> ///
<summary>
/// Returns pet inventories by status Returns a map of status codes to quantities /// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary> ///
</summary>
/// <returns>Dictionary<String, int?></returns> ///
<returns>Dictionary<String, int?></returns>
Task<Dictionary<String, int?>> GetInventoryAsync (); Task<Dictionary<String, int?>> GetInventoryAsync ();
/// <summary> ///
<summary>
/// Place an order for a pet /// Place an order for a pet
/// </summary> ///
/// <param name="Body">order placed for purchasing the pet</param> </summary>
/// <returns>Order</returns> ///
<param name="Body">order placed for purchasing the pet</param>
///
<returns>Order</returns>
Order PlaceOrder (Order Body); Order PlaceOrder (Order Body);
/// <summary> ///
<summary>
/// Place an order for a pet /// Place an order for a pet
/// </summary> ///
/// <param name="Body">order placed for purchasing the pet</param> </summary>
/// <returns>Order</returns> ///
<param name="Body">order placed for purchasing the pet</param>
///
<returns>Order</returns>
Task<Order> PlaceOrderAsync (Order Body); Task<Order> PlaceOrderAsync (Order Body);
/// <summary> ///
<summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions /// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary> ///
/// <param name="OrderId">ID of pet that needs to be fetched</param> </summary>
/// <returns>Order</returns> ///
<param name="OrderId">ID of pet that needs to be fetched</param>
///
<returns>Order</returns>
Order GetOrderById (string OrderId); Order GetOrderById (string OrderId);
/// <summary> ///
<summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions /// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary> ///
/// <param name="OrderId">ID of pet that needs to be fetched</param> </summary>
/// <returns>Order</returns> ///
<param name="OrderId">ID of pet that needs to be fetched</param>
///
<returns>Order</returns>
Task<Order> GetOrderByIdAsync (string OrderId); Task<Order> GetOrderByIdAsync (string OrderId);
/// <summary> ///
<summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors /// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary> ///
/// <param name="OrderId">ID of the order that needs to be deleted</param> </summary>
/// <returns></returns> ///
<param name="OrderId">ID of the order that needs to be deleted</param>
///
<returns></returns>
void DeleteOrder (string OrderId); void DeleteOrder (string OrderId);
/// <summary> ///
<summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors /// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary> ///
/// <param name="OrderId">ID of the order that needs to be deleted</param> </summary>
/// <returns></returns> ///
<param name="OrderId">ID of the order that needs to be deleted</param>
///
<returns></returns>
Task DeleteOrderAsync (string OrderId); Task DeleteOrderAsync (string OrderId);
} }
/// <summary> ///
<summary>
/// Represents a collection of functions to interact with the API endpoints /// Represents a collection of functions to interact with the API endpoints
/// </summary> ///
</summary>
public class StoreApi : IStoreApi { public class StoreApi : IStoreApi {
/// <summary> ///
/// Initializes a new instance of the <see cref="StoreApi"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <param name="apiClient"> an instance of ApiClient (optional) <see cref="StoreApi"/>
/// <returns></returns> class.
///
</summary>
///
<param name="apiClient"> an instance of ApiClient (optional)
///
<returns></returns>
public StoreApi(ApiClient apiClient = null) { public StoreApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient; this.apiClient = Configuration.apiClient;
@ -86,44 +123,61 @@ namespace IO.Swagger.Api {
} }
} }
/// <summary> ///
/// Initializes a new instance of the <see cref="StoreApi"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <returns></returns> <see cref="StoreApi"/>
class.
///
</summary>
///
<returns></returns>
public StoreApi(String basePath) public StoreApi(String basePath)
{ {
this.apiClient = new ApiClient(basePath); this.apiClient = new ApiClient(basePath);
} }
/// <summary> ///
<summary>
/// Sets the base path of the API client. /// Sets the base path of the API client.
/// </summary> ///
/// <value>The base path</value> </summary>
///
<value>The base path</value>
public void SetBasePath(String basePath) { public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath; this.apiClient.basePath = basePath;
} }
/// <summary> ///
<summary>
/// Gets the base path of the API client. /// Gets the base path of the API client.
/// </summary> ///
/// <value>The base path</value> </summary>
///
<value>The base path</value>
public String GetBasePath(String basePath) { public String GetBasePath(String basePath) {
return this.apiClient.basePath; return this.apiClient.basePath;
} }
/// <summary> ///
<summary>
/// Gets or sets the API client. /// Gets or sets the API client.
/// </summary> ///
/// <value>The API client</value> </summary>
///
<value>The API client</value>
public ApiClient apiClient {get; set;} public ApiClient apiClient {get; set;}
/// <summary> ///
<summary>
/// Returns pet inventories by status Returns a map of status codes to quantities /// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary> ///
</summary>
/// <returns>Dictionary<String, int?></returns> ///
<returns>Dictionary<String, int?></returns>
public Dictionary<String, int?> GetInventory () { public Dictionary<String, int?> GetInventory () {
@ -132,10 +186,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -155,11 +213,14 @@ namespace IO.Swagger.Api {
return (Dictionary<String, int?>) apiClient.Deserialize(response.Content, typeof(Dictionary<String, int?>)); return (Dictionary<String, int?>) apiClient.Deserialize(response.Content, typeof(Dictionary<String, int?>));
} }
/// <summary> ///
<summary>
/// Returns pet inventories by status Returns a map of status codes to quantities /// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary> ///
</summary>
/// <returns>Dictionary<String, int?></returns> ///
<returns>Dictionary<String, int?></returns>
public async Task<Dictionary<String, int?>> GetInventoryAsync () { public async Task<Dictionary<String, int?>> GetInventoryAsync () {
@ -168,10 +229,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -190,11 +255,15 @@ namespace IO.Swagger.Api {
return (Dictionary<String, int?>) ApiInvoker.Deserialize(response.Content, typeof(Dictionary<String, int?>)); return (Dictionary<String, int?>) ApiInvoker.Deserialize(response.Content, typeof(Dictionary<String, int?>));
} }
/// <summary> ///
<summary>
/// Place an order for a pet /// Place an order for a pet
/// </summary> ///
/// <param name="Body">order placed for purchasing the pet</param> </summary>
/// <returns>Order</returns> ///
<param name="Body">order placed for purchasing the pet</param>
///
<returns>Order</returns>
public Order PlaceOrder (Order Body) { public Order PlaceOrder (Order Body) {
@ -203,10 +272,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -227,11 +300,15 @@ namespace IO.Swagger.Api {
return (Order) apiClient.Deserialize(response.Content, typeof(Order)); return (Order) apiClient.Deserialize(response.Content, typeof(Order));
} }
/// <summary> ///
<summary>
/// Place an order for a pet /// Place an order for a pet
/// </summary> ///
/// <param name="Body">order placed for purchasing the pet</param> </summary>
/// <returns>Order</returns> ///
<param name="Body">order placed for purchasing the pet</param>
///
<returns>Order</returns>
public async Task<Order> PlaceOrderAsync (Order Body) { public async Task<Order> PlaceOrderAsync (Order Body) {
@ -240,10 +317,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -263,11 +344,15 @@ namespace IO.Swagger.Api {
return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order));
} }
/// <summary> ///
<summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions /// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary> ///
/// <param name="OrderId">ID of pet that needs to be fetched</param> </summary>
/// <returns>Order</returns> ///
<param name="OrderId">ID of pet that needs to be fetched</param>
///
<returns>Order</returns>
public Order GetOrderById (string OrderId) { public Order GetOrderById (string OrderId) {
@ -280,10 +365,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -303,11 +392,15 @@ namespace IO.Swagger.Api {
return (Order) apiClient.Deserialize(response.Content, typeof(Order)); return (Order) apiClient.Deserialize(response.Content, typeof(Order));
} }
/// <summary> ///
<summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions /// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary> ///
/// <param name="OrderId">ID of pet that needs to be fetched</param> </summary>
/// <returns>Order</returns> ///
<param name="OrderId">ID of pet that needs to be fetched</param>
///
<returns>Order</returns>
public async Task<Order> GetOrderByIdAsync (string OrderId) { public async Task<Order> GetOrderByIdAsync (string OrderId) {
@ -320,10 +413,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -342,11 +439,15 @@ namespace IO.Swagger.Api {
return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order));
} }
/// <summary> ///
<summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors /// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary> ///
/// <param name="OrderId">ID of the order that needs to be deleted</param> </summary>
/// <returns></returns> ///
<param name="OrderId">ID of the order that needs to be deleted</param>
///
<returns></returns>
public void DeleteOrder (string OrderId) { public void DeleteOrder (string OrderId) {
@ -359,10 +460,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -383,11 +488,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors /// Delete purchase order by ID For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
/// </summary> ///
/// <param name="OrderId">ID of the order that needs to be deleted</param> </summary>
/// <returns></returns> ///
<param name="OrderId">ID of the order that needs to be deleted</param>
///
<returns></returns>
public async Task DeleteOrderAsync (string OrderId) { public async Task DeleteOrderAsync (string OrderId) {
@ -400,10 +509,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -424,5 +537,4 @@ namespace IO.Swagger.Api {
} }
} }
} }

View File

@ -7,133 +7,206 @@ using IO.Swagger.Model;
namespace IO.Swagger.Api { namespace IO.Swagger.Api {
public interface IUserApi { public interface IUserApi {
/// <summary> ///
<summary>
/// Create user This can only be done by the logged in user. /// Create user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Body">Created user object</param> </summary>
/// <returns></returns> ///
<param name="Body">Created user object</param>
///
<returns></returns>
void CreateUser (User Body); void CreateUser (User Body);
/// <summary> ///
<summary>
/// Create user This can only be done by the logged in user. /// Create user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Body">Created user object</param> </summary>
/// <returns></returns> ///
<param name="Body">Created user object</param>
///
<returns></returns>
Task CreateUserAsync (User Body); Task CreateUserAsync (User Body);
/// <summary> ///
<summary>
/// Creates list of users with given input array /// Creates list of users with given input array
/// </summary> ///
/// <param name="Body">List of user object</param> </summary>
/// <returns></returns> ///
<param name="Body">List of user object</param>
///
<returns></returns>
void CreateUsersWithArrayInput (List<User> Body); void CreateUsersWithArrayInput (List<User> Body);
/// <summary> ///
<summary>
/// Creates list of users with given input array /// Creates list of users with given input array
/// </summary> ///
/// <param name="Body">List of user object</param> </summary>
/// <returns></returns> ///
<param name="Body">List of user object</param>
///
<returns></returns>
Task CreateUsersWithArrayInputAsync (List<User> Body); Task CreateUsersWithArrayInputAsync (List<User> Body);
/// <summary> ///
<summary>
/// Creates list of users with given input array /// Creates list of users with given input array
/// </summary> ///
/// <param name="Body">List of user object</param> </summary>
/// <returns></returns> ///
<param name="Body">List of user object</param>
///
<returns></returns>
void CreateUsersWithListInput (List<User> Body); void CreateUsersWithListInput (List<User> Body);
/// <summary> ///
<summary>
/// Creates list of users with given input array /// Creates list of users with given input array
/// </summary> ///
/// <param name="Body">List of user object</param> </summary>
/// <returns></returns> ///
<param name="Body">List of user object</param>
///
<returns></returns>
Task CreateUsersWithListInputAsync (List<User> Body); Task CreateUsersWithListInputAsync (List<User> Body);
/// <summary> ///
<summary>
/// Logs user into the system /// Logs user into the system
/// </summary> ///
/// <param name="Username">The user name for login</param>/// <param name="Password">The password for login in clear text</param> </summary>
/// <returns>string</returns> ///
<param name="Username">The user name for login</param>///
<param name="Password">The password for login in clear text</param>
///
<returns>string</returns>
string LoginUser (string Username, string Password); string LoginUser (string Username, string Password);
/// <summary> ///
<summary>
/// Logs user into the system /// Logs user into the system
/// </summary> ///
/// <param name="Username">The user name for login</param>/// <param name="Password">The password for login in clear text</param> </summary>
/// <returns>string</returns> ///
<param name="Username">The user name for login</param>///
<param name="Password">The password for login in clear text</param>
///
<returns>string</returns>
Task<string> LoginUserAsync (string Username, string Password); Task<string> LoginUserAsync (string Username, string Password);
/// <summary> ///
<summary>
/// Logs out current logged in user session /// Logs out current logged in user session
/// </summary> ///
</summary>
/// <returns></returns> ///
<returns></returns>
void LogoutUser (); void LogoutUser ();
/// <summary> ///
<summary>
/// Logs out current logged in user session /// Logs out current logged in user session
/// </summary> ///
</summary>
/// <returns></returns> ///
<returns></returns>
Task LogoutUserAsync (); Task LogoutUserAsync ();
/// <summary> ///
<summary>
/// Get user by user name /// Get user by user name
/// </summary> ///
/// <param name="Username">The name that needs to be fetched. Use user1 for testing. </param> </summary>
/// <returns>User</returns> ///
<param name="Username">The name that needs to be fetched. Use user1 for testing. </param>
///
<returns>User</returns>
User GetUserByName (string Username); User GetUserByName (string Username);
/// <summary> ///
<summary>
/// Get user by user name /// Get user by user name
/// </summary> ///
/// <param name="Username">The name that needs to be fetched. Use user1 for testing. </param> </summary>
/// <returns>User</returns> ///
<param name="Username">The name that needs to be fetched. Use user1 for testing. </param>
///
<returns>User</returns>
Task<User> GetUserByNameAsync (string Username); Task<User> GetUserByNameAsync (string Username);
/// <summary> ///
<summary>
/// Updated user This can only be done by the logged in user. /// Updated user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Username">name that need to be deleted</param>/// <param name="Body">Updated user object</param> </summary>
/// <returns></returns> ///
<param name="Username">name that need to be deleted</param>///
<param name="Body">Updated user object</param>
///
<returns></returns>
void UpdateUser (string Username, User Body); void UpdateUser (string Username, User Body);
/// <summary> ///
<summary>
/// Updated user This can only be done by the logged in user. /// Updated user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Username">name that need to be deleted</param>/// <param name="Body">Updated user object</param> </summary>
/// <returns></returns> ///
<param name="Username">name that need to be deleted</param>///
<param name="Body">Updated user object</param>
///
<returns></returns>
Task UpdateUserAsync (string Username, User Body); Task UpdateUserAsync (string Username, User Body);
/// <summary> ///
<summary>
/// Delete user This can only be done by the logged in user. /// Delete user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Username">The name that needs to be deleted</param> </summary>
/// <returns></returns> ///
<param name="Username">The name that needs to be deleted</param>
///
<returns></returns>
void DeleteUser (string Username); void DeleteUser (string Username);
/// <summary> ///
<summary>
/// Delete user This can only be done by the logged in user. /// Delete user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Username">The name that needs to be deleted</param> </summary>
/// <returns></returns> ///
<param name="Username">The name that needs to be deleted</param>
///
<returns></returns>
Task DeleteUserAsync (string Username); Task DeleteUserAsync (string Username);
} }
/// <summary> ///
<summary>
/// Represents a collection of functions to interact with the API endpoints /// Represents a collection of functions to interact with the API endpoints
/// </summary> ///
</summary>
public class UserApi : IUserApi { public class UserApi : IUserApi {
/// <summary> ///
/// Initializes a new instance of the <see cref="UserApi"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <param name="apiClient"> an instance of ApiClient (optional) <see cref="UserApi"/>
/// <returns></returns> class.
///
</summary>
///
<param name="apiClient"> an instance of ApiClient (optional)
///
<returns></returns>
public UserApi(ApiClient apiClient = null) { public UserApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient; this.apiClient = Configuration.apiClient;
@ -142,44 +215,62 @@ namespace IO.Swagger.Api {
} }
} }
/// <summary> ///
/// Initializes a new instance of the <see cref="UserApi"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <returns></returns> <see cref="UserApi"/>
class.
///
</summary>
///
<returns></returns>
public UserApi(String basePath) public UserApi(String basePath)
{ {
this.apiClient = new ApiClient(basePath); this.apiClient = new ApiClient(basePath);
} }
/// <summary> ///
<summary>
/// Sets the base path of the API client. /// Sets the base path of the API client.
/// </summary> ///
/// <value>The base path</value> </summary>
///
<value>The base path</value>
public void SetBasePath(String basePath) { public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath; this.apiClient.basePath = basePath;
} }
/// <summary> ///
<summary>
/// Gets the base path of the API client. /// Gets the base path of the API client.
/// </summary> ///
/// <value>The base path</value> </summary>
///
<value>The base path</value>
public String GetBasePath(String basePath) { public String GetBasePath(String basePath) {
return this.apiClient.basePath; return this.apiClient.basePath;
} }
/// <summary> ///
<summary>
/// Gets or sets the API client. /// Gets or sets the API client.
/// </summary> ///
/// <value>The API client</value> </summary>
///
<value>The API client</value>
public ApiClient apiClient {get; set;} public ApiClient apiClient {get; set;}
/// <summary> ///
<summary>
/// Create user This can only be done by the logged in user. /// Create user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Body">Created user object</param> </summary>
/// <returns></returns> ///
<param name="Body">Created user object</param>
///
<returns></returns>
public void CreateUser (User Body) { public void CreateUser (User Body) {
@ -188,10 +279,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -213,11 +308,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Create user This can only be done by the logged in user. /// Create user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Body">Created user object</param> </summary>
/// <returns></returns> ///
<param name="Body">Created user object</param>
///
<returns></returns>
public async Task CreateUserAsync (User Body) { public async Task CreateUserAsync (User Body) {
@ -226,10 +325,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -250,11 +353,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Creates list of users with given input array /// Creates list of users with given input array
/// </summary> ///
/// <param name="Body">List of user object</param> </summary>
/// <returns></returns> ///
<param name="Body">List of user object</param>
///
<returns></returns>
public void CreateUsersWithArrayInput (List<User> Body) { public void CreateUsersWithArrayInput (List<User> Body) {
@ -263,10 +370,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -288,11 +399,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Creates list of users with given input array /// Creates list of users with given input array
/// </summary> ///
/// <param name="Body">List of user object</param> </summary>
/// <returns></returns> ///
<param name="Body">List of user object</param>
///
<returns></returns>
public async Task CreateUsersWithArrayInputAsync (List<User> Body) { public async Task CreateUsersWithArrayInputAsync (List<User> Body) {
@ -301,10 +416,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -325,11 +444,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Creates list of users with given input array /// Creates list of users with given input array
/// </summary> ///
/// <param name="Body">List of user object</param> </summary>
/// <returns></returns> ///
<param name="Body">List of user object</param>
///
<returns></returns>
public void CreateUsersWithListInput (List<User> Body) { public void CreateUsersWithListInput (List<User> Body) {
@ -338,10 +461,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -363,11 +490,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Creates list of users with given input array /// Creates list of users with given input array
/// </summary> ///
/// <param name="Body">List of user object</param> </summary>
/// <returns></returns> ///
<param name="Body">List of user object</param>
///
<returns></returns>
public async Task CreateUsersWithListInputAsync (List<User> Body) { public async Task CreateUsersWithListInputAsync (List<User> Body) {
@ -376,10 +507,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -400,11 +535,16 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Logs user into the system /// Logs user into the system
/// </summary> ///
/// <param name="Username">The user name for login</param>/// <param name="Password">The password for login in clear text</param> </summary>
/// <returns>string</returns> ///
<param name="Username">The user name for login</param>///
<param name="Password">The password for login in clear text</param>
///
<returns>string</returns>
public string LoginUser (string Username, string Password) { public string LoginUser (string Username, string Password) {
@ -413,10 +553,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
if (Username != null) queryParams.Add("username", apiClient.ParameterToString(Username)); // query parameter if (Username != null) queryParams.Add("username", apiClient.ParameterToString(Username)); // query parameter
@ -438,11 +582,16 @@ namespace IO.Swagger.Api {
return (string) apiClient.Deserialize(response.Content, typeof(string)); return (string) apiClient.Deserialize(response.Content, typeof(string));
} }
/// <summary> ///
<summary>
/// Logs user into the system /// Logs user into the system
/// </summary> ///
/// <param name="Username">The user name for login</param>/// <param name="Password">The password for login in clear text</param> </summary>
/// <returns>string</returns> ///
<param name="Username">The user name for login</param>///
<param name="Password">The password for login in clear text</param>
///
<returns>string</returns>
public async Task<string> LoginUserAsync (string Username, string Password) { public async Task<string> LoginUserAsync (string Username, string Password) {
@ -451,10 +600,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
if (Username != null) queryParams.Add("username", apiClient.ParameterToString(Username)); // query parameter if (Username != null) queryParams.Add("username", apiClient.ParameterToString(Username)); // query parameter
@ -475,11 +628,14 @@ namespace IO.Swagger.Api {
return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); return (string) ApiInvoker.Deserialize(response.Content, typeof(string));
} }
/// <summary> ///
<summary>
/// Logs out current logged in user session /// Logs out current logged in user session
/// </summary> ///
</summary>
/// <returns></returns> ///
<returns></returns>
public void LogoutUser () { public void LogoutUser () {
@ -488,10 +644,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -512,11 +672,14 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Logs out current logged in user session /// Logs out current logged in user session
/// </summary> ///
</summary>
/// <returns></returns> ///
<returns></returns>
public async Task LogoutUserAsync () { public async Task LogoutUserAsync () {
@ -525,10 +688,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -548,11 +715,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Get user by user name /// Get user by user name
/// </summary> ///
/// <param name="Username">The name that needs to be fetched. Use user1 for testing. </param> </summary>
/// <returns>User</returns> ///
<param name="Username">The name that needs to be fetched. Use user1 for testing. </param>
///
<returns>User</returns>
public User GetUserByName (string Username) { public User GetUserByName (string Username) {
@ -565,10 +736,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -588,11 +763,15 @@ namespace IO.Swagger.Api {
return (User) apiClient.Deserialize(response.Content, typeof(User)); return (User) apiClient.Deserialize(response.Content, typeof(User));
} }
/// <summary> ///
<summary>
/// Get user by user name /// Get user by user name
/// </summary> ///
/// <param name="Username">The name that needs to be fetched. Use user1 for testing. </param> </summary>
/// <returns>User</returns> ///
<param name="Username">The name that needs to be fetched. Use user1 for testing. </param>
///
<returns>User</returns>
public async Task<User> GetUserByNameAsync (string Username) { public async Task<User> GetUserByNameAsync (string Username) {
@ -605,10 +784,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -627,11 +810,16 @@ namespace IO.Swagger.Api {
return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); return (User) ApiInvoker.Deserialize(response.Content, typeof(User));
} }
/// <summary> ///
<summary>
/// Updated user This can only be done by the logged in user. /// Updated user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Username">name that need to be deleted</param>/// <param name="Body">Updated user object</param> </summary>
/// <returns></returns> ///
<param name="Username">name that need to be deleted</param>///
<param name="Body">Updated user object</param>
///
<returns></returns>
public void UpdateUser (string Username, User Body) { public void UpdateUser (string Username, User Body) {
@ -644,10 +832,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -669,11 +861,16 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Updated user This can only be done by the logged in user. /// Updated user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Username">name that need to be deleted</param>/// <param name="Body">Updated user object</param> </summary>
/// <returns></returns> ///
<param name="Username">name that need to be deleted</param>///
<param name="Body">Updated user object</param>
///
<returns></returns>
public async Task UpdateUserAsync (string Username, User Body) { public async Task UpdateUserAsync (string Username, User Body) {
@ -686,10 +883,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -710,11 +911,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Delete user This can only be done by the logged in user. /// Delete user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Username">The name that needs to be deleted</param> </summary>
/// <returns></returns> ///
<param name="Username">The name that needs to be deleted</param>
///
<returns></returns>
public void DeleteUser (string Username) { public void DeleteUser (string Username) {
@ -727,10 +932,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -751,11 +960,15 @@ namespace IO.Swagger.Api {
return; return;
} }
/// <summary> ///
<summary>
/// Delete user This can only be done by the logged in user. /// Delete user This can only be done by the logged in user.
/// </summary> ///
/// <param name="Username">The name that needs to be deleted</param> </summary>
/// <returns></returns> ///
<param name="Username">The name that needs to be deleted</param>
///
<returns></returns>
public async Task DeleteUserAsync (string Username) { public async Task DeleteUserAsync (string Username) {
@ -768,10 +981,14 @@ namespace IO.Swagger.Api {
path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username)); path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username));
var queryParams = new Dictionary<String, String>(); var queryParams = new Dictionary
var headerParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary<String, String>(); var headerParams = new Dictionary
var fileParams = new Dictionary<String, String>(); <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null; String postBody = null;
@ -792,5 +1009,4 @@ namespace IO.Swagger.Api {
} }
} }
} }

View File

@ -5,11 +5,14 @@ using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary> namespace IO.Swagger.Model {
/// ///
/// </summary> <summary>
///
///
</summary>
[DataContract] [DataContract]
public class Category { public class Category {
@ -24,10 +27,13 @@ namespace IO.Swagger.Model {
/// <summary> ///
<summary>
/// Get the string presentation of the object /// Get the string presentation of the object
/// </summary> ///
/// <returns>String presentation of the object</returns> </summary>
///
<returns>String presentation of the object</returns>
public override string ToString() { public override string ToString() {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class Category {\n"); sb.Append("class Category {\n");
@ -40,15 +46,17 @@ namespace IO.Swagger.Model {
return sb.ToString(); return sb.ToString();
} }
/// <summary> ///
<summary>
/// Get the JSON string presentation of the object /// Get the JSON string presentation of the object
/// </summary> ///
/// <returns>JSON string presentation of the object</returns> </summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() { public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented); return JsonConvert.SerializeObject(this, Formatting.Indented);
} }
} }
} }

View File

@ -5,11 +5,14 @@ using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary> namespace IO.Swagger.Model {
/// ///
/// </summary> <summary>
///
///
</summary>
[DataContract] [DataContract]
public class Order { public class Order {
@ -44,10 +47,13 @@ namespace IO.Swagger.Model {
/// <summary> ///
<summary>
/// Get the string presentation of the object /// Get the string presentation of the object
/// </summary> ///
/// <returns>String presentation of the object</returns> </summary>
///
<returns>String presentation of the object</returns>
public override string ToString() { public override string ToString() {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class Order {\n"); sb.Append("class Order {\n");
@ -68,15 +74,17 @@ namespace IO.Swagger.Model {
return sb.ToString(); return sb.ToString();
} }
/// <summary> ///
<summary>
/// Get the JSON string presentation of the object /// Get the JSON string presentation of the object
/// </summary> ///
/// <returns>JSON string presentation of the object</returns> </summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() { public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented); return JsonConvert.SerializeObject(this, Formatting.Indented);
} }
} }
} }

View File

@ -5,11 +5,14 @@ using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary> namespace IO.Swagger.Model {
/// ///
/// </summary> <summary>
///
///
</summary>
[DataContract] [DataContract]
public class Pet { public class Pet {
@ -44,10 +47,13 @@ namespace IO.Swagger.Model {
/// <summary> ///
<summary>
/// Get the string presentation of the object /// Get the string presentation of the object
/// </summary> ///
/// <returns>String presentation of the object</returns> </summary>
///
<returns>String presentation of the object</returns>
public override string ToString() { public override string ToString() {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class Pet {\n"); sb.Append("class Pet {\n");
@ -68,15 +74,17 @@ namespace IO.Swagger.Model {
return sb.ToString(); return sb.ToString();
} }
/// <summary> ///
<summary>
/// Get the JSON string presentation of the object /// Get the JSON string presentation of the object
/// </summary> ///
/// <returns>JSON string presentation of the object</returns> </summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() { public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented); return JsonConvert.SerializeObject(this, Formatting.Indented);
} }
} }
} }

View File

@ -5,11 +5,14 @@ using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary> namespace IO.Swagger.Model {
/// ///
/// </summary> <summary>
///
///
</summary>
[DataContract] [DataContract]
public class Tag { public class Tag {
@ -24,10 +27,13 @@ namespace IO.Swagger.Model {
/// <summary> ///
<summary>
/// Get the string presentation of the object /// Get the string presentation of the object
/// </summary> ///
/// <returns>String presentation of the object</returns> </summary>
///
<returns>String presentation of the object</returns>
public override string ToString() { public override string ToString() {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class Tag {\n"); sb.Append("class Tag {\n");
@ -40,15 +46,17 @@ namespace IO.Swagger.Model {
return sb.ToString(); return sb.ToString();
} }
/// <summary> ///
<summary>
/// Get the JSON string presentation of the object /// Get the JSON string presentation of the object
/// </summary> ///
/// <returns>JSON string presentation of the object</returns> </summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() { public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented); return JsonConvert.SerializeObject(this, Formatting.Indented);
} }
} }
} }

View File

@ -5,11 +5,14 @@ using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary> namespace IO.Swagger.Model {
/// ///
/// </summary> <summary>
///
///
</summary>
[DataContract] [DataContract]
public class User { public class User {
@ -54,10 +57,13 @@ namespace IO.Swagger.Model {
/// <summary> ///
<summary>
/// Get the string presentation of the object /// Get the string presentation of the object
/// </summary> ///
/// <returns>String presentation of the object</returns> </summary>
///
<returns>String presentation of the object</returns>
public override string ToString() { public override string ToString() {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append("class User {\n"); sb.Append("class User {\n");
@ -82,15 +88,17 @@ namespace IO.Swagger.Model {
return sb.ToString(); return sb.ToString();
} }
/// <summary> ///
<summary>
/// Get the JSON string presentation of the object /// Get the JSON string presentation of the object
/// </summary> ///
/// <returns>JSON string presentation of the object</returns> </summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() { public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented); return JsonConvert.SerializeObject(this, Formatting.Indented);
} }
} }
} }

View File

@ -9,68 +9,106 @@ using Newtonsoft.Json;
using RestSharp; using RestSharp;
namespace IO.Swagger.Client { namespace IO.Swagger.Client {
/// <summary> ///
<summary>
/// API client is mainly responible for making the HTTP call to the API backend /// API client is mainly responible for making the HTTP call to the API backend
/// </summary> ///
public class ApiClient { </summary>
public class ApiClient {
/// <summary> ///
/// Initializes a new instance of the <see cref="ApiClient"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <param name="basePath">The base path.</param> <see cref="ApiClient"/>
public ApiClient(String basePath="http://petstore.swagger.io/v2") { class.
this.basePath = basePath; ///
this.restClient = new RestClient(this.basePath); </summary>
} ///
<param name="basePath">The base path.</param>
public ApiClient(String basePath="http://petstore.swagger.io/v2") {
this.basePath = basePath;
this.restClient = new RestClient(this.basePath);
}
/// <summary> ///
<summary>
/// Gets or sets the base path. /// Gets or sets the base path.
/// </summary> ///
/// <value>The base path.</value> </summary>
public string basePath { get; set; } ///
<value>The base path.</value>
public string basePath { get; set; }
/// <summary> ///
<summary>
/// Gets or sets the RestClient /// Gets or sets the RestClient
/// </summary> ///
/// <value>The RestClient.</value> </summary>
public RestClient restClient { get; set; } ///
<value>The RestClient.</value>
public RestClient restClient { get; set; }
private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>(); private Dictionary
<String, String> defaultHeaderMap = new Dictionary
<String, String>();
public Object CallApi(String Path, RestSharp.Method Method, Dictionary<String, String> QueryParams, String PostBody, public Object CallApi(String Path, RestSharp.Method Method, Dictionary
Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) { <String, String> QueryParams, String PostBody,
var response = Task.Run(async () => { Dictionary
var resp = await CallApiAsync(Path, Method, QueryParams, PostBody, HeaderParams, FormParams, FileParams, AuthSettings); <String, String> HeaderParams, Dictionary
return resp; <String, String> FormParams, Dictionary
}); <String, String> FileParams, String[] AuthSettings) {
return response.Result; var response = Task.Run(async () => {
} var resp = await CallApiAsync(Path, Method, QueryParams, PostBody, HeaderParams, FormParams, FileParams, AuthSettings);
return resp;
});
return response.Result;
}
public async Task<Object> CallApiAsync(String Path, RestSharp.Method Method, Dictionary<String, String> QueryParams, String PostBody, public async Task
Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) { <Object> CallApiAsync(String Path, RestSharp.Method Method, Dictionary
<String
, String> QueryParams, String PostBody,
Dictionary
<String
, String> HeaderParams, Dictionary
<String
, String> FormParams, Dictionary
<String
, String> FileParams, String[] AuthSettings) {
var request = new RestRequest(Path, Method); var request = new RestRequest(Path, Method);
UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings); UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings);
// add default header, if any // add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in this.defaultHeaderMap) foreach(KeyValuePair
<string
, string> defaultHeader in this.defaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value); request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any // add header parameter, if any
foreach(KeyValuePair<string, string> param in HeaderParams) foreach(KeyValuePair
<string
, string> param in HeaderParams)
request.AddHeader(param.Key, param.Value); request.AddHeader(param.Key, param.Value);
// add query parameter, if any // add query parameter, if any
foreach(KeyValuePair<string, string> param in QueryParams) foreach(KeyValuePair
<string
, string> param in QueryParams)
request.AddQueryParameter(param.Key, param.Value); request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any // add form parameter, if any
foreach(KeyValuePair<string, string> param in FormParams) foreach(KeyValuePair
<string
, string> param in FormParams)
request.AddParameter(param.Key, param.Value); request.AddParameter(param.Key, param.Value);
// add file parameter, if any // add file parameter, if any
foreach(KeyValuePair<string, string> param in FileParams) foreach(KeyValuePair
<string
, string> param in FileParams)
request.AddFile(param.Key, param.Value); request.AddFile(param.Key, param.Value);
if (PostBody != null) { if (PostBody != null) {
@ -81,57 +119,88 @@ namespace IO.Swagger.Client {
} }
/// <summary> ///
<summary>
/// Add default header /// Add default header
/// </summary> ///
/// <param name="key"> Header field name </summary>
/// <param name="value"> Header field value ///
/// <returns></returns> <param name="key">
Header field name
///
<param name="value">
Header field value
///
<returns></returns>
public void AddDefaultHeader(string key, string value) { public void AddDefaultHeader(string key, string value) {
defaultHeaderMap.Add(key, value); defaultHeaderMap.Add(key, value);
} }
/// <summary> ///
<summary>
/// Get default header /// Get default header
/// </summary> ///
/// <returns>Dictionary of default header</returns> </summary>
public Dictionary<String, String> GetDefaultHeader() { ///
<returns>Dictionary of default header</returns>
public Dictionary
<String
, String> GetDefaultHeader() {
return defaultHeaderMap; return defaultHeaderMap;
} }
/// <summary> ///
<summary>
/// escape string (url-encoded) /// escape string (url-encoded)
/// </summary> ///
/// <param name="str"> String to be escaped </summary>
/// <returns>Escaped string</returns> ///
<param name="str">
String to be escaped
///
<returns>Escaped string</returns>
public string EscapeString(string str) { public string EscapeString(string str) {
return str; return str;
} }
/// <summary> ///
<summary>
/// if parameter is DateTime, output in ISO8601 format /// if parameter is DateTime, output in ISO8601 format
/// if parameter is a list of string, join the list with "," /// if parameter is a list of string, join the list with ","
/// otherwise just return the string /// otherwise just return the string
/// </summary> ///
/// <param name="obj"> The parameter (header, path, query, form) </summary>
/// <returns>Formatted string</returns> ///
<param name="obj">
The parameter (header, path, query, form)
///
<returns>Formatted string</returns>
public string ParameterToString(object obj) public string ParameterToString(object obj)
{ {
if (obj is DateTime) { if (obj is DateTime) {
return ((DateTime)obj).ToString ("u"); return ((DateTime)obj).ToString ("u");
} else if (obj is List<string>) { } else if (obj is List
return String.Join(",", obj as List<string>); <string>) {
return String.Join(",", obj as List
<string>);
} else { } else {
return Convert.ToString (obj); return Convert.ToString (obj);
} }
} }
/// <summary> ///
<summary>
/// Deserialize the JSON string into a proper object /// Deserialize the JSON string into a proper object
/// </summary> ///
/// <param name="json"> JSON string </summary>
/// <param name="type"> Object type ///
/// <returns>Object representation of the JSON string</returns> <param name="json">
JSON string
///
<param name="type">
Object type
///
<returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type) { public object Deserialize(string content, Type type) {
if (type.GetType() == typeof(Object)) if (type.GetType() == typeof(Object))
return (Object)content; return (Object)content;
@ -145,11 +214,16 @@ namespace IO.Swagger.Client {
} }
} }
/// <summary> ///
<summary>
/// Serialize an object into JSON string /// Serialize an object into JSON string
/// </summary> ///
/// <param name="obj"> Object </summary>
/// <returns>JSON string</returns> ///
<param name="obj">
Object
///
<returns>JSON string</returns>
public string Serialize(object obj) { public string Serialize(object obj) {
try try
{ {
@ -160,11 +234,16 @@ namespace IO.Swagger.Client {
} }
} }
/// <summary> ///
<summary>
/// Get the API key with prefix /// Get the API key with prefix
/// </summary> ///
/// <param name="obj"> Object </summary>
/// <returns>API key with prefix</returns> ///
<param name="obj">
Object
///
<returns>API key with prefix</returns>
public string GetApiKeyWithPrefix (string apiKey) public string GetApiKeyWithPrefix (string apiKey)
{ {
var apiKeyValue = ""; var apiKeyValue = "";
@ -177,13 +256,25 @@ namespace IO.Swagger.Client {
} }
} }
/// <summary> ///
<summary>
/// Update parameters based on authentication /// Update parameters based on authentication
/// </summary> ///
/// <param name="QueryParams">Query parameters</param> </summary>
/// <param name="HeaderParams">Header parameters</param> ///
/// <param name="AuthSettings">Authentication settings</param> <param name="QueryParams">
public void UpdateParamsForAuth(Dictionary<String, String> QueryParams, Dictionary<String, String> HeaderParams, string[] AuthSettings) { Query parameters</param>
///
<param name="HeaderParams">
Header parameters</param>
///
<param name="AuthSettings">
Authentication settings</param>
public void UpdateParamsForAuth(Dictionary
<String
, String> QueryParams, Dictionary
<String
, String> HeaderParams, string[] AuthSettings) {
if (AuthSettings == null || AuthSettings.Length == 0) if (AuthSettings == null || AuthSettings.Length == 0)
return; return;
@ -192,7 +283,8 @@ namespace IO.Swagger.Client {
switch(auth) { switch(auth) {
case "api_key": case "api_key":
HeaderParams["api_key"] = GetApiKeyWithPrefix("api_key"); HeaderParams["api_key"] = GetApiKeyWithPrefix("api_key
");
break; break;
@ -209,14 +301,18 @@ namespace IO.Swagger.Client {
} }
/// <summary> ///
<summary>
/// Encode string in base64 format /// Encode string in base64 format
/// </summary> ///
/// <param name="text">String to be encoded</param> </summary>
///
<param name="text">
String to be encoded</param>
public static string Base64Encode(string text) { public static string Base64Encode(string text) {
var textByte = System.Text.Encoding.UTF8.GetBytes(text); var textByte = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(textByte); return System.Convert.ToBase64String(textByte);
} }
} }
} }

View File

@ -1,42 +1,61 @@
using System; using System;
namespace IO.Swagger.Client { namespace IO.Swagger.Client {
/// <summary> ///
<summary>
/// API Exception /// API Exception
/// </summary> ///
public class ApiException : Exception { </summary>
/// <summary> public class ApiException : Exception {
///
<summary>
/// Gets or sets the error code (HTTP status code) /// Gets or sets the error code (HTTP status code)
/// </summary> ///
/// <value>The error code (HTTP status code).</value> </summary>
public int ErrorCode { get; set; } ///
<value>The error code (HTTP status code).</value>
public int ErrorCode { get; set; }
/// <summary> ///
<summary>
/// Gets or sets the error content (body json object) /// Gets or sets the error content (body json object)
/// </summary> ///
/// <value>The error content (Http response body).</value> </summary>
public dynamic ErrorContent { get; private set; } ///
<value>The error content (Http response body).</value>
public dynamic ErrorContent { get; private set; }
/// <summary> ///
/// Initializes a new instance of the <see cref="ApiException"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <param name="basePath">The base path.</param> <see cref="ApiException"/>
public ApiException() {} class.
///
</summary>
///
<param name="basePath">The base path.</param>
public ApiException() {}
/// <summary> ///
/// Initializes a new instance of the <see cref="ApiException"/> class. <summary>
/// </summary> /// Initializes a new instance of the
/// <param name="errorCode">HTTP status code.</param> <see cref="ApiException"/>
/// <param name="message">Error message.</param> class.
public ApiException(int errorCode, string message) : base(message) { ///
this.ErrorCode = errorCode; </summary>
} ///
<param name="errorCode">HTTP status code.</param>
///
<param name="message">Error message.</param>
public ApiException(int errorCode, string message) : base(message) {
this.ErrorCode = errorCode;
}
public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) { public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) {
this.ErrorCode = errorCode; this.ErrorCode = errorCode;
this.ErrorContent = errorContent; this.ErrorContent = errorContent;
} }
} }
} }

View File

@ -7,41 +7,62 @@ using System.Text;
using IO.Swagger.Client; using IO.Swagger.Client;
namespace IO.Swagger.Client { namespace IO.Swagger.Client {
/// <summary> ///
<summary>
/// Represents a set of configuration settings /// Represents a set of configuration settings
/// </summary> ///
public class Configuration{ </summary>
public class Configuration{
/// <summary> ///
<summary>
/// Gets or sets the API client. This is the default API client for making HTTP calls. /// Gets or sets the API client. This is the default API client for making HTTP calls.
/// </summary> ///
/// <value>The API client.</value> </summary>
public static ApiClient apiClient = new ApiClient(); ///
<value>The API client.</value>
public static ApiClient apiClient = new ApiClient();
/// <summary> ///
<summary>
/// Gets or sets the username (HTTP basic authentication) /// Gets or sets the username (HTTP basic authentication)
/// </summary> ///
/// <value>The username.</value> </summary>
public static String username { get; set; } ///
<value>The username.</value>
public static String username { get; set; }
/// <summary> ///
<summary>
/// Gets or sets the password (HTTP basic authentication) /// Gets or sets the password (HTTP basic authentication)
/// </summary> ///
/// <value>The password.</value> </summary>
public static String password { get; set; } ///
<value>The password.</value>
public static String password { get; set; }
/// <summary> ///
<summary>
/// Gets or sets the API key based on the authentication name /// Gets or sets the API key based on the authentication name
/// </summary> ///
/// <value>The API key.</value> </summary>
public static Dictionary<String, String> apiKey = new Dictionary<String, String>(); ///
<value>The API key.</value>
public static Dictionary
<String, String> apiKey = new Dictionary
<String, String>();
/// <summary> ///
<summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name
/// </summary> ///
/// <value>The prefix of the API key.</value> </summary>
public static Dictionary<String, String> apiKeyPrefix = new Dictionary<String, String>(); ///
<value>The prefix of the API key.</value>
public static Dictionary
<String, String> apiKeyPrefix = new Dictionary
<String, String>();
} }
} }

View File

@ -1,15 +1,21 @@
#import <Foundation/Foundation.h> #import
<Foundation/Foundation.h>
#import "SWGObject.h" #import "SWGObject.h"
@protocol SWGCategory
@end
@interface SWGCategory : SWGObject @protocol SWGCategory
@end
@interface SWGCategory : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSString* name; @property(nonatomic) NSNumber* _id;
@property(nonatomic) NSString* name;
@end
@end

View File

@ -1,14 +1,15 @@
#import "SWGCategory.h"
@implementation SWGCategory #import "SWGCategory.h"
+ (JSONKeyMapper *)keyMapper @implementation SWGCategory
{
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }];
} }
+ (BOOL)propertyIsOptional:(NSString *)propertyName + (BOOL)propertyIsOptional:(NSString *)propertyName
{ {
NSArray *optionalProperties = @[@"_id", @"name"]; NSArray *optionalProperties = @[@"_id", @"name"];
if ([optionalProperties containsObject:propertyName]) { if ([optionalProperties containsObject:propertyName]) {
@ -17,6 +18,7 @@
else { else {
return NO; return NO;
} }
} }
@end
@end

View File

@ -1,56 +1,57 @@
#import <Foundation/Foundation.h> #import
<Foundation/Foundation.h>
@interface SWGConfiguration : NSObject @interface SWGConfiguration : NSObject
/** /**
* Api key values for Api Key type Authentication * Api key values for Api Key type Authentication
* *
* To add or remove api key, use `setValue:forApiKeyField:`. * To add or remove api key, use `setValue:forApiKeyField:`.
*/ */
@property (readonly, nonatomic, strong) NSDictionary *apiKey; @property (readonly, nonatomic, strong) NSDictionary *apiKey;
/** /**
* Api key prefix values to be prepend to the respective api key * Api key prefix values to be prepend to the respective api key
* *
* To add or remove prefix, use `setValue:forApiKeyPrefixField:`. * To add or remove prefix, use `setValue:forApiKeyPrefixField:`.
*/ */
@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; @property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix;
/** /**
* Usename and Password for Basic type Authentication * Usename and Password for Basic type Authentication
*/ */
@property (nonatomic) NSString *username; @property (nonatomic) NSString *username;
@property (nonatomic) NSString *password; @property (nonatomic) NSString *password;
/** /**
* Get configuration singleton instance * Get configuration singleton instance
*/ */
+ (instancetype) sharedConfig; + (instancetype) sharedConfig;
/** /**
* Sets field in `apiKey` * Sets field in `apiKey`
*/ */
- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; - (void) setValue:(NSString *)value forApiKeyField:(NSString*)field;
/** /**
* Sets field in `apiKeyPrefix` * Sets field in `apiKeyPrefix`
*/ */
- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; - (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field;
/** /**
* Get API key (with prefix if set) * Get API key (with prefix if set)
*/ */
- (NSString *) getApiKeyWithPrefix:(NSString *) key; - (NSString *) getApiKeyWithPrefix:(NSString *) key;
/** /**
* Get Basic Auth token * Get Basic Auth token
*/ */
- (NSString *) getBasicAuthToken; - (NSString *) getBasicAuthToken;
/** /**
* Get Authentication Setings * Get Authentication Setings
*/ */
- (NSDictionary *) authSettings; - (NSDictionary *) authSettings;
@end @end

View File

@ -12,73 +12,73 @@
#pragma mark - Singletion Methods #pragma mark - Singletion Methods
+ (instancetype) sharedConfig { + (instancetype) sharedConfig {
static SWGConfiguration *shardConfig = nil; static SWGConfiguration *shardConfig = nil;
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ dispatch_once(&onceToken, ^{
shardConfig = [[self alloc] init]; shardConfig = [[self alloc] init];
}); });
return shardConfig; return shardConfig;
} }
#pragma mark - Initialize Methods #pragma mark - Initialize Methods
- (instancetype) init { - (instancetype) init {
self = [super init]; self = [super init];
if (self) { if (self) {
self.username = @""; self.username = @"";
self.password = @""; self.password = @"";
self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKey = [NSMutableDictionary dictionary];
self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
#pragma mark - Instance Methods #pragma mark - Instance Methods
- (NSString *) getApiKeyWithPrefix:(NSString *)key { - (NSString *) getApiKeyWithPrefix:(NSString *)key {
if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) { if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) {
return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]];
} }
else if ([self.apiKey objectForKey:key]) { else if ([self.apiKey objectForKey:key]) {
return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]];
} }
else { else {
return @""; return @"";
} }
} }
- (NSString *) getBasicAuthToken { - (NSString *) getBasicAuthToken {
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password];
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
return basicAuthCredentials; return basicAuthCredentials;
} }
#pragma mark - Setter Methods #pragma mark - Setter Methods
- (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { - (void) setValue:(NSString *)value forApiKeyField:(NSString *)field {
[self.mutableApiKey setValue:value forKey:field]; [self.mutableApiKey setValue:value forKey:field];
} }
- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { - (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field {
[self.mutableApiKeyPrefix setValue:value forKey:field]; [self.mutableApiKeyPrefix setValue:value forKey:field];
} }
#pragma mark - Getter Methods #pragma mark - Getter Methods
- (NSDictionary *) apiKey { - (NSDictionary *) apiKey {
return [NSDictionary dictionaryWithDictionary:self.mutableApiKey]; return [NSDictionary dictionaryWithDictionary:self.mutableApiKey];
} }
- (NSDictionary *) apiKeyPrefix { - (NSDictionary *) apiKeyPrefix {
return [NSDictionary dictionaryWithDictionary:self.mutableApiKeyPrefix]; return [NSDictionary dictionaryWithDictionary:self.mutableApiKeyPrefix];
} }
#pragma mark - #pragma mark -
- (NSDictionary *) authSettings { - (NSDictionary *) authSettings {
return @{ return @{
@"api_key": @{ @"api_key": @{
@"type": @"api_key", @"type": @"api_key",
@"in": @"header", @"in": @"header",
@ -86,7 +86,7 @@
@"value": [self getApiKeyWithPrefix:@"api_key"] @"value": [self getApiKeyWithPrefix:@"api_key"]
}, },
}; };
} }
@end @end

View File

@ -1,24 +1,34 @@
#import <Foundation/Foundation.h> #import
<Foundation/Foundation.h>
#import "SWGObject.h" #import "SWGObject.h"
@protocol SWGOrder
@end
@interface SWGOrder : SWGObject @protocol SWGOrder
@end
@interface SWGOrder : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* petId; @property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* quantity;
@property(nonatomic) NSDate* shipDate; @property(nonatomic) NSNumber* petId;
/* Order Status [optional]
@property(nonatomic) NSNumber* quantity;
@property(nonatomic) NSDate* shipDate;
/* Order Status [optional]
*/ */
@property(nonatomic) NSString* status; @property(nonatomic) NSString* status;
@property(nonatomic) BOOL complete;
@end @property(nonatomic) BOOL complete;
@end

View File

@ -1,14 +1,15 @@
#import "SWGOrder.h"
@implementation SWGOrder #import "SWGOrder.h"
+ (JSONKeyMapper *)keyMapper @implementation SWGOrder
{
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }];
} }
+ (BOOL)propertyIsOptional:(NSString *)propertyName + (BOOL)propertyIsOptional:(NSString *)propertyName
{ {
NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"]; NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"];
if ([optionalProperties containsObject:propertyName]) { if ([optionalProperties containsObject:propertyName]) {
@ -17,6 +18,7 @@
else { else {
return NO; return NO;
} }
} }
@end
@end

View File

@ -1,26 +1,36 @@
#import <Foundation/Foundation.h> #import
<Foundation/Foundation.h>
#import "SWGObject.h" #import "SWGObject.h"
#import "SWGTag.h" #import "SWGTag.h"
#import "SWGCategory.h" #import "SWGCategory.h"
@protocol SWGPet
@end
@interface SWGPet : SWGObject @protocol SWGPet
@end
@interface SWGPet : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) SWGCategory* category; @property(nonatomic) NSNumber* _id;
@property(nonatomic) NSString* name;
@property(nonatomic) NSArray* photoUrls; @property(nonatomic) SWGCategory* category;
@property(nonatomic) NSArray<SWGTag>* tags;
/* pet status in the store [optional] @property(nonatomic) NSString* name;
@property(nonatomic) NSArray* photoUrls;
@property(nonatomic) NSArray<SWGTag>* tags;
/* pet status in the store [optional]
*/ */
@property(nonatomic) NSString* status; @property(nonatomic) NSString* status;
@end
@end

View File

@ -1,14 +1,15 @@
#import "SWGPet.h"
@implementation SWGPet #import "SWGPet.h"
+ (JSONKeyMapper *)keyMapper @implementation SWGPet
{
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }]; return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }];
} }
+ (BOOL)propertyIsOptional:(NSString *)propertyName + (BOOL)propertyIsOptional:(NSString *)propertyName
{ {
NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"]; NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"];
if ([optionalProperties containsObject:propertyName]) { if ([optionalProperties containsObject:propertyName]) {
@ -17,6 +18,7 @@
else { else {
return NO; return NO;
} }
} }
@end
@end

View File

@ -1,21 +1,23 @@
#import <Foundation/Foundation.h> #import
<Foundation/Foundation.h>
#import "SWGPet.h" #import "SWGPet.h"
#import "SWGFile.h" #import "SWGFile.h"
#import "SWGObject.h" #import "SWGObject.h"
#import "SWGApiClient.h" #import "SWGApiClient.h"
@interface SWGPetApi: NSObject @interface SWGPetApi: NSObject
@property(nonatomic, assign)SWGApiClient *apiClient; @property(nonatomic, assign)SWGApiClient *apiClient;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key; -(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize; -(unsigned long) requestQueueSize;
+(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath; +(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath; +(NSString*) getBasePath;
/**
/**
Update an existing pet Update an existing pet
@ -25,13 +27,14 @@
return type: return type:
*/ */
-(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body -(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;
/**
/**
Add a new pet to the store Add a new pet to the store
@ -41,13 +44,14 @@
return type: return type:
*/ */
-(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body -(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;
/**
/**
Finds Pets by status Finds Pets by status
Multiple status values can be provided with comma seperated strings Multiple status values can be provided with comma seperated strings
@ -57,13 +61,14 @@
return type: NSArray<SWGPet>* return type: NSArray<SWGPet>*
*/ */
-(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status -(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock; completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock;
/**
/**
Finds Pets by tags Finds Pets by tags
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
@ -73,13 +78,14 @@
return type: NSArray<SWGPet>* return type: NSArray<SWGPet>*
*/ */
-(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags -(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock; completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock;
/**
/**
Find pet by ID Find pet by ID
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
@ -89,13 +95,14 @@
return type: SWGPet* return type: SWGPet*
*/ */
-(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId -(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock; completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock;
/**
/**
Updates a pet in the store with form data Updates a pet in the store with form data
@ -107,7 +114,7 @@
return type: return type:
*/ */
-(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId -(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId
name:(NSString*) name name:(NSString*) name
status:(NSString*) status status:(NSString*) status
@ -115,7 +122,8 @@
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;
/**
/**
Deletes a pet Deletes a pet
@ -126,14 +134,15 @@
return type: return type:
*/ */
-(NSNumber*) deletePetWithCompletionBlock :(NSString*) apiKey -(NSNumber*) deletePetWithCompletionBlock :(NSString*) apiKey
petId:(NSNumber*) petId petId:(NSNumber*) petId
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;
/**
/**
uploads an image uploads an image
@ -145,7 +154,7 @@
return type: return type:
*/ */
-(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId -(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId
additionalMetadata:(NSString*) additionalMetadata additionalMetadata:(NSString*) additionalMetadata
file:(SWGFile*) file file:(SWGFile*) file
@ -154,4 +163,5 @@
@end @end

View File

@ -1,30 +1,31 @@
#import "SWGPetApi.h" #import "SWGPetApi.h"
#import "SWGFile.h" #import "SWGFile.h"
#import "SWGQueryParamCollection.h" #import "SWGQueryParamCollection.h"
#import "SWGPet.h" #import "SWGPet.h"
#import "SWGFile.h" #import "SWGFile.h"
@interface SWGPetApi ()
@interface SWGPetApi ()
@property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; @property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders;
@end @end
@implementation SWGPetApi @implementation SWGPetApi
static NSString * basePath = @"http://petstore.swagger.io/v2"; static NSString * basePath = @"http://petstore.swagger.io/v2";
#pragma mark - Initialize methods #pragma mark - Initialize methods
- (id) init { - (id) init {
self = [super init]; self = [super init];
if (self) { if (self) {
self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; self.apiClient = [SWGApiClient sharedClientFromPool:basePath];
self.defaultHeaders = [NSMutableDictionary dictionary]; self.defaultHeaders = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
- (id) initWithApiClient:(SWGApiClient *)apiClient { - (id) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init]; self = [super init];
if (self) { if (self) {
if (apiClient) { if (apiClient) {
@ -36,11 +37,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
self.defaultHeaders = [NSMutableDictionary dictionary]; self.defaultHeaders = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
#pragma mark - #pragma mark -
+(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {
static SWGPetApi* singletonAPI = nil; static SWGPetApi* singletonAPI = nil;
if (singletonAPI == nil) { if (singletonAPI == nil) {
@ -48,37 +49,38 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
[singletonAPI addHeader:headerValue forKey:key]; [singletonAPI addHeader:headerValue forKey:key];
} }
return singletonAPI; return singletonAPI;
} }
+(void) setBasePath:(NSString*)path { +(void) setBasePath:(NSString*)path {
basePath = path; basePath = path;
} }
+(NSString*) getBasePath { +(NSString*) getBasePath {
return basePath; return basePath;
} }
-(void) addHeader:(NSString*)value forKey:(NSString*)key { -(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key]; [self.defaultHeaders setValue:value forKey:key];
} }
-(void) setHeaderValue:(NSString*) value -(void) setHeaderValue:(NSString*) value
forKey:(NSString*)key { forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key]; [self.defaultHeaders setValue:value forKey:key];
} }
-(unsigned long) requestQueueSize { -(unsigned long) requestQueueSize {
return [SWGApiClient requestQueueSize]; return [SWGApiClient requestQueueSize];
} }
/*!
/*!
* Update an existing pet * Update an existing pet
* *
* \param body Pet object that needs to be added to the store * \param body Pet object that needs to be added to the store
* \returns void * \returns void
*/ */
-(NSNumber*) updatePetWithCompletionBlock: (SWGPet*) body -(NSNumber*) updatePetWithCompletionBlock: (SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock { completionHandler: (void (^)(NSError* error))completionBlock {
@ -161,31 +163,32 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"PUT" method: @"PUT"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
/*!
}
/*!
* Add a new pet to the store * Add a new pet to the store
* *
* \param body Pet object that needs to be added to the store * \param body Pet object that needs to be added to the store
* \returns void * \returns void
*/ */
-(NSNumber*) addPetWithCompletionBlock: (SWGPet*) body -(NSNumber*) addPetWithCompletionBlock: (SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock { completionHandler: (void (^)(NSError* error))completionBlock {
@ -268,31 +271,32 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST" method: @"POST"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
/*!
}
/*!
* Finds Pets by status * Finds Pets by status
* Multiple status values can be provided with comma seperated strings * Multiple status values can be provided with comma seperated strings
* \param status Status values that need to be considered for filter * \param status Status values that need to be considered for filter
* \returns NSArray<SWGPet>* * \returns NSArray<SWGPet>*
*/ */
-(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray*) status -(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock
{ {
@ -354,19 +358,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// response is in a container // response is in a container
// array container response type // array container response type
return [self.apiClient dictionary: requestUrl return [self.apiClient dictionary: requestUrl
method: @"GET" method: @"GET"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) { completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) { if (error) {
completionBlock(nil, error); completionBlock(nil, error);
return; return;
} }
if([data isKindOfClass:[NSArray class]]){ if([data isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]];
@ -380,23 +384,23 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
completionBlock((NSArray<SWGPet>*)objs, nil); completionBlock((NSArray<SWGPet>*)objs, nil);
} }
}];
}];
} }
/*!
/*!
* Finds Pets by tags * Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
* \param tags Tags to filter by * \param tags Tags to filter by
* \returns NSArray<SWGPet>* * \returns NSArray<SWGPet>*
*/ */
-(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray*) tags -(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock
{ {
@ -458,19 +462,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// response is in a container // response is in a container
// array container response type // array container response type
return [self.apiClient dictionary: requestUrl return [self.apiClient dictionary: requestUrl
method: @"GET" method: @"GET"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) { completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) { if (error) {
completionBlock(nil, error); completionBlock(nil, error);
return; return;
} }
if([data isKindOfClass:[NSArray class]]){ if([data isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]];
@ -484,23 +488,23 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
completionBlock((NSArray<SWGPet>*)objs, nil); completionBlock((NSArray<SWGPet>*)objs, nil);
} }
}];
}];
} }
/*!
/*!
* Find pet by ID * Find pet by ID
* Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
* \param petId ID of pet that needs to be fetched * \param petId ID of pet that needs to be fetched
* \returns SWGPet* * \returns SWGPet*
*/ */
-(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId -(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock
{ {
@ -566,7 +570,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// complex response // complex response
// comples response type // comples response type
return [self.apiClient dictionary: requestUrl return [self.apiClient dictionary: requestUrl
method: @"GET" method: @"GET"
@ -593,10 +596,10 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
}
}
/*! /*!
* Updates a pet in the store with form data * Updates a pet in the store with form data
* *
* \param petId ID of pet that needs to be updated * \param petId ID of pet that needs to be updated
@ -604,7 +607,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
* \param status Updated status of the pet * \param status Updated status of the pet
* \returns void * \returns void
*/ */
-(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId -(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId
name: (NSString*) name name: (NSString*) name
status: (NSString*) status status: (NSString*) status
@ -686,32 +689,33 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST" method: @"POST"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
/*!
}
/*!
* Deletes a pet * Deletes a pet
* *
* \param apiKey * \param apiKey
* \param petId Pet id to delete * \param petId Pet id to delete
* \returns void * \returns void
*/ */
-(NSNumber*) deletePetWithCompletionBlock: (NSString*) apiKey -(NSNumber*) deletePetWithCompletionBlock: (NSString*) apiKey
petId: (NSNumber*) petId petId: (NSNumber*) petId
@ -778,25 +782,26 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"DELETE" method: @"DELETE"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
/*!
}
/*!
* uploads an image * uploads an image
* *
* \param petId ID of pet to update * \param petId ID of pet to update
@ -804,7 +809,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
* \param file file to upload * \param file file to upload
* \returns void * \returns void
*/ */
-(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId -(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId
additionalMetadata: (NSString*) additionalMetadata additionalMetadata: (NSString*) additionalMetadata
file: (SWGFile*) file file: (SWGFile*) file
@ -893,23 +898,24 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST" method: @"POST"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
}

View File

@ -1,20 +1,22 @@
#import <Foundation/Foundation.h> #import
<Foundation/Foundation.h>
#import "SWGOrder.h" #import "SWGOrder.h"
#import "SWGObject.h" #import "SWGObject.h"
#import "SWGApiClient.h" #import "SWGApiClient.h"
@interface SWGStoreApi: NSObject @interface SWGStoreApi: NSObject
@property(nonatomic, assign)SWGApiClient *apiClient; @property(nonatomic, assign)SWGApiClient *apiClient;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key; -(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize; -(unsigned long) requestQueueSize;
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath; +(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath; +(NSString*) getBasePath;
/**
/**
Returns pet inventories by status Returns pet inventories by status
Returns a map of status codes to quantities Returns a map of status codes to quantities
@ -23,12 +25,13 @@
return type: NSDictionary* return type: NSDictionary*
*/ */
-(NSNumber*) getInventoryWithCompletionBlock : -(NSNumber*) getInventoryWithCompletionBlock :
(void (^)(NSDictionary* output, NSError* error))completionBlock; (void (^)(NSDictionary* output, NSError* error))completionBlock;
/**
/**
Place an order for a pet Place an order for a pet
@ -38,13 +41,14 @@
return type: SWGOrder* return type: SWGOrder*
*/ */
-(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body -(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock;
/**
/**
Find purchase order by ID Find purchase order by ID
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
@ -54,13 +58,14 @@
return type: SWGOrder* return type: SWGOrder*
*/ */
-(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId -(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock;
/**
/**
Delete purchase order by ID Delete purchase order by ID
For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
@ -70,11 +75,12 @@
return type: return type:
*/ */
-(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId -(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;
@end @end

View File

@ -1,29 +1,30 @@
#import "SWGStoreApi.h" #import "SWGStoreApi.h"
#import "SWGFile.h" #import "SWGFile.h"
#import "SWGQueryParamCollection.h" #import "SWGQueryParamCollection.h"
#import "SWGOrder.h" #import "SWGOrder.h"
@interface SWGStoreApi ()
@interface SWGStoreApi ()
@property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; @property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders;
@end @end
@implementation SWGStoreApi @implementation SWGStoreApi
static NSString * basePath = @"http://petstore.swagger.io/v2"; static NSString * basePath = @"http://petstore.swagger.io/v2";
#pragma mark - Initialize methods #pragma mark - Initialize methods
- (id) init { - (id) init {
self = [super init]; self = [super init];
if (self) { if (self) {
self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; self.apiClient = [SWGApiClient sharedClientFromPool:basePath];
self.defaultHeaders = [NSMutableDictionary dictionary]; self.defaultHeaders = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
- (id) initWithApiClient:(SWGApiClient *)apiClient { - (id) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init]; self = [super init];
if (self) { if (self) {
if (apiClient) { if (apiClient) {
@ -35,11 +36,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
self.defaultHeaders = [NSMutableDictionary dictionary]; self.defaultHeaders = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
#pragma mark - #pragma mark -
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {
static SWGStoreApi* singletonAPI = nil; static SWGStoreApi* singletonAPI = nil;
if (singletonAPI == nil) { if (singletonAPI == nil) {
@ -47,36 +48,37 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
[singletonAPI addHeader:headerValue forKey:key]; [singletonAPI addHeader:headerValue forKey:key];
} }
return singletonAPI; return singletonAPI;
} }
+(void) setBasePath:(NSString*)path { +(void) setBasePath:(NSString*)path {
basePath = path; basePath = path;
} }
+(NSString*) getBasePath { +(NSString*) getBasePath {
return basePath; return basePath;
} }
-(void) addHeader:(NSString*)value forKey:(NSString*)key { -(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key]; [self.defaultHeaders setValue:value forKey:key];
} }
-(void) setHeaderValue:(NSString*) value -(void) setHeaderValue:(NSString*) value
forKey:(NSString*)key { forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key]; [self.defaultHeaders setValue:value forKey:key];
} }
-(unsigned long) requestQueueSize { -(unsigned long) requestQueueSize {
return [SWGApiClient requestQueueSize]; return [SWGApiClient requestQueueSize];
} }
/*!
/*!
* Returns pet inventories by status * Returns pet inventories by status
* Returns a map of status codes to quantities * Returns a map of status codes to quantities
* \returns NSDictionary* * \returns NSDictionary*
*/ */
-(NSNumber*) getInventoryWithCompletionBlock: -(NSNumber*) getInventoryWithCompletionBlock:
(void (^)(NSDictionary* output, NSError* error))completionBlock (void (^)(NSDictionary* output, NSError* error))completionBlock
{ {
@ -131,42 +133,41 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// response is in a container // response is in a container
// map container response type // map container response type
return [self.apiClient dictionary: requestUrl return [self.apiClient dictionary: requestUrl
method: @"GET" method: @"GET"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) { completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) { if (error) {
completionBlock(nil, error); completionBlock(nil, error);
return; return;
} }
NSDictionary *result = nil; NSDictionary *result = nil;
if (data) { if (data) {
result = [[NSDictionary alloc]initWithDictionary: data]; result = [[NSDictionary alloc]initWithDictionary: data];
} }
completionBlock(data, nil); completionBlock(data, nil);
}];
}];
} }
/*!
/*!
* Place an order for a pet * Place an order for a pet
* *
* \param body order placed for purchasing the pet * \param body order placed for purchasing the pet
* \returns SWGOrder* * \returns SWGOrder*
*/ */
-(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body -(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
{ {
@ -251,7 +252,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// complex response // complex response
// comples response type // comples response type
return [self.apiClient dictionary: requestUrl return [self.apiClient dictionary: requestUrl
method: @"POST" method: @"POST"
@ -278,16 +278,16 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
}
}
/*! /*!
* Find purchase order by ID * Find purchase order by ID
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* \param orderId ID of pet that needs to be fetched * \param orderId ID of pet that needs to be fetched
* \returns SWGOrder* * \returns SWGOrder*
*/ */
-(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId -(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
{ {
@ -353,7 +353,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// complex response // complex response
// comples response type // comples response type
return [self.apiClient dictionary: requestUrl return [self.apiClient dictionary: requestUrl
method: @"GET" method: @"GET"
@ -380,16 +379,16 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
}
}
/*! /*!
* Delete purchase order by ID * Delete purchase order by ID
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* \param orderId ID of the order that needs to be deleted * \param orderId ID of the order that needs to be deleted
* \returns void * \returns void
*/ */
-(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId -(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(NSError* error))completionBlock { completionHandler: (void (^)(NSError* error))completionBlock {
@ -453,23 +452,24 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"DELETE" method: @"DELETE"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
}

View File

@ -1,15 +1,21 @@
#import <Foundation/Foundation.h> #import
<Foundation/Foundation.h>
#import "SWGObject.h" #import "SWGObject.h"
@protocol SWGTag
@end
@interface SWGTag : SWGObject @protocol SWGTag
@end
@interface SWGTag : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSString* name; @property(nonatomic) NSNumber* _id;
@property(nonatomic) NSString* name;
@end
@end

View File

@ -1,14 +1,15 @@
#import "SWGTag.h"
@implementation SWGTag #import "SWGTag.h"
+ (JSONKeyMapper *)keyMapper @implementation SWGTag
{
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }];
} }
+ (BOOL)propertyIsOptional:(NSString *)propertyName + (BOOL)propertyIsOptional:(NSString *)propertyName
{ {
NSArray *optionalProperties = @[@"_id", @"name"]; NSArray *optionalProperties = @[@"_id", @"name"];
if ([optionalProperties containsObject:propertyName]) { if ([optionalProperties containsObject:propertyName]) {
@ -17,6 +18,7 @@
else { else {
return NO; return NO;
} }
} }
@end
@end

View File

@ -1,28 +1,40 @@
#import <Foundation/Foundation.h> #import
<Foundation/Foundation.h>
#import "SWGObject.h" #import "SWGObject.h"
@protocol SWGUser
@end
@interface SWGUser : SWGObject @protocol SWGUser
@end
@interface SWGUser : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSString* username; @property(nonatomic) NSNumber* _id;
@property(nonatomic) NSString* firstName;
@property(nonatomic) NSString* lastName; @property(nonatomic) NSString* username;
@property(nonatomic) NSString* email;
@property(nonatomic) NSString* password; @property(nonatomic) NSString* firstName;
@property(nonatomic) NSString* phone;
/* User Status [optional] @property(nonatomic) NSString* lastName;
@property(nonatomic) NSString* email;
@property(nonatomic) NSString* password;
@property(nonatomic) NSString* phone;
/* User Status [optional]
*/ */
@property(nonatomic) NSNumber* userStatus; @property(nonatomic) NSNumber* userStatus;
@end
@end

View File

@ -1,14 +1,15 @@
#import "SWGUser.h"
@implementation SWGUser #import "SWGUser.h"
+ (JSONKeyMapper *)keyMapper @implementation SWGUser
{
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }]; return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }];
} }
+ (BOOL)propertyIsOptional:(NSString *)propertyName + (BOOL)propertyIsOptional:(NSString *)propertyName
{ {
NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"]; NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"];
if ([optionalProperties containsObject:propertyName]) { if ([optionalProperties containsObject:propertyName]) {
@ -17,6 +18,7 @@
else { else {
return NO; return NO;
} }
} }
@end
@end

View File

@ -1,20 +1,22 @@
#import <Foundation/Foundation.h> #import
<Foundation/Foundation.h>
#import "SWGUser.h" #import "SWGUser.h"
#import "SWGObject.h" #import "SWGObject.h"
#import "SWGApiClient.h" #import "SWGApiClient.h"
@interface SWGUserApi: NSObject @interface SWGUserApi: NSObject
@property(nonatomic, assign)SWGApiClient *apiClient; @property(nonatomic, assign)SWGApiClient *apiClient;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key; -(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize; -(unsigned long) requestQueueSize;
+(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath; +(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath; +(NSString*) getBasePath;
/**
/**
Create user Create user
This can only be done by the logged in user. This can only be done by the logged in user.
@ -24,13 +26,14 @@
return type: return type:
*/ */
-(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body -(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;
/**
/**
Creates list of users with given input array Creates list of users with given input array
@ -40,13 +43,14 @@
return type: return type:
*/ */
-(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray<SWGUser>*) body -(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;
/**
/**
Creates list of users with given input array Creates list of users with given input array
@ -56,13 +60,14 @@
return type: return type:
*/ */
-(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray<SWGUser>*) body -(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;
/**
/**
Logs user into the system Logs user into the system
@ -73,14 +78,15 @@
return type: NSString* return type: NSString*
*/ */
-(NSNumber*) loginUserWithCompletionBlock :(NSString*) username -(NSNumber*) loginUserWithCompletionBlock :(NSString*) username
password:(NSString*) password password:(NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error))completionBlock; completionHandler: (void (^)(NSString* output, NSError* error))completionBlock;
/**
/**
Logs out current logged in user session Logs out current logged in user session
@ -89,12 +95,13 @@
return type: return type:
*/ */
-(NSNumber*) logoutUserWithCompletionBlock : -(NSNumber*) logoutUserWithCompletionBlock :
(void (^)(NSError* error))completionBlock; (void (^)(NSError* error))completionBlock;
/**
/**
Get user by user name Get user by user name
@ -104,13 +111,14 @@
return type: SWGUser* return type: SWGUser*
*/ */
-(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username -(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock; completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock;
/**
/**
Updated user Updated user
This can only be done by the logged in user. This can only be done by the logged in user.
@ -121,14 +129,15 @@
return type: return type:
*/ */
-(NSNumber*) updateUserWithCompletionBlock :(NSString*) username -(NSNumber*) updateUserWithCompletionBlock :(NSString*) username
body:(SWGUser*) body body:(SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;
/**
/**
Delete user Delete user
This can only be done by the logged in user. This can only be done by the logged in user.
@ -138,11 +147,12 @@
return type: return type:
*/ */
-(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username -(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username
completionHandler: (void (^)(NSError* error))completionBlock; completionHandler: (void (^)(NSError* error))completionBlock;
@end @end

View File

@ -1,29 +1,30 @@
#import "SWGUserApi.h" #import "SWGUserApi.h"
#import "SWGFile.h" #import "SWGFile.h"
#import "SWGQueryParamCollection.h" #import "SWGQueryParamCollection.h"
#import "SWGUser.h" #import "SWGUser.h"
@interface SWGUserApi ()
@interface SWGUserApi ()
@property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; @property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders;
@end @end
@implementation SWGUserApi @implementation SWGUserApi
static NSString * basePath = @"http://petstore.swagger.io/v2"; static NSString * basePath = @"http://petstore.swagger.io/v2";
#pragma mark - Initialize methods #pragma mark - Initialize methods
- (id) init { - (id) init {
self = [super init]; self = [super init];
if (self) { if (self) {
self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; self.apiClient = [SWGApiClient sharedClientFromPool:basePath];
self.defaultHeaders = [NSMutableDictionary dictionary]; self.defaultHeaders = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
- (id) initWithApiClient:(SWGApiClient *)apiClient { - (id) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init]; self = [super init];
if (self) { if (self) {
if (apiClient) { if (apiClient) {
@ -35,11 +36,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
self.defaultHeaders = [NSMutableDictionary dictionary]; self.defaultHeaders = [NSMutableDictionary dictionary];
} }
return self; return self;
} }
#pragma mark - #pragma mark -
+(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {
static SWGUserApi* singletonAPI = nil; static SWGUserApi* singletonAPI = nil;
if (singletonAPI == nil) { if (singletonAPI == nil) {
@ -47,37 +48,38 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
[singletonAPI addHeader:headerValue forKey:key]; [singletonAPI addHeader:headerValue forKey:key];
} }
return singletonAPI; return singletonAPI;
} }
+(void) setBasePath:(NSString*)path { +(void) setBasePath:(NSString*)path {
basePath = path; basePath = path;
} }
+(NSString*) getBasePath { +(NSString*) getBasePath {
return basePath; return basePath;
} }
-(void) addHeader:(NSString*)value forKey:(NSString*)key { -(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key]; [self.defaultHeaders setValue:value forKey:key];
} }
-(void) setHeaderValue:(NSString*) value -(void) setHeaderValue:(NSString*) value
forKey:(NSString*)key { forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key]; [self.defaultHeaders setValue:value forKey:key];
} }
-(unsigned long) requestQueueSize { -(unsigned long) requestQueueSize {
return [SWGApiClient requestQueueSize]; return [SWGApiClient requestQueueSize];
} }
/*!
/*!
* Create user * Create user
* This can only be done by the logged in user. * This can only be done by the logged in user.
* \param body Created user object * \param body Created user object
* \returns void * \returns void
*/ */
-(NSNumber*) createUserWithCompletionBlock: (SWGUser*) body -(NSNumber*) createUserWithCompletionBlock: (SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock { completionHandler: (void (^)(NSError* error))completionBlock {
@ -160,31 +162,32 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST" method: @"POST"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
/*!
}
/*!
* Creates list of users with given input array * Creates list of users with given input array
* *
* \param body List of user object * \param body List of user object
* \returns void * \returns void
*/ */
-(NSNumber*) createUsersWithArrayInputWithCompletionBlock: (NSArray<SWGUser>*) body -(NSNumber*) createUsersWithArrayInputWithCompletionBlock: (NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error))completionBlock { completionHandler: (void (^)(NSError* error))completionBlock {
@ -267,31 +270,32 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST" method: @"POST"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
/*!
}
/*!
* Creates list of users with given input array * Creates list of users with given input array
* *
* \param body List of user object * \param body List of user object
* \returns void * \returns void
*/ */
-(NSNumber*) createUsersWithListInputWithCompletionBlock: (NSArray<SWGUser>*) body -(NSNumber*) createUsersWithListInputWithCompletionBlock: (NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error))completionBlock { completionHandler: (void (^)(NSError* error))completionBlock {
@ -374,32 +378,33 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"POST" method: @"POST"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
/*!
}
/*!
* Logs user into the system * Logs user into the system
* *
* \param username The user name for login * \param username The user name for login
* \param password The password for login in clear text * \param password The password for login in clear text
* \returns NSString* * \returns NSString*
*/ */
-(NSNumber*) loginUserWithCompletionBlock: (NSString*) username -(NSNumber*) loginUserWithCompletionBlock: (NSString*) username
password: (NSString*) password password: (NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error))completionBlock completionHandler: (void (^)(NSString* output, NSError* error))completionBlock
@ -469,24 +474,22 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// primitive response // primitive response
// primitive response type // primitive response type
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"GET" method: @"GET"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(nil, error); completionBlock(nil, error);
return; return;
} }
NSString *result = data ? [[NSString alloc]initWithString: data] : nil; NSString *result = data ? [[NSString alloc]initWithString: data] : nil;
completionBlock(result, nil); completionBlock(result, nil);
}]; }];
@ -496,15 +499,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
}
}
/*! /*!
* Logs out current logged in user session * Logs out current logged in user session
* *
* \returns void * \returns void
*/ */
-(NSNumber*) logoutUserWithCompletionBlock: -(NSNumber*) logoutUserWithCompletionBlock:
(void (^)(NSError* error))completionBlock { (void (^)(NSError* error))completionBlock {
@ -563,31 +566,32 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"GET" method: @"GET"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
/*!
}
/*!
* Get user by user name * Get user by user name
* *
* \param username The name that needs to be fetched. Use user1 for testing. * \param username The name that needs to be fetched. Use user1 for testing.
* \returns SWGUser* * \returns SWGUser*
*/ */
-(NSNumber*) getUserByNameWithCompletionBlock: (NSString*) username -(NSNumber*) getUserByNameWithCompletionBlock: (NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock
{ {
@ -653,7 +657,6 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// complex response // complex response
// comples response type // comples response type
return [self.apiClient dictionary: requestUrl return [self.apiClient dictionary: requestUrl
method: @"GET" method: @"GET"
@ -680,17 +683,17 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
}
}
/*! /*!
* Updated user * Updated user
* This can only be done by the logged in user. * This can only be done by the logged in user.
* \param username name that need to be deleted * \param username name that need to be deleted
* \param body Updated user object * \param body Updated user object
* \returns void * \returns void
*/ */
-(NSNumber*) updateUserWithCompletionBlock: (NSString*) username -(NSNumber*) updateUserWithCompletionBlock: (NSString*) username
body: (SWGUser*) body body: (SWGUser*) body
@ -778,31 +781,32 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"PUT" method: @"PUT"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
/*!
}
/*!
* Delete user * Delete user
* This can only be done by the logged in user. * This can only be done by the logged in user.
* \param username The name that needs to be deleted * \param username The name that needs to be deleted
* \returns void * \returns void
*/ */
-(NSNumber*) deleteUserWithCompletionBlock: (NSString*) username -(NSNumber*) deleteUserWithCompletionBlock: (NSString*) username
completionHandler: (void (^)(NSError* error))completionBlock { completionHandler: (void (^)(NSError* error))completionBlock {
@ -866,23 +870,24 @@ static NSString * basePath = @"http://petstore.swagger.io/v2";
// it's void // it's void
return [self.apiClient stringWithCompletionBlock: requestUrl return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"DELETE" method: @"DELETE"
queryParams: queryParams queryParams: queryParams
body: bodyDictionary body: bodyDictionary
headerParams: headerParams headerParams: headerParams
authSettings: authSettings authSettings: authSettings
requestContentType: requestContentType requestContentType: requestContentType
responseContentType: responseContentType responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) { completionBlock: ^(NSString *data, NSError *error) {
if (error) { if (error) {
completionBlock(error); completionBlock(error);
return; return;
}
completionBlock(nil);
}];
} }
completionBlock(nil);
}];
}

View File

@ -1,34 +1,32 @@
{ {
"name": "SwaggerClient/SwaggerClient-php", "name": "SwaggerClient/SwaggerClient-php",
"description": "", "description": "",
"keywords": [ "keywords": [
"swagger", "swagger",
"php", "php",
"sdk", "sdk",
"api" "api"
], ],
"homepage": "http://swagger.io", "homepage": "http://swagger.io",
"license": "Apache v2", "license": "Apache v2",
"authors": [ "authors": [
{ {
"name": "Swagger and contributors", "name": "Swagger and contributors",
"homepage": "https://github.com/swagger-api/swagger-codegen" "homepage": "https://github.com/swagger-api/swagger-codegen"
} }
], ],
"require": { "require": {
"php": ">=5.3.3", "php": ">=5.3.3",
"ext-curl": "*", "ext-curl": "*",
"ext-json": "*", "ext-json": "*",
"ext-mbstring": "*" "ext-mbstring": "*"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "~4.0", "phpunit/phpunit": "~4.0",
"satooshi/php-coveralls": "~0.6.1", "satooshi/php-coveralls": "~0.6.1",
"squizlabs/php_codesniffer": "~2.0" "squizlabs/php_codesniffer": "~2.0"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": { "SwaggerClient\\" : "lib/" }
"SwaggerClient\\": "lib/" }
}
}
} }

View File

@ -43,412 +43,409 @@ class ApiClient {
function __construct($host = null) { function __construct($host = null) {
if ($host === null) { if ($host === null) {
$this->host = 'http://petstore.swagger.io/v2'; $this->host = 'http://petstore.swagger.io/v2';
} else { } else {
$this->host = $host; $this->host = $host;
} }
} }
/** /**
* add default header * add default header
* *
* @param string $header_name header name (e.g. Token) * @param string $header_name header name (e.g. Token)
* @param string $header_value header value (e.g. 1z8wp3) * @param string $header_value header value (e.g. 1z8wp3)
*/ */
public function addDefaultHeader($header_name, $header_value) { public function addDefaultHeader($header_name, $header_value) {
if (!is_string($header_name)) if (!is_string($header_name))
throw new \InvalidArgumentException('Header name must be a string.'); throw new \InvalidArgumentException('Header name must be a string.');
self::$default_header[$header_name] = $header_value; self::$default_header[$header_name] = $header_value;
} }
/** /**
* get the default header * get the default header
* *
* @return array default header * @return array default header
*/ */
public function getDefaultHeader() { public function getDefaultHeader() {
return self::$default_header; return self::$default_header;
} }
/** /**
* delete the default header based on header name * delete the default header based on header name
* *
* @param string $header_name header name (e.g. Token) * @param string $header_name header name (e.g. Token)
*/ */
public function deleteDefaultHeader($header_name) { public function deleteDefaultHeader($header_name) {
unset(self::$default_header[$header_name]); unset(self::$default_header[$header_name]);
} }
/** /**
* set the user agent of the api client * set the user agent of the api client
* *
* @param string $user_agent the user agent of the api client * @param string $user_agent the user agent of the api client
*/ */
public function setUserAgent($user_agent) { public function setUserAgent($user_agent) {
if (!is_string($user_agent)) if (!is_string($user_agent))
throw new \InvalidArgumentException('User-agent must be a string.'); throw new \InvalidArgumentException('User-agent must be a string.');
$this->user_agent= $user_agent; $this->user_agent= $user_agent;
} }
/** /**
* get the user agent of the api client * get the user agent of the api client
* *
* @return string user agent * @return string user agent
*/ */
public function getUserAgent($user_agent) { public function getUserAgent($user_agent) {
return $this->user_agent; return $this->user_agent;
} }
/** /**
* set the HTTP timeout value * set the HTTP timeout value
* *
* @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout]
*/ */
public function setTimeout($seconds) { public function setTimeout($seconds) {
if (!is_numeric($seconds) || $seconds < 0) if (!is_numeric($seconds) || $seconds < 0)
throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.');
$this->curl_timeout = $seconds; $this->curl_timeout = $seconds;
} }
/** /**
* get the HTTP timeout value * get the HTTP timeout value
* *
* @return string HTTP timeout value * @return string HTTP timeout value
*/ */
public function getTimeout() { public function getTimeout() {
return $this->curl_timeout; return $this->curl_timeout;
} }
/** /**
* Get API key (with prefix if set) * Get API key (with prefix if set)
* @param string key name * @param string key name
* @return string API key with the prefix * @return string API key with the prefix
*/ */
public function getApiKeyWithPrefix($apiKey) { public function getApiKeyWithPrefix($apiKey) {
if (isset(Configuration::$apiKeyPrefix[$apiKey])) { if (isset(Configuration::$apiKeyPrefix[$apiKey])) {
return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey];
} else if (isset(Configuration::$apiKey[$apiKey])) { } else if (isset(Configuration::$apiKey[$apiKey])) {
return Configuration::$apiKey[$apiKey]; return Configuration::$apiKey[$apiKey];
} else { } else {
return; return;
} }
} }
/** /**
* update hearder and query param based on authentication setting * update hearder and query param based on authentication setting
* *
* @param array $headerParams header parameters (by ref) * @param array $headerParams header parameters (by ref)
* @param array $queryParams query parameters (by ref) * @param array $queryParams query parameters (by ref)
* @param array $authSettings array of authentication scheme (e.g ['api_key']) * @param array $authSettings array of authentication scheme (e.g ['api_key'])
*/ */
public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings)
{ {
if (count($authSettings) == 0) if (count($authSettings) == 0)
return; return;
// one endpoint can have more than 1 auth settings
foreach($authSettings as $auth) {
// determine which one to use
switch($auth) {
// one endpoint can have more than 1 auth settings
foreach($authSettings as $auth) {
// determine which one to use
switch($auth) {
case 'api_key': case 'api_key':
$headerParams['api_key'] = $this->getApiKeyWithPrefix('api_key'); $headerParams['api_key'] = $this->getApiKeyWithPrefix('api_key');
break; break;
case 'petstore_auth': case 'petstore_auth':
//TODO support oauth //TODO support oauth
break; break;
default:
//TODO show warning about security definition not found
}
}
}
default: /**
//TODO show warning about security definition not found * @param string $resourcePath path to method endpoint
} * @param string $method method to call
} * @param array $queryParams parameters to be place in query URL
} * @param array $postData parameters to be placed in POST body
* @param array $headerParams parameters to be place in request header
* @return mixed
*/
public function callApi($resourcePath, $method, $queryParams, $postData,
$headerParams, $authSettings) {
/** $headers = array();
* @param string $resourcePath path to method endpoint
* @param string $method method to call
* @param array $queryParams parameters to be place in query URL
* @param array $postData parameters to be placed in POST body
* @param array $headerParams parameters to be place in request header
* @return mixed
*/
public function callApi($resourcePath, $method, $queryParams, $postData,
$headerParams, $authSettings) {
$headers = array(); # determine authentication setting
$this->updateParamsForAuth($headerParams, $queryParams, $authSettings);
# determine authentication setting # construct the http header
$this->updateParamsForAuth($headerParams, $queryParams, $authSettings); $headerParams = array_merge((array)self::$default_header, (array)$headerParams);
# construct the http header foreach ($headerParams as $key => $val) {
$headerParams = array_merge((array)self::$default_header, (array)$headerParams); $headers[] = "$key: $val";
}
foreach ($headerParams as $key => $val) { // form data
$headers[] = "$key: $val"; if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) {
} $postData = http_build_query($postData);
}
else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model
$postData = json_encode($this->sanitizeForSerialization($postData));
}
// form data $url = $this->host . $resourcePath;
if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) {
$postData = http_build_query($postData);
}
else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model
$postData = json_encode($this->sanitizeForSerialization($postData));
}
$url = $this->host . $resourcePath; $curl = curl_init();
// set timeout, if needed
if ($this->curl_timeout != 0) {
curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout);
}
// return the result on success, rather than just TRUE
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl = curl_init(); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// set timeout, if needed
if ($this->curl_timeout != 0) {
curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timeout);
}
// return the result on success, rather than just TRUE
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); if (! empty($queryParams)) {
$url = ($url . '?' . http_build_query($queryParams));
}
if (! empty($queryParams)) { if ($method == self::$POST) {
$url = ($url . '?' . http_build_query($queryParams)); curl_setopt($curl, CURLOPT_POST, true);
} curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method == self::$PATCH) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method == self::$PUT) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method == self::$DELETE) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method != self::$GET) {
throw new ApiException('Method ' . $method . ' is not recognized.');
}
curl_setopt($curl, CURLOPT_URL, $url);
if ($method == self::$POST) { // Set user agent
curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method == self::$PATCH) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method == self::$PUT) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method == self::$DELETE) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method != self::$GET) {
throw new ApiException('Method ' . $method . ' is not recognized.');
}
curl_setopt($curl, CURLOPT_URL, $url);
// Set user agent // debugging for curl
curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); if (Configuration::$debug) {
error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file);
// debugging for curl curl_setopt($curl, CURLOPT_VERBOSE, 1);
if (Configuration::$debug) { curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a'));
error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file); } else {
curl_setopt($curl, CURLOPT_VERBOSE, 0);
}
curl_setopt($curl, CURLOPT_VERBOSE, 1); // obtain the HTTP response headers
curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); curl_setopt($curl, CURLOPT_HEADER, 1);
} else {
curl_setopt($curl, CURLOPT_VERBOSE, 0);
}
// obtain the HTTP response headers // Make the request
curl_setopt($curl, CURLOPT_HEADER, 1); $response = curl_exec($curl);
$http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$http_header = substr($response, 0, $http_header_size);
$http_body = substr($response, $http_header_size);
$response_info = curl_getinfo($curl);
// Make the request // debug HTTP response body
$response = curl_exec($curl); if (Configuration::$debug) {
$http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file);
$http_header = substr($response, 0, $http_header_size); }
$http_body = substr($response, $http_header_size);
$response_info = curl_getinfo($curl);
// debug HTTP response body // Handle the response
if (Configuration::$debug) { if ($response_info['http_code'] == 0) {
error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file); throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null);
} } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) {
$data = json_decode($http_body);
if (json_last_error() > 0) { // if response is a string
$data = $http_body;
}
} else {
throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)",
$response_info['http_code'], $http_header, $http_body);
}
return $data;
}
// Handle the response /**
if ($response_info['http_code'] == 0) { * Build a JSON POST object
throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); */
} else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { protected function sanitizeForSerialization($data)
$data = json_decode($http_body); {
if (json_last_error() > 0) { // if response is a string if (is_scalar($data) || null === $data) {
$data = $http_body; $sanitized = $data;
} } else if ($data instanceof \DateTime) {
} else { $sanitized = $data->format(\DateTime::ISO8601);
throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", } else if (is_array($data)) {
$response_info['http_code'], $http_header, $http_body); foreach ($data as $property => $value) {
} $data[$property] = $this->sanitizeForSerialization($value);
return $data; }
} $sanitized = $data;
} else if (is_object($data)) {
$values = array();
foreach (array_keys($data::$swaggerTypes) as $property) {
if ($data->$property !== null) {
$values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property);
}
}
$sanitized = $values;
} else {
$sanitized = (string)$data;
}
/** return $sanitized;
* Build a JSON POST object }
*/
protected function sanitizeForSerialization($data)
{
if (is_scalar($data) || null === $data) {
$sanitized = $data;
} else if ($data instanceof \DateTime) {
$sanitized = $data->format(\DateTime::ISO8601);
} else if (is_array($data)) {
foreach ($data as $property => $value) {
$data[$property] = $this->sanitizeForSerialization($value);
}
$sanitized = $data;
} else if (is_object($data)) {
$values = array();
foreach (array_keys($data::$swaggerTypes) as $property) {
if ($data->$property !== null) {
$values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property);
}
}
$sanitized = $values;
} else {
$sanitized = (string)$data;
}
return $sanitized; /**
} * Take value and turn it into a string suitable for inclusion in
* the path, by url-encoding.
* @param string $value a string which will be part of the path
* @return string the serialized object
*/
public static function toPathValue($value) {
return rawurlencode(self::toString($value));
}
/** /**
* Take value and turn it into a string suitable for inclusion in * Take value and turn it into a string suitable for inclusion in
* the path, by url-encoding. * the query, by imploding comma-separated if it's an object.
* @param string $value a string which will be part of the path * If it's a string, pass through unchanged. It will be url-encoded
* @return string the serialized object * later.
*/ * @param object $object an object to be serialized to a string
public static function toPathValue($value) { * @return string the serialized object
return rawurlencode(self::toString($value)); */
} public static function toQueryValue($object) {
if (is_array($object)) {
return implode(',', $object);
} else {
return self::toString($object);
}
}
/** /**
* Take value and turn it into a string suitable for inclusion in * Take value and turn it into a string suitable for inclusion in
* the query, by imploding comma-separated if it's an object. * the header. If it's a string, pass through unchanged
* If it's a string, pass through unchanged. It will be url-encoded * If it's a datetime object, format it in ISO8601
* later. * @param string $value a string which will be part of the header
* @param object $object an object to be serialized to a string * @return string the header string
* @return string the serialized object */
*/ public static function toHeaderValue($value) {
public static function toQueryValue($object) { return self::toString($value);
if (is_array($object)) { }
return implode(',', $object);
} else {
return self::toString($object);
}
}
/** /**
* Take value and turn it into a string suitable for inclusion in * Take value and turn it into a string suitable for inclusion in
* the header. If it's a string, pass through unchanged * the http body (form parameter). If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601 * If it's a datetime object, format it in ISO8601
* @param string $value a string which will be part of the header * @param string $value the value of the form parameter
* @return string the header string * @return string the form string
*/ */
public static function toHeaderValue($value) { public static function toFormValue($value) {
return self::toString($value); return self::toString($value);
} }
/** /**
* Take value and turn it into a string suitable for inclusion in * Take value and turn it into a string suitable for inclusion in
* the http body (form parameter). If it's a string, pass through unchanged * the parameter. If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601 * If it's a datetime object, format it in ISO8601
* @param string $value the value of the form parameter * @param string $value the value of the parameter
* @return string the form string * @return string the header string
*/ */
public static function toFormValue($value) { public static function toString($value) {
return self::toString($value); if ($value instanceof \DateTime) { // datetime in ISO8601 format
} return $value->format(\DateTime::ISO8601);
}
else {
return $value;
}
}
/** /**
* Take value and turn it into a string suitable for inclusion in * Deserialize a JSON string into an object
* the parameter. If it's a string, pass through unchanged *
* If it's a datetime object, format it in ISO8601 * @param object $object object or primitive to be deserialized
* @param string $value the value of the parameter * @param string $class class name is passed as a string
* @return string the header string * @return object an instance of $class
*/ */
public static function toString($value) { public static function deserialize($data, $class)
if ($value instanceof \DateTime) { // datetime in ISO8601 format {
return $value->format(\DateTime::ISO8601); if (null === $data) {
} $deserialized = null;
else { } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int]
return $value; $inner = substr($class, 4, -1);
} $deserialized = array();
} if(strrpos($inner, ",") !== false) {
$subClass_array = explode(',', $inner, 2);
$subClass = $subClass_array[1];
foreach ($data as $key => $value) {
$deserialized[$key] = self::deserialize($value, $subClass);
}
}
} elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) {
$subClass = substr($class, 6, -1);
$values = array();
foreach ($data as $key => $value) {
$values[] = self::deserialize($value, $subClass);
}
$deserialized = $values;
} elseif ($class == 'DateTime') {
$deserialized = new \DateTime($data);
} elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) {
settype($data, $class);
$deserialized = $data;
} else {
$class = "SwaggerClient\\models\\".$class;
$instance = new $class();
foreach ($instance::$swaggerTypes as $property => $type) {
$original_property_name = $instance::$attributeMap[$property];
if (isset($original_property_name) && isset($data->$original_property_name)) {
$instance->$property = self::deserialize($data->$original_property_name, $type);
}
}
$deserialized = $instance;
}
/** return $deserialized;
* Deserialize a JSON string into an object }
*
* @param object $object object or primitive to be deserialized
* @param string $class class name is passed as a string
* @return object an instance of $class
*/
public static function deserialize($data, $class)
{
if (null === $data) {
$deserialized = null;
} elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int]
$inner = substr($class, 4, -1);
$deserialized = array();
if(strrpos($inner, ",") !== false) {
$subClass_array = explode(',', $inner, 2);
$subClass = $subClass_array[1];
foreach ($data as $key => $value) {
$deserialized[$key] = self::deserialize($value, $subClass);
}
}
} elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) {
$subClass = substr($class, 6, -1);
$values = array();
foreach ($data as $key => $value) {
$values[] = self::deserialize($value, $subClass);
}
$deserialized = $values;
} elseif ($class == 'DateTime') {
$deserialized = new \DateTime($data);
} elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) {
settype($data, $class);
$deserialized = $data;
} else {
$class = "SwaggerClient\\models\\".$class;
$instance = new $class();
foreach ($instance::$swaggerTypes as $property => $type) {
$original_property_name = $instance::$attributeMap[$property];
if (isset($original_property_name) && isset($data->$original_property_name)) {
$instance->$property = self::deserialize($data->$original_property_name, $type);
}
}
$deserialized = $instance;
}
return $deserialized; /*
} * return the header 'Accept' based on an array of Accept provided
*
* @param array[string] $accept Array of header
* @return string Accept (e.g. application/json)
*/
public static function selectHeaderAccept($accept) {
if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) {
return NULL;
} elseif (preg_grep("/application\/json/i", $accept)) {
return 'application/json';
} else {
return implode(',', $accept);
}
}
/* /*
* return the header 'Accept' based on an array of Accept provided * return the content type based on an array of content-type provided
* *
* @param array[string] $accept Array of header * @param array[string] content_type_array Array fo content-type
* @return string Accept (e.g. application/json) * @return string Content-Type (e.g. application/json)
*/ */
public static function selectHeaderAccept($accept) { public static function selectHeaderContentType($content_type) {
if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) {
return NULL; return 'application/json';
} elseif (preg_grep("/application\/json/i", $accept)) { } elseif (preg_grep("/application\/json/i", $content_type)) {
return 'application/json'; return 'application/json';
} else { } else {
return implode(',', $accept); return implode(',', $content_type);
} }
} }
/*
* return the content type based on an array of content-type provided
*
* @param array[string] content_type_array Array fo content-type
* @return string Content-Type (e.g. application/json)
*/
public static function selectHeaderContentType($content_type) {
if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) {
return 'application/json';
} elseif (preg_grep("/application\/json/i", $content_type)) {
return 'application/json';
} else {
return implode(',', $content_type);
}
}
} }

View File

@ -34,25 +34,25 @@ class ApiException extends Exception {
public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) {
parent::__construct($message, $code); parent::__construct($message, $code);
$this->response_headers = $responseHeaders; $this->response_headers = $responseHeaders;
$this->response_body = $responseBody; $this->response_body = $responseBody;
} }
/** /**
* Get the HTTP response header * Get the HTTP response header
* *
* @return string HTTP response header * @return string HTTP response header
*/ */
public function getResponseHeaders() { public function getResponseHeaders() {
return $this->response_headers; return $this->response_headers;
} }
/** /**
* Get the HTTP response body * Get the HTTP response body
* *
* @return string HTTP response body * @return string HTTP response body
*/ */
public function getResponseBody() { public function getResponseBody() {
return $this->response_body; return $this->response_body;
} }
} }

View File

@ -29,30 +29,29 @@ class PetApi {
if (Configuration::$apiClient === null) { if (Configuration::$apiClient === null) {
Configuration::$apiClient = new ApiClient(); // create a new API client if not present Configuration::$apiClient = new ApiClient(); // create a new API client if not present
$this->apiClient = Configuration::$apiClient; $this->apiClient = Configuration::$apiClient;
} }
else else
$this->apiClient = Configuration::$apiClient; // use the default one $this->apiClient = Configuration::$apiClient; // use the default one
} else { } else {
$this->apiClient = $apiClient; // use the one provided by the user $this->apiClient = $apiClient; // use the one provided by the user
} }
} }
private $apiClient; // instance of the ApiClient private $apiClient; // instance of the ApiClient
/** /**
* get the API client * get the API client
*/ */
public function getApiClient() { public function getApiClient() {
return $this->apiClient; return $this->apiClient;
} }
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
/** /**
* updatePet * updatePet
@ -107,7 +106,6 @@ class PetApi {
} }
/** /**
* addPet * addPet
* *
@ -161,7 +159,6 @@ class PetApi {
} }
/** /**
* findPetsByStatus * findPetsByStatus
* *
@ -219,7 +216,6 @@ class PetApi {
$responseObject = $this->apiClient->deserialize($response,'array[Pet]'); $responseObject = $this->apiClient->deserialize($response,'array[Pet]');
return $responseObject; return $responseObject;
} }
/** /**
* findPetsByTags * findPetsByTags
* *
@ -277,7 +273,6 @@ class PetApi {
$responseObject = $this->apiClient->deserialize($response,'array[Pet]'); $responseObject = $this->apiClient->deserialize($response,'array[Pet]');
return $responseObject; return $responseObject;
} }
/** /**
* getPetById * getPetById
* *
@ -341,7 +336,6 @@ class PetApi {
$responseObject = $this->apiClient->deserialize($response,'Pet'); $responseObject = $this->apiClient->deserialize($response,'Pet');
return $responseObject; return $responseObject;
} }
/** /**
* updatePetWithForm * updatePetWithForm
* *
@ -408,7 +402,6 @@ class PetApi {
} }
/** /**
* deletePet * deletePet
* *
@ -471,7 +464,6 @@ class PetApi {
} }
/** /**
* uploadFile * uploadFile
* *
@ -539,5 +531,4 @@ class PetApi {
} }
} }

View File

@ -29,30 +29,29 @@ class StoreApi {
if (Configuration::$apiClient === null) { if (Configuration::$apiClient === null) {
Configuration::$apiClient = new ApiClient(); // create a new API client if not present Configuration::$apiClient = new ApiClient(); // create a new API client if not present
$this->apiClient = Configuration::$apiClient; $this->apiClient = Configuration::$apiClient;
} }
else else
$this->apiClient = Configuration::$apiClient; // use the default one $this->apiClient = Configuration::$apiClient; // use the default one
} else { } else {
$this->apiClient = $apiClient; // use the one provided by the user $this->apiClient = $apiClient; // use the one provided by the user
} }
} }
private $apiClient; // instance of the ApiClient private $apiClient; // instance of the ApiClient
/** /**
* get the API client * get the API client
*/ */
public function getApiClient() { public function getApiClient() {
return $this->apiClient; return $this->apiClient;
} }
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
/** /**
* getInventory * getInventory
@ -107,7 +106,6 @@ class StoreApi {
$responseObject = $this->apiClient->deserialize($response,'map[string,int]'); $responseObject = $this->apiClient->deserialize($response,'map[string,int]');
return $responseObject; return $responseObject;
} }
/** /**
* placeOrder * placeOrder
* *
@ -166,7 +164,6 @@ class StoreApi {
$responseObject = $this->apiClient->deserialize($response,'Order'); $responseObject = $this->apiClient->deserialize($response,'Order');
return $responseObject; return $responseObject;
} }
/** /**
* getOrderById * getOrderById
* *
@ -230,7 +227,6 @@ class StoreApi {
$responseObject = $this->apiClient->deserialize($response,'Order'); $responseObject = $this->apiClient->deserialize($response,'Order');
return $responseObject; return $responseObject;
} }
/** /**
* deleteOrder * deleteOrder
* *
@ -290,5 +286,4 @@ class StoreApi {
} }
} }

View File

@ -29,30 +29,29 @@ class UserApi {
if (Configuration::$apiClient === null) { if (Configuration::$apiClient === null) {
Configuration::$apiClient = new ApiClient(); // create a new API client if not present Configuration::$apiClient = new ApiClient(); // create a new API client if not present
$this->apiClient = Configuration::$apiClient; $this->apiClient = Configuration::$apiClient;
} }
else else
$this->apiClient = Configuration::$apiClient; // use the default one $this->apiClient = Configuration::$apiClient; // use the default one
} else { } else {
$this->apiClient = $apiClient; // use the one provided by the user $this->apiClient = $apiClient; // use the one provided by the user
} }
} }
private $apiClient; // instance of the ApiClient private $apiClient; // instance of the ApiClient
/** /**
* get the API client * get the API client
*/ */
public function getApiClient() { public function getApiClient() {
return $this->apiClient; return $this->apiClient;
} }
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
/** /**
* createUser * createUser
@ -107,7 +106,6 @@ class UserApi {
} }
/** /**
* createUsersWithArrayInput * createUsersWithArrayInput
* *
@ -161,7 +159,6 @@ class UserApi {
} }
/** /**
* createUsersWithListInput * createUsersWithListInput
* *
@ -215,7 +212,6 @@ class UserApi {
} }
/** /**
* loginUser * loginUser
* *
@ -277,7 +273,6 @@ class UserApi {
$responseObject = $this->apiClient->deserialize($response,'string'); $responseObject = $this->apiClient->deserialize($response,'string');
return $responseObject; return $responseObject;
} }
/** /**
* logoutUser * logoutUser
* *
@ -326,7 +321,6 @@ class UserApi {
} }
/** /**
* getUserByName * getUserByName
* *
@ -390,7 +384,6 @@ class UserApi {
$responseObject = $this->apiClient->deserialize($response,'User'); $responseObject = $this->apiClient->deserialize($response,'User');
return $responseObject; return $responseObject;
} }
/** /**
* updateUser * updateUser
* *
@ -454,7 +447,6 @@ class UserApi {
} }
/** /**
* deleteUser * deleteUser
* *
@ -514,5 +506,4 @@ class UserApi {
} }
} }

View File

@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
/** /**
* *
* *
@ -61,4 +62,5 @@ class Category implements ArrayAccess {
public function offsetUnset($offset) { public function offsetUnset($offset) {
unset($this->$offset); unset($this->$offset);
} }
} }

View File

@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
/** /**
* *
* *
@ -80,4 +81,5 @@ class Order implements ArrayAccess {
public function offsetUnset($offset) { public function offsetUnset($offset) {
unset($this->$offset); unset($this->$offset);
} }
} }

View File

@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
/** /**
* *
* *
@ -80,4 +81,5 @@ class Pet implements ArrayAccess {
public function offsetUnset($offset) { public function offsetUnset($offset) {
unset($this->$offset); unset($this->$offset);
} }
} }

View File

@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
/** /**
* *
* *
@ -61,4 +62,5 @@ class Tag implements ArrayAccess {
public function offsetUnset($offset) { public function offsetUnset($offset) {
unset($this->$offset); unset($this->$offset);
} }
} }

View File

@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
/** /**
* *
* *
@ -88,4 +89,5 @@ class User implements ArrayAccess {
public function offsetUnset($offset) { public function offsetUnset($offset) {
unset($this->$offset); unset($this->$offset);
} }
} }

View File

@ -67,8 +67,8 @@ If you want to run the tests in all the python platforms:
```sh ```sh
$ make test-all $ make test-all
[... tox creates a virtualenv for every platform and runs tests inside of each] [... tox creates a virtualenv for every platform and runs tests inside of each]
py27: commands succeeded py27: commands succeeded
py34: commands succeeded py34: commands succeeded
congratulations :) congratulations :)
``` ```

View File

@ -22,282 +22,282 @@ import random
from six import iteritems from six import iteritems
try: try:
# for python3 # for python3
from urllib.parse import quote from urllib.parse import quote
except ImportError: except ImportError:
# for python2 # for python2
from urllib import quote from urllib import quote
from . import configuration from . import configuration
class ApiClient(object): class ApiClient(object):
""" """
Generic API client for Swagger client library builds Generic API client for Swagger client library builds
:param host: The base path for the server to call :param host: The base path for the server to call
:param header_name: a header to pass when making calls to the API :param header_name: a header to pass when making calls to the API
:param header_value: a header value to pass when making calls to the API :param header_value: a header value to pass when making calls to the API
""" """
def __init__(self, host=configuration.host, header_name=None, header_value=None): def __init__(self, host=configuration.host, header_name=None, header_value=None):
self.default_headers = {} self.default_headers = {}
if header_name is not None: if header_name is not None:
self.default_headers[header_name] = header_value self.default_headers[header_name] = header_value
self.host = host self.host = host
self.cookie = None self.cookie = None
# Set default User-Agent. # Set default User-Agent.
self.user_agent = 'Python-Swagger' self.user_agent = 'Python-Swagger'
@property @property
def user_agent(self): def user_agent(self):
return self.default_headers['User-Agent'] return self.default_headers['User-Agent']
@user_agent.setter @user_agent.setter
def user_agent(self, value): def user_agent(self, value):
self.default_headers['User-Agent'] = value self.default_headers['User-Agent'] = value
def set_default_header(self, header_name, header_value): def set_default_header(self, header_name, header_value):
self.default_headers[header_name] = header_value self.default_headers[header_name] = header_value
def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None, response=None, auth_settings=None): body=None, post_params=None, files=None, response=None, auth_settings=None):
# headers parameters # headers parameters
header_params = header_params or {} header_params = header_params or {}
header_params.update(self.default_headers) header_params.update(self.default_headers)
if self.cookie: if self.cookie:
header_params['Cookie'] = self.cookie header_params['Cookie'] = self.cookie
if header_params: if header_params:
header_params = self.sanitize_for_serialization(header_params) header_params = self.sanitize_for_serialization(header_params)
# path parameters # path parameters
if path_params: if path_params:
path_params = self.sanitize_for_serialization(path_params) path_params = self.sanitize_for_serialization(path_params)
for k, v in iteritems(path_params): for k, v in iteritems(path_params):
replacement = quote(str(self.to_path_value(v))) replacement = quote(str(self.to_path_value(v)))
resource_path = resource_path.replace('{' + k + '}', replacement) resource_path = resource_path.replace('{' + k + '}', replacement)
# query parameters # query parameters
if query_params: if query_params:
query_params = self.sanitize_for_serialization(query_params) query_params = self.sanitize_for_serialization(query_params)
query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)}
# post parameters # post parameters
if post_params: if post_params:
post_params = self.prepare_post_parameters(post_params, files) post_params = self.prepare_post_parameters(post_params, files)
post_params = self.sanitize_for_serialization(post_params) post_params = self.sanitize_for_serialization(post_params)
# auth setting # auth setting
self.update_params_for_auth(header_params, query_params, auth_settings) self.update_params_for_auth(header_params, query_params, auth_settings)
# body # body
if body: if body:
body = self.sanitize_for_serialization(body) body = self.sanitize_for_serialization(body)
# request url # request url
url = self.host + resource_path url = self.host + resource_path
# perform request and return response # perform request and return response
response_data = self.request(method, url, query_params=query_params, headers=header_params, response_data = self.request(method, url, query_params=query_params, headers=header_params,
post_params=post_params, body=body) post_params=post_params, body=body)
# deserialize response data # deserialize response data
if response: if response:
return self.deserialize(response_data, response) return self.deserialize(response_data, response)
else: else:
return None return None
def to_path_value(self, obj): def to_path_value(self, obj):
""" """
Convert a string or object to a path-friendly value Convert a string or object to a path-friendly value
:param obj: object or string value :param obj: object or string value
:return string: quoted value :return string: quoted value
""" """
if type(obj) == list: if type(obj) == list:
return ','.join(obj) return ','.join(obj)
else: else:
return str(obj) return str(obj)
def sanitize_for_serialization(self, obj): def sanitize_for_serialization(self, obj):
""" """
Sanitize an object for Request. Sanitize an object for Request.
If obj is None, return None. If obj is None, return None.
If obj is str, int, float, bool, return directly. If obj is str, int, float, bool, return directly.
If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is datetime.datetime, datetime.date convert to string in iso8601 format.
If obj is list, santize each element in the list. If obj is list, santize each element in the list.
If obj is dict, return the dict. If obj is dict, return the dict.
If obj is swagger model, return the properties dict. If obj is swagger model, return the properties dict.
""" """
if isinstance(obj, type(None)): if isinstance(obj, type(None)):
return None return None
elif isinstance(obj, (str, int, float, bool, tuple)): elif isinstance(obj, (str, int, float, bool, tuple)):
return obj return obj
elif isinstance(obj, list): elif isinstance(obj, list):
return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj]
elif isinstance(obj, (datetime.datetime, datetime.date)): elif isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat() return obj.isoformat()
else: else:
if isinstance(obj, dict): if isinstance(obj, dict):
obj_dict = obj obj_dict = obj
else: else:
# Convert model obj to dict except attributes `swagger_types`, `attribute_map` # Convert model obj to dict except attributes `swagger_types`, `attribute_map`
# and attributes which value is not None. # and attributes which value is not None.
# Convert attribute name to json key in model definition for request. # Convert attribute name to json key in model definition for request.
obj_dict = {obj.attribute_map[key]: val obj_dict = {obj.attribute_map[key]: val
for key, val in iteritems(obj.__dict__) for key, val in iteritems(obj.__dict__)
if key != 'swagger_types' and key != 'attribute_map' and val is not None} if key != 'swagger_types' and key != 'attribute_map' and val is not None}
return {key: self.sanitize_for_serialization(val) return {key: self.sanitize_for_serialization(val)
for key, val in iteritems(obj_dict)} for key, val in iteritems(obj_dict)}
def deserialize(self, obj, obj_class): def deserialize(self, obj, obj_class):
""" """
Derialize a JSON string into an object. Derialize a JSON string into an object.
:param obj: string or object to be deserialized :param obj: string or object to be deserialized
:param obj_class: class literal for deserialzied object, or string of class name :param obj_class: class literal for deserialzied object, or string of class name
:return object: deserialized object :return object: deserialized object
""" """
# Have to accept obj_class as string or actual type. Type could be a # Have to accept obj_class as string or actual type. Type could be a
# native Python type, or one of the model classes. # native Python type, or one of the model classes.
if type(obj_class) == str: if type(obj_class) == str:
if 'list[' in obj_class: if 'list[' in obj_class:
match = re.match('list\[(.*)\]', obj_class) match = re.match('list\[(.*)\]', obj_class)
sub_class = match.group(1) sub_class = match.group(1)
return [self.deserialize(sub_obj, sub_class) for sub_obj in obj] return [self.deserialize(sub_obj, sub_class) for sub_obj in obj]
if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']: if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']:
obj_class = eval(obj_class) obj_class = eval(obj_class)
else: # not a native type, must be model class else: # not a native type, must be model class
obj_class = eval('models.' + obj_class) obj_class = eval('models.' + obj_class)
if obj_class in [int, float, dict, list, str, bool]: if obj_class in [int, float, dict, list, str, bool]:
return obj_class(obj) return obj_class(obj)
elif obj_class == datetime: elif obj_class == datetime:
return self.__parse_string_to_datetime(obj) return self.__parse_string_to_datetime(obj)
instance = obj_class() instance = obj_class()
for attr, attr_type in iteritems(instance.swagger_types): for attr, attr_type in iteritems(instance.swagger_types):
if obj is not None and instance.attribute_map[attr] in obj and type(obj) in [list, dict]: if obj is not None and instance.attribute_map[attr] in obj and type(obj) in [list, dict]:
value = obj[instance.attribute_map[attr]] value = obj[instance.attribute_map[attr]]
if attr_type in ['str', 'int', 'float', 'bool']: if attr_type in ['str', 'int', 'float', 'bool']:
attr_type = eval(attr_type) attr_type = eval(attr_type)
try: try:
value = attr_type(value) value = attr_type(value)
except UnicodeEncodeError: except UnicodeEncodeError:
value = unicode(value) value = unicode(value)
except TypeError: except TypeError:
value = value value = value
setattr(instance, attr, value) setattr(instance, attr, value)
elif attr_type == 'datetime': elif attr_type == 'datetime':
setattr(instance, attr, self.__parse_string_to_datetime(value)) setattr(instance, attr, self.__parse_string_to_datetime(value))
elif 'list[' in attr_type: elif 'list[' in attr_type:
match = re.match('list\[(.*)\]', attr_type) match = re.match('list\[(.*)\]', attr_type)
sub_class = match.group(1) sub_class = match.group(1)
sub_values = [] sub_values = []
if not value: if not value:
setattr(instance, attr, None) setattr(instance, attr, None)
else: else:
for sub_value in value: for sub_value in value:
sub_values.append(self.deserialize(sub_value, sub_class)) sub_values.append(self.deserialize(sub_value, sub_class))
setattr(instance, attr, sub_values) setattr(instance, attr, sub_values)
else: else:
setattr(instance, attr, self.deserialize(value, attr_type)) setattr(instance, attr, self.deserialize(value, attr_type))
return instance return instance
def __parse_string_to_datetime(self, string): def __parse_string_to_datetime(self, string):
""" """
Parse datetime in string to datetime. Parse datetime in string to datetime.
The string should be in iso8601 datetime format. The string should be in iso8601 datetime format.
""" """
try: try:
from dateutil.parser import parse from dateutil.parser import parse
return parse(string) return parse(string)
except ImportError: except ImportError:
return string return string
def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): def request(self, method, url, query_params=None, headers=None, post_params=None, body=None):
""" """
Perform http request using RESTClient. Perform http request using RESTClient.
""" """
if method == "GET": if method == "GET":
return RESTClient.GET(url, query_params=query_params, headers=headers) return RESTClient.GET(url, query_params=query_params, headers=headers)
elif method == "HEAD": elif method == "HEAD":
return RESTClient.HEAD(url, query_params=query_params, headers=headers) return RESTClient.HEAD(url, query_params=query_params, headers=headers)
elif method == "POST": elif method == "POST":
return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) return RESTClient.POST(url, headers=headers, post_params=post_params, body=body)
elif method == "PUT": elif method == "PUT":
return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body)
elif method == "PATCH": elif method == "PATCH":
return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body)
elif method == "DELETE": elif method == "DELETE":
return RESTClient.DELETE(url, query_params=query_params, headers=headers) return RESTClient.DELETE(url, query_params=query_params, headers=headers)
else: else:
raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`")
def prepare_post_parameters(self, post_params=None, files=None): def prepare_post_parameters(self, post_params=None, files=None):
params = {} params = {}
if post_params: if post_params:
params.update(post_params) params.update(post_params)
if files: if files:
for k, v in iteritems(files): for k, v in iteritems(files):
if v: if v:
with open(v, 'rb') as f: with open(v, 'rb') as f:
filename = os.path.basename(f.name) filename = os.path.basename(f.name)
filedata = f.read() filedata = f.read()
mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
params[k] = tuple([filename, filedata, mimetype]) params[k] = tuple([filename, filedata, mimetype])
return params return params
def select_header_accept(self, accepts): def select_header_accept(self, accepts):
""" """
Return `Accept` based on an array of accepts provided Return `Accept` based on an array of accepts provided
""" """
if not accepts: if not accepts:
return return
accepts = list(map(lambda x: x.lower(), accepts)) accepts = list(map(lambda x: x.lower(), accepts))
if 'application/json' in accepts: if 'application/json' in accepts:
return 'application/json' return 'application/json'
else: else:
return ', '.join(accepts) return ', '.join(accepts)
def select_header_content_type(self, content_types): def select_header_content_type(self, content_types):
""" """
Return `Content-Type` baseed on an array of content_types provided Return `Content-Type` baseed on an array of content_types provided
""" """
if not content_types: if not content_types:
return 'application/json' return 'application/json'
content_types = list(map(lambda x: x.lower(), content_types)) content_types = list(map(lambda x: x.lower(), content_types))
if 'application/json' in content_types: if 'application/json' in content_types:
return 'application/json' return 'application/json'
else: else:
return content_types[0] return content_types[0]
def update_params_for_auth(self, headers, querys, auth_settings): def update_params_for_auth(self, headers, querys, auth_settings):
""" """
Update header and query params based on authentication setting Update header and query params based on authentication setting
""" """
if not auth_settings: if not auth_settings:
return return
for auth in auth_settings: for auth in auth_settings:
auth_setting = configuration.auth_settings().get(auth) auth_setting = configuration.auth_settings().get(auth)
if auth_setting: if auth_setting:
if auth_setting['in'] == 'header': if auth_setting['in'] == 'header':
headers[auth_setting['key']] = auth_setting['value'] headers[auth_setting['key']] = auth_setting['value']
elif auth_setting['in'] == 'query': elif auth_setting['in'] == 'query':
querys[auth_setting['key']] = auth_setting['value'] querys[auth_setting['key']] = auth_setting['value']
else: else:
raise ValueError('Authentication token must be in `query` or `header`') raise ValueError('Authentication token must be in `query` or `header`')

View File

@ -5,17 +5,17 @@
PetApi.py PetApi.py
Copyright 2015 SmartBear Software Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
""" """
@ -30,7 +30,7 @@ from six import iteritems
from .. import configuration from .. import configuration
from ..api_client import ApiClient from ..api_client import ApiClient
class PetApi(object): class PetApi(object):
def __init__(self, api_client=None): def __init__(self, api_client=None):
if api_client: if api_client:

View File

@ -5,17 +5,17 @@
StoreApi.py StoreApi.py
Copyright 2015 SmartBear Software Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
""" """
@ -30,7 +30,7 @@ from six import iteritems
from .. import configuration from .. import configuration
from ..api_client import ApiClient from ..api_client import ApiClient
class StoreApi(object): class StoreApi(object):
def __init__(self, api_client=None): def __init__(self, api_client=None):
if api_client: if api_client:

View File

@ -5,17 +5,17 @@
UserApi.py UserApi.py
Copyright 2015 SmartBear Software Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
""" """
@ -30,7 +30,7 @@ from six import iteritems
from .. import configuration from .. import configuration
from ..api_client import ApiClient from ..api_client import ApiClient
class UserApi(object): class UserApi(object):
def __init__(self, api_client=None): def __init__(self, api_client=None):
if api_client: if api_client:

View File

@ -3,22 +3,22 @@ import base64
import urllib3 import urllib3
def get_api_key_with_prefix(key): def get_api_key_with_prefix(key):
global api_key global api_key
global api_key_prefix global api_key_prefix
if api_key.get(key) and api_key_prefix.get(key): if api_key.get(key) and api_key_prefix.get(key):
return api_key_prefix[key] + ' ' + api_key[key] return api_key_prefix[key] + ' ' + api_key[key]
elif api_key.get(key): elif api_key.get(key):
return api_key[key] return api_key[key]
def get_basic_auth_token(): def get_basic_auth_token():
global username global username
global password global password
return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization')
def auth_settings(): def auth_settings():
return { return {
'api_key': { 'api_key': {
'type': 'api_key', 'type': 'api_key',
'in': 'header', 'in': 'header',
@ -26,7 +26,7 @@ def auth_settings():
'value': get_api_key_with_prefix('api_key') 'value': get_api_key_with_prefix('api_key')
}, },
} }
# Default Base url # Default Base url
host = "http://petstore.swagger.io/v2" host = "http://petstore.swagger.io/v2"

View File

@ -4,20 +4,21 @@
""" """
Copyright 2015 SmartBear Software Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
""" """
class Category(object):
class Category(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
@ -56,3 +57,4 @@ class Category(object):
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@ -4,20 +4,21 @@
""" """
Copyright 2015 SmartBear Software Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
""" """
class Order(object):
class Order(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
@ -76,3 +77,4 @@ class Order(object):
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@ -4,20 +4,21 @@
""" """
Copyright 2015 SmartBear Software Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
""" """
class Pet(object):
class Pet(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
@ -76,3 +77,4 @@ class Pet(object):
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@ -4,20 +4,21 @@
""" """
Copyright 2015 SmartBear Software Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
""" """
class Tag(object):
class Tag(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
@ -56,3 +57,4 @@ class Tag(object):
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@ -4,20 +4,21 @@
""" """
Copyright 2015 SmartBear Software Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
You may obtain a copy of the License at You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
""" """
class User(object):
class User(object):
""" """
NOTE: This class is auto generated by the swagger code generator program. NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. Do not edit the class manually.
@ -86,3 +87,4 @@ class User(object):
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@ -15,239 +15,239 @@ import certifi
from six import iteritems from six import iteritems
try: try:
import urllib3 import urllib3
except ImportError: except ImportError:
raise ImportError('Swagger python client requires urllib3.') raise ImportError('Swagger python client requires urllib3.')
try: try:
# for python3 # for python3
from urllib.parse import urlencode from urllib.parse import urlencode
except ImportError: except ImportError:
# for python2 # for python2
from urllib import urlencode from urllib import urlencode
class RESTResponse(io.IOBase): class RESTResponse(io.IOBase):
def __init__(self, resp): def __init__(self, resp):
self.urllib3_response = resp self.urllib3_response = resp
self.status = resp.status self.status = resp.status
self.reason = resp.reason self.reason = resp.reason
self.data = resp.data self.data = resp.data
def getheaders(self): def getheaders(self):
""" """
Returns a dictionary of the response headers. Returns a dictionary of the response headers.
""" """
return self.urllib3_response.getheaders() return self.urllib3_response.getheaders()
def getheader(self, name, default=None): def getheader(self, name, default=None):
""" """
Returns a given response header. Returns a given response header.
""" """
return self.urllib3_response.getheader(name, default) return self.urllib3_response.getheader(name, default)
class RESTClientObject(object): class RESTClientObject(object):
def __init__(self, pools_size=4): def __init__(self, pools_size=4):
# http pool manager # http pool manager
self.pool_manager = urllib3.PoolManager( self.pool_manager = urllib3.PoolManager(
num_pools=pools_size num_pools=pools_size
) )
# https pool manager # https pool manager
# certificates validated using Mozillas root certificates # certificates validated using Mozillas root certificates
self.ssl_pool_manager = urllib3.PoolManager( self.ssl_pool_manager = urllib3.PoolManager(
num_pools=pools_size, num_pools=pools_size,
cert_reqs=ssl.CERT_REQUIRED, cert_reqs=ssl.CERT_REQUIRED,
ca_certs=certifi.where() ca_certs=certifi.where()
) )
def agent(self, url): def agent(self, url):
""" """
Return proper pool manager for the http\https schemes. Return proper pool manager for the http\https schemes.
""" """
url = urllib3.util.url.parse_url(url) url = urllib3.util.url.parse_url(url)
scheme = url.scheme scheme = url.scheme
if scheme == 'https': if scheme == 'https':
return self.ssl_pool_manager return self.ssl_pool_manager
else: else:
return self.pool_manager return self.pool_manager
def request(self, method, url, query_params=None, headers=None, def request(self, method, url, query_params=None, headers=None,
body=None, post_params=None): body=None, post_params=None):
""" """
:param method: http request method :param method: http request method
:param url: http request url :param url: http request url
:param query_params: query parameters in the url :param query_params: query parameters in the url
:param headers: http request headers :param headers: http request headers
:param body: request json body, for `application/json` :param body: request json body, for `application/json`
:param post_params: request post parameters, `application/x-www-form-urlencode` :param post_params: request post parameters, `application/x-www-form-urlencode`
and `multipart/form-data` and `multipart/form-data`
""" """
method = method.upper() method = method.upper()
assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH']
if post_params and body: if post_params and body:
raise ValueError("body parameter cannot be used with post_params parameter.") raise ValueError("body parameter cannot be used with post_params parameter.")
post_params = post_params or {} post_params = post_params or {}
headers = headers or {} headers = headers or {}
if 'Content-Type' not in headers: if 'Content-Type' not in headers:
headers['Content-Type'] = 'application/json' headers['Content-Type'] = 'application/json'
# For `POST`, `PUT`, `PATCH` # For `POST`, `PUT`, `PATCH`
if method in ['POST', 'PUT', 'PATCH']: if method in ['POST', 'PUT', 'PATCH']:
if query_params: if query_params:
url += '?' + urlencode(query_params) url += '?' + urlencode(query_params)
if headers['Content-Type'] == 'application/json': if headers['Content-Type'] == 'application/json':
r = self.agent(url).request(method, url, r = self.agent(url).request(method, url,
body=json.dumps(body), body=json.dumps(body),
headers=headers) headers=headers)
if headers['Content-Type'] == 'application/x-www-form-urlencoded': if headers['Content-Type'] == 'application/x-www-form-urlencoded':
r = self.agent(url).request(method, url, r = self.agent(url).request(method, url,
fields=post_params, fields=post_params,
encode_multipart=False, encode_multipart=False,
headers=headers) headers=headers)
if headers['Content-Type'] == 'multipart/form-data': if headers['Content-Type'] == 'multipart/form-data':
# must del headers['Content-Type'], or the correct Content-Type # must del headers['Content-Type'], or the correct Content-Type
# which generated by urllib3 will be overwritten. # which generated by urllib3 will be overwritten.
del headers['Content-Type'] del headers['Content-Type']
r = self.agent(url).request(method, url, r = self.agent(url).request(method, url,
fields=post_params, fields=post_params,
encode_multipart=True, encode_multipart=True,
headers=headers) headers=headers)
# For `GET`, `HEAD`, `DELETE` # For `GET`, `HEAD`, `DELETE`
else: else:
r = self.agent(url).request(method, url, r = self.agent(url).request(method, url,
fields=query_params, fields=query_params,
headers=headers) headers=headers)
r = RESTResponse(r) r = RESTResponse(r)
if r.status not in range(200, 206): if r.status not in range(200, 206):
raise ApiException(r) raise ApiException(r)
return self.process_response(r) return self.process_response(r)
def process_response(self, response): def process_response(self, response):
# In the python 3, the response.data is bytes. # In the python 3, the response.data is bytes.
# we need to decode it to string. # we need to decode it to string.
if sys.version_info > (3,): if sys.version_info > (3,):
data = response.data.decode('utf8') data = response.data.decode('utf8')
else: else:
data = response.data data = response.data
try: try:
resp = json.loads(data) resp = json.loads(data)
except ValueError: except ValueError:
resp = data resp = data
return resp return resp
def GET(self, url, headers=None, query_params=None): def GET(self, url, headers=None, query_params=None):
return self.request("GET", url, headers=headers, query_params=query_params) return self.request("GET", url, headers=headers, query_params=query_params)
def HEAD(self, url, headers=None, query_params=None): def HEAD(self, url, headers=None, query_params=None):
return self.request("HEAD", url, headers=headers, query_params=query_params) return self.request("HEAD", url, headers=headers, query_params=query_params)
def DELETE(self, url, headers=None, query_params=None): def DELETE(self, url, headers=None, query_params=None):
return self.request("DELETE", url, headers=headers, query_params=query_params) return self.request("DELETE", url, headers=headers, query_params=query_params)
def POST(self, url, headers=None, post_params=None, body=None): def POST(self, url, headers=None, post_params=None, body=None):
return self.request("POST", url, headers=headers, post_params=post_params, body=body) return self.request("POST", url, headers=headers, post_params=post_params, body=body)
def PUT(self, url, headers=None, post_params=None, body=None): def PUT(self, url, headers=None, post_params=None, body=None):
return self.request("PUT", url, headers=headers, post_params=post_params, body=body) return self.request("PUT", url, headers=headers, post_params=post_params, body=body)
def PATCH(self, url, headers=None, post_params=None, body=None): def PATCH(self, url, headers=None, post_params=None, body=None):
return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) return self.request("PATCH", url, headers=headers, post_params=post_params, body=body)
class ApiException(Exception): class ApiException(Exception):
""" """
Non-2xx HTTP response Non-2xx HTTP response
""" """
def __init__(self, http_resp): def __init__(self, http_resp):
self.status = http_resp.status self.status = http_resp.status
self.reason = http_resp.reason self.reason = http_resp.reason
self.body = http_resp.data self.body = http_resp.data
self.headers = http_resp.getheaders() self.headers = http_resp.getheaders()
# In the python 3, the self.body is bytes. # In the python 3, the self.body is bytes.
# we need to decode it to string. # we need to decode it to string.
if sys.version_info > (3,): if sys.version_info > (3,):
data = self.body.decode('utf8') data = self.body.decode('utf8')
else: else:
data = self.body data = self.body
try: try:
self.body = json.loads(data) self.body = json.loads(data)
except ValueError: except ValueError:
self.body = data self.body = data
def __str__(self): def __str__(self):
""" """
Custom error response messages Custom error response messages
""" """
return "({0})\n"\ return "({0})\n"\
"Reason: {1}\n"\ "Reason: {1}\n"\
"HTTP response headers: {2}\n"\ "HTTP response headers: {2}\n"\
"HTTP response body: {3}\n".\ "HTTP response body: {3}\n".\
format(self.status, self.reason, self.headers, self.body) format(self.status, self.reason, self.headers, self.body)
class RESTClient(object): class RESTClient(object):
""" """
A class with all class methods to perform JSON requests. A class with all class methods to perform JSON requests.
""" """
IMPL = RESTClientObject() IMPL = RESTClientObject()
@classmethod @classmethod
def request(cls, *n, **kw): def request(cls, *n, **kw):
""" """
Perform a REST request and parse the response. Perform a REST request and parse the response.
""" """
return cls.IMPL.request(*n, **kw) return cls.IMPL.request(*n, **kw)
@classmethod @classmethod
def GET(cls, *n, **kw): def GET(cls, *n, **kw):
""" """
Perform a GET request using `RESTClient.request()`. Perform a GET request using `RESTClient.request()`.
""" """
return cls.IMPL.GET(*n, **kw) return cls.IMPL.GET(*n, **kw)
@classmethod @classmethod
def HEAD(cls, *n, **kw): def HEAD(cls, *n, **kw):
""" """
Perform a HEAD request using `RESTClient.request()`. Perform a HEAD request using `RESTClient.request()`.
""" """
return cls.IMPL.GET(*n, **kw) return cls.IMPL.GET(*n, **kw)
@classmethod @classmethod
def POST(cls, *n, **kw): def POST(cls, *n, **kw):
""" """
Perform a POST request using `RESTClient.request()` Perform a POST request using `RESTClient.request()`
""" """
return cls.IMPL.POST(*n, **kw) return cls.IMPL.POST(*n, **kw)
@classmethod @classmethod
def PUT(cls, *n, **kw): def PUT(cls, *n, **kw):
""" """
Perform a PUT request using `RESTClient.request()` Perform a PUT request using `RESTClient.request()`
""" """
return cls.IMPL.PUT(*n, **kw) return cls.IMPL.PUT(*n, **kw)
@classmethod @classmethod
def PATCH(cls, *n, **kw): def PATCH(cls, *n, **kw):
""" """
Perform a PATCH request using `RESTClient.request()` Perform a PATCH request using `RESTClient.request()`
""" """
return cls.IMPL.PATCH(*n, **kw) return cls.IMPL.PATCH(*n, **kw)
@classmethod @classmethod
def DELETE(cls, *n, **kw): def DELETE(cls, *n, **kw):
""" """
Perform a DELETE request using `RESTClient.request()` Perform a DELETE request using `RESTClient.request()`
""" """
return cls.IMPL.DELETE(*n, **kw) return cls.IMPL.DELETE(*n, **kw)

View File

@ -3,18 +3,18 @@ from setuptools import setup, find_packages
# To install the library, open a Terminal shell, then run this # To install the library, open a Terminal shell, then run this
# file by typing: # file by typing:
# #
# python setup.py install # python setup.py install
# #
# You need to have the setuptools module installed. # You need to have the setuptools module installed.
# Try reading the setuptools documentation: # Try reading the setuptools documentation:
# http://pypi.python.org/pypi/setuptools # http://pypi.python.org/pypi/setuptools
REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi"] REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi"]
setup( setup(
name="SwaggerPetstore", name="SwaggerPetstore",
version="1.0.0", version="1.0.0",
description="Swagger Petstore", description="Swagger Petstore",
@ -27,7 +27,7 @@ setup(
long_description="""\ long_description="""\
This is a sample server Petstore server. You can find out more about Swagger at &lt;a href=\&quot;http://swagger.io\&quot;&gt;http://swagger.io&lt;/a&gt; or on irc.freenode.net, #swagger. For this sample, you can use the api key \&quot;special-key\&quot; to test the authorization filters This is a sample server Petstore server. You can find out more about Swagger at &lt;a href=\&quot;http://swagger.io\&quot;&gt;http://swagger.io&lt;/a&gt; or on irc.freenode.net, #swagger. For this sample, you can use the api key \&quot;special-key\&quot; to test the authorization filters
""" """
) )

View File

@ -1,73 +1,77 @@
#include "SWGCategory.h" #include "SWGCategory.h"
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include <QJsonDocument> #include
#include <QJsonArray> <QJsonDocument>
#include <QObject> #include
#include <QDebug> <QJsonArray>
#include
<QObject>
#include
<QDebug>
namespace Swagger { namespace Swagger {
SWGCategory::SWGCategory(QString* json) { SWGCategory::SWGCategory(QString* json) {
init(); init();
this->fromJson(*json); this->fromJson(*json);
} }
SWGCategory::SWGCategory() { SWGCategory::SWGCategory() {
init(); init();
} }
SWGCategory::~SWGCategory() { SWGCategory::~SWGCategory() {
this->cleanup(); this->cleanup();
} }
void void
SWGCategory::init() { SWGCategory::init() {
id = 0L; id = 0L;
name = new QString(""); name = new QString("");
} }
void void
SWGCategory::cleanup() { SWGCategory::cleanup() {
if(name != NULL) { if(name != NULL) {
delete name; delete name;
} }
} }
SWGCategory* SWGCategory*
SWGCategory::fromJson(QString &json) { SWGCategory::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object(); QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject); this->fromJsonObject(jsonObject);
return this; return this;
} }
void void
SWGCategory::fromJsonObject(QJsonObject &pJson) { SWGCategory::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", ""); setValue(&id, pJson["id"], "qint64", "");
setValue(&name, pJson["name"], "QString", "QString"); setValue(&name, pJson["name"], "QString", "QString");
} }
QString QString
SWGCategory::asJson () SWGCategory::asJson ()
{ {
QJsonObject* obj = this->asJsonObject(); QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj); QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
return QString(bytes); return QString(bytes);
} }
QJsonObject* QJsonObject*
SWGCategory::asJsonObject() { SWGCategory::asJsonObject() {
QJsonObject* obj = new QJsonObject(); QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
@ -79,27 +83,30 @@ SWGCategory::asJsonObject() {
return obj; return obj;
} }
qint64
SWGCategory::getId() { qint64
SWGCategory::getId() {
return id; return id;
} }
void void
SWGCategory::setId(qint64 id) { SWGCategory::setId(qint64 id) {
this->id = id; this->id = id;
} }
QString*
SWGCategory::getName() { QString*
SWGCategory::getName() {
return name; return name;
} }
void void
SWGCategory::setName(QString* name) { SWGCategory::setName(QString* name) {
this->name = name; this->name = name;
} }
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -1,24 +1,25 @@
/* /*
* SWGCategory.h * SWGCategory.h
* *
* *
*/ */
#ifndef SWGCategory_H_ #ifndef SWGCategory_H_
#define SWGCategory_H_ #define SWGCategory_H_
#include <QJsonObject> #include
<QJsonObject>
#include <QString> #include <QString>
#include "SWGObject.h" #include "SWGObject.h"
namespace Swagger { namespace Swagger {
class SWGCategory: public SWGObject { class SWGCategory: public SWGObject {
public: public:
SWGCategory(); SWGCategory();
SWGCategory(QString* json); SWGCategory(QString* json);
virtual ~SWGCategory(); virtual ~SWGCategory();
@ -36,12 +37,12 @@ public:
void setName(QString* name); void setName(QString* name);
private: private:
qint64 id; qint64 id;
QString* name; QString* name;
}; };
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* SWGCategory_H_ */ #endif /* SWGCategory_H_ */

View File

@ -1,32 +1,43 @@
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include "SWGModelFactory.h" #include "SWGModelFactory.h"
#include "SWGObject.h" #include "SWGObject.h"
#import <QDebug> #import
#import <QJsonArray> <QDebug>
#import <QJsonValue> #import
<QJsonArray>
#import
<QJsonValue>
namespace Swagger { namespace Swagger {
void void
setValue(void* value, QJsonValue obj, QString type, QString complexType) { setValue(void* value, QJsonValue obj, QString type, QString complexType) {
if(value == NULL) { if(value == NULL) {
// can't set value with a null pointer // can't set value with a null pointer
return; return;
} }
if(QStringLiteral("bool").compare(type) == 0) { if(QStringLiteral("bool").compare(type) == 0) {
bool * val = static_cast<bool*>(value); bool * val = static_cast
<bool
*>(value);
*val = obj.toBool(); *val = obj.toBool();
} }
else if(QStringLiteral("qint32").compare(type) == 0) { else if(QStringLiteral("qint32").compare(type) == 0) {
qint32 *val = static_cast<qint32*>(value); qint32 *val = static_cast
<qint32
*>(value);
*val = obj.toInt(); *val = obj.toInt();
} }
else if(QStringLiteral("qint64").compare(type) == 0) { else if(QStringLiteral("qint64").compare(type) == 0) {
qint64 *val = static_cast<qint64*>(value); qint64 *val = static_cast
<qint64
*>(value);
*val = obj.toVariant().toLongLong(); *val = obj.toVariant().toLongLong();
} }
else if (QStringLiteral("QString").compare(type) == 0) { else if (QStringLiteral("QString").compare(type) == 0) {
QString **val = static_cast<QString**>(value); QString **val = static_cast
<QString
**>(value);
if(val != NULL) { if(val != NULL) {
if(!obj.isNull()) { if(!obj.isNull()) {
@ -51,14 +62,20 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) {
SWGObject * so = (SWGObject*)Swagger::create(type); SWGObject * so = (SWGObject*)Swagger::create(type);
if(so != NULL) { if(so != NULL) {
so->fromJsonObject(jsonObj); so->fromJsonObject(jsonObj);
SWGObject **val = static_cast<SWGObject**>(value); SWGObject **val = static_cast
<SWGObject
**>(value);
delete *val; delete *val;
*val = so; *val = so;
} }
} }
else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) { else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) {
// list of values // list of values
QList<void*>* output = new QList<void*>(); QList
<void
*>* output = new QList
<void
*>();
QJsonArray arr = obj.toArray(); QJsonArray arr = obj.toArray();
foreach (const QJsonValue & jval, arr) { foreach (const QJsonValue & jval, arr) {
if(complexType.startsWith("SWG")) { if(complexType.startsWith("SWG")) {
@ -88,19 +105,25 @@ setValue(void* value, QJsonValue obj, QString type, QString complexType) {
} }
} }
} }
QList<void*> **val = static_cast<QList<void*>**>(value); QList
<void
*> **val = static_cast
<QList
<void
*>**>(value);
delete *val; delete *val;
*val = output; *val = output;
} }
} }
void void
toJsonValue(QString name, void* value, QJsonObject* output, QString type) { toJsonValue(QString name, void* value, QJsonObject* output, QString type) {
if(value == NULL) { if(value == NULL) {
return; return;
} }
if(type.startsWith("SWG")) { if(type.startsWith("SWG")) {
SWGObject *swgObject = reinterpret_cast<SWGObject *>(value); SWGObject *swgObject = reinterpret_cast
<SWGObject *>(value);
if(swgObject != NULL) { if(swgObject != NULL) {
QJsonObject* o = (*swgObject).asJsonObject(); QJsonObject* o = (*swgObject).asJsonObject();
if(name != NULL) { if(name != NULL) {
@ -116,51 +139,63 @@ toJsonValue(QString name, void* value, QJsonObject* output, QString type) {
} }
} }
else if(QStringLiteral("QString").compare(type) == 0) { else if(QStringLiteral("QString").compare(type) == 0) {
QString* str = static_cast<QString*>(value); QString* str = static_cast
<QString
*>(value);
output->insert(name, QJsonValue(*str)); output->insert(name, QJsonValue(*str));
} }
else if(QStringLiteral("qint32").compare(type) == 0) { else if(QStringLiteral("qint32").compare(type) == 0) {
qint32* str = static_cast<qint32*>(value); qint32* str = static_cast
<qint32
*>(value);
output->insert(name, QJsonValue(*str)); output->insert(name, QJsonValue(*str));
} }
else if(QStringLiteral("qint64").compare(type) == 0) { else if(QStringLiteral("qint64").compare(type) == 0) {
qint64* str = static_cast<qint64*>(value); qint64* str = static_cast
<qint64
*>(value);
output->insert(name, QJsonValue(*str)); output->insert(name, QJsonValue(*str));
} }
else if(QStringLiteral("bool").compare(type) == 0) { else if(QStringLiteral("bool").compare(type) == 0) {
bool* str = static_cast<bool*>(value); bool* str = static_cast
<bool
*>(value);
output->insert(name, QJsonValue(*str)); output->insert(name, QJsonValue(*str));
} }
} }
void void
toJsonArray(QList<void*>* value, QJsonArray* output, QString innerName, QString innerType) { toJsonArray(QList
<void
*>* value, QJsonArray* output, QString innerName, QString innerType) {
foreach(void* obj, *value) { foreach(void* obj, *value) {
QJsonObject element; QJsonObject element;
toJsonValue(NULL, obj, &element, innerType); toJsonValue(NULL, obj, &element, innerType);
output->append(element); output->append(element);
} }
} }
QString QString
stringValue(QString* value) { stringValue(QString* value) {
QString* str = static_cast<QString*>(value); QString* str = static_cast
<QString
*>(value);
return QString(*str); return QString(*str);
} }
QString QString
stringValue(qint32 value) { stringValue(qint32 value) {
return QString::number(value); return QString::number(value);
} }
QString QString
stringValue(qint64 value) { stringValue(qint64 value) {
return QString::number(value); return QString::number(value);
} }
QString QString
stringValue(bool value) { stringValue(bool value) {
return QString(value ? "true" : "false"); return QString(value ? "true" : "false");
} }
} /* namespace Swagger */ } /* namespace Swagger */

View File

@ -1,17 +1,20 @@
#ifndef SWGHELPERS_H #ifndef SWGHELPERS_H
#define SWGHELPERS_H #define SWGHELPERS_H
#include <QJsonValue> #include
<QJsonValue>
namespace Swagger { namespace Swagger {
void setValue(void* value, QJsonValue obj, QString type, QString complexType); void setValue(void* value, QJsonValue obj, QString type, QString complexType);
void toJsonArray(QList<void*>* value, QJsonArray* output, QString innerName, QString innerType); void toJsonArray(QList
<void
*>* value, QJsonArray* output, QString innerName, QString innerType);
void toJsonValue(QString name, void* value, QJsonObject* output, QString type); void toJsonValue(QString name, void* value, QJsonObject* output, QString type);
bool isCompatibleJsonValue(QString type); bool isCompatibleJsonValue(QString type);
QString stringValue(QString* value); QString stringValue(QString* value);
QString stringValue(qint32 value); QString stringValue(qint32 value);
QString stringValue(qint64 value); QString stringValue(qint64 value);
QString stringValue(bool value); QString stringValue(bool value);
} }
#endif // SWGHELPERS_H #endif // SWGHELPERS_H

View File

@ -2,44 +2,45 @@
#define ModelFactory_H_ #define ModelFactory_H_
#include "SWGUser.h" #include "SWGUser.h"
#include "SWGCategory.h" #include "SWGCategory.h"
#include "SWGPet.h" #include "SWGPet.h"
#include "SWGTag.h" #include "SWGTag.h"
#include "SWGOrder.h" #include "SWGOrder.h"
namespace Swagger { namespace Swagger {
inline void* create(QString type) { inline void* create(QString type) {
if(QString("SWGUser").compare(type) == 0) { if(QString("SWGUser").compare(type) == 0) {
return new SWGUser(); return new SWGUser();
} }
if(QString("SWGCategory").compare(type) == 0) { if(QString("SWGCategory").compare(type) == 0) {
return new SWGCategory(); return new SWGCategory();
} }
if(QString("SWGPet").compare(type) == 0) { if(QString("SWGPet").compare(type) == 0) {
return new SWGPet(); return new SWGPet();
} }
if(QString("SWGTag").compare(type) == 0) { if(QString("SWGTag").compare(type) == 0) {
return new SWGTag(); return new SWGTag();
} }
if(QString("SWGOrder").compare(type) == 0) { if(QString("SWGOrder").compare(type) == 0) {
return new SWGOrder(); return new SWGOrder();
} }
return NULL; return NULL;
} }
inline void* create(QString json, QString type) { inline void* create(QString json, QString type) {
void* val = create(type); void* val = create(type);
if(val != NULL) { if(val != NULL) {
SWGObject* obj = static_cast<SWGObject*>(val); SWGObject* obj = static_cast
return obj->fromJson(json); <SWGObject*>(val);
} return obj->fromJson(json);
if(type.startsWith("QString")) { }
return new QString(); if(type.startsWith("QString")) {
} return new QString();
return NULL; }
} return NULL;
}
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* ModelFactory_H_ */ #endif /* ModelFactory_H_ */

View File

@ -1,9 +1,10 @@
#ifndef _SWG_OBJECT_H_ #ifndef _SWG_OBJECT_H_
#define _SWG_OBJECT_H_ #define _SWG_OBJECT_H_
#include <QJsonValue> #include
<QJsonValue>
class SWGObject { class SWGObject {
public: public:
virtual QJsonObject* asJsonObject() { virtual QJsonObject* asJsonObject() {
return NULL; return NULL;
@ -19,6 +20,6 @@ class SWGObject {
virtual QString asJson() { virtual QString asJson() {
return QString(""); return QString("");
} }
}; };
#endif /* _SWG_OBJECT_H_ */ #endif /* _SWG_OBJECT_H_ */

View File

@ -1,31 +1,35 @@
#include "SWGOrder.h" #include "SWGOrder.h"
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include <QJsonDocument> #include
#include <QJsonArray> <QJsonDocument>
#include <QObject> #include
#include <QDebug> <QJsonArray>
#include
<QObject>
#include
<QDebug>
namespace Swagger { namespace Swagger {
SWGOrder::SWGOrder(QString* json) { SWGOrder::SWGOrder(QString* json) {
init(); init();
this->fromJson(*json); this->fromJson(*json);
} }
SWGOrder::SWGOrder() { SWGOrder::SWGOrder() {
init(); init();
} }
SWGOrder::~SWGOrder() { SWGOrder::~SWGOrder() {
this->cleanup(); this->cleanup();
} }
void void
SWGOrder::init() { SWGOrder::init() {
id = 0L; id = 0L;
petId = 0L; petId = 0L;
quantity = 0; quantity = 0;
@ -33,10 +37,10 @@ SWGOrder::init() {
status = new QString(""); status = new QString("");
complete = false; complete = false;
} }
void void
SWGOrder::cleanup() { SWGOrder::cleanup() {
@ -48,19 +52,19 @@ SWGOrder::cleanup() {
} }
} }
SWGOrder* SWGOrder*
SWGOrder::fromJson(QString &json) { SWGOrder::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object(); QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject); this->fromJsonObject(jsonObject);
return this; return this;
} }
void void
SWGOrder::fromJsonObject(QJsonObject &pJson) { SWGOrder::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", ""); setValue(&id, pJson["id"], "qint64", "");
setValue(&petId, pJson["petId"], "qint64", ""); setValue(&petId, pJson["petId"], "qint64", "");
setValue(&quantity, pJson["quantity"], "qint32", ""); setValue(&quantity, pJson["quantity"], "qint32", "");
@ -68,20 +72,20 @@ SWGOrder::fromJsonObject(QJsonObject &pJson) {
setValue(&status, pJson["status"], "QString", "QString"); setValue(&status, pJson["status"], "QString", "QString");
setValue(&complete, pJson["complete"], "bool", ""); setValue(&complete, pJson["complete"], "bool", "");
} }
QString QString
SWGOrder::asJson () SWGOrder::asJson ()
{ {
QJsonObject* obj = this->asJsonObject(); QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj); QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
return QString(bytes); return QString(bytes);
} }
QJsonObject* QJsonObject*
SWGOrder::asJsonObject() { SWGOrder::asJsonObject() {
QJsonObject* obj = new QJsonObject(); QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
obj->insert("petId", QJsonValue(petId)); obj->insert("petId", QJsonValue(petId));
@ -102,63 +106,70 @@ SWGOrder::asJsonObject() {
return obj; return obj;
} }
qint64
SWGOrder::getId() { qint64
SWGOrder::getId() {
return id; return id;
} }
void void
SWGOrder::setId(qint64 id) { SWGOrder::setId(qint64 id) {
this->id = id; this->id = id;
} }
qint64
SWGOrder::getPetId() { qint64
SWGOrder::getPetId() {
return petId; return petId;
} }
void void
SWGOrder::setPetId(qint64 petId) { SWGOrder::setPetId(qint64 petId) {
this->petId = petId; this->petId = petId;
} }
qint32
SWGOrder::getQuantity() { qint32
SWGOrder::getQuantity() {
return quantity; return quantity;
} }
void void
SWGOrder::setQuantity(qint32 quantity) { SWGOrder::setQuantity(qint32 quantity) {
this->quantity = quantity; this->quantity = quantity;
} }
QDateTime*
SWGOrder::getShipDate() { QDateTime*
SWGOrder::getShipDate() {
return shipDate; return shipDate;
} }
void void
SWGOrder::setShipDate(QDateTime* shipDate) { SWGOrder::setShipDate(QDateTime* shipDate) {
this->shipDate = shipDate; this->shipDate = shipDate;
} }
QString*
SWGOrder::getStatus() { QString*
SWGOrder::getStatus() {
return status; return status;
} }
void void
SWGOrder::setStatus(QString* status) { SWGOrder::setStatus(QString* status) {
this->status = status; this->status = status;
} }
bool
SWGOrder::getComplete() { bool
SWGOrder::getComplete() {
return complete; return complete;
} }
void void
SWGOrder::setComplete(bool complete) { SWGOrder::setComplete(bool complete) {
this->complete = complete; this->complete = complete;
} }
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -1,25 +1,26 @@
/* /*
* SWGOrder.h * SWGOrder.h
* *
* *
*/ */
#ifndef SWGOrder_H_ #ifndef SWGOrder_H_
#define SWGOrder_H_ #define SWGOrder_H_
#include <QJsonObject> #include
<QJsonObject>
#include "QDateTime.h" #include "QDateTime.h"
#include <QString> #include <QString>
#include "SWGObject.h" #include "SWGObject.h"
namespace Swagger { namespace Swagger {
class SWGOrder: public SWGObject { class SWGOrder: public SWGObject {
public: public:
SWGOrder(); SWGOrder();
SWGOrder(QString* json); SWGOrder(QString* json);
virtual ~SWGOrder(); virtual ~SWGOrder();
@ -45,7 +46,7 @@ public:
void setComplete(bool complete); void setComplete(bool complete);
private: private:
qint64 id; qint64 id;
qint64 petId; qint64 petId;
qint32 quantity; qint32 quantity;
@ -53,8 +54,8 @@ private:
QString* status; QString* status;
bool complete; bool complete;
}; };
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* SWGOrder_H_ */ #endif /* SWGOrder_H_ */

View File

@ -1,31 +1,35 @@
#include "SWGPet.h" #include "SWGPet.h"
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include <QJsonDocument> #include
#include <QJsonArray> <QJsonDocument>
#include <QObject> #include
#include <QDebug> <QJsonArray>
#include
<QObject>
#include
<QDebug>
namespace Swagger { namespace Swagger {
SWGPet::SWGPet(QString* json) { SWGPet::SWGPet(QString* json) {
init(); init();
this->fromJson(*json); this->fromJson(*json);
} }
SWGPet::SWGPet() { SWGPet::SWGPet() {
init(); init();
} }
SWGPet::~SWGPet() { SWGPet::~SWGPet() {
this->cleanup(); this->cleanup();
} }
void void
SWGPet::init() { SWGPet::init() {
id = 0L; id = 0L;
category = new SWGCategory(); category = new SWGCategory();
name = new QString(""); name = new QString("");
@ -33,10 +37,10 @@ SWGPet::init() {
tags = new QList<SWGTag*>(); tags = new QList<SWGTag*>();
status = new QString(""); status = new QString("");
} }
void void
SWGPet::cleanup() { SWGPet::cleanup() {
if(category != NULL) { if(category != NULL) {
delete category; delete category;
@ -62,19 +66,19 @@ SWGPet::cleanup() {
delete status; delete status;
} }
} }
SWGPet* SWGPet*
SWGPet::fromJson(QString &json) { SWGPet::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object(); QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject); this->fromJsonObject(jsonObject);
return this; return this;
} }
void void
SWGPet::fromJsonObject(QJsonObject &pJson) { SWGPet::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", ""); setValue(&id, pJson["id"], "qint64", "");
setValue(&category, pJson["category"], "SWGCategory", "SWGCategory"); setValue(&category, pJson["category"], "SWGCategory", "SWGCategory");
setValue(&name, pJson["name"], "QString", "QString"); setValue(&name, pJson["name"], "QString", "QString");
@ -82,20 +86,20 @@ SWGPet::fromJsonObject(QJsonObject &pJson) {
setValue(&tags, pJson["tags"], "QList", "SWGTag"); setValue(&tags, pJson["tags"], "QList", "SWGTag");
setValue(&status, pJson["status"], "QString", "QString"); setValue(&status, pJson["status"], "QString", "QString");
} }
QString QString
SWGPet::asJson () SWGPet::asJson ()
{ {
QJsonObject* obj = this->asJsonObject(); QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj); QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
return QString(bytes); return QString(bytes);
} }
QJsonObject* QJsonObject*
SWGPet::asJsonObject() { SWGPet::asJsonObject() {
QJsonObject* obj = new QJsonObject(); QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
@ -114,7 +118,8 @@ SWGPet::asJsonObject() {
QList<QString*>* photoUrlsList = photoUrls; QList<QString*>* photoUrlsList = photoUrls;
QJsonArray photoUrlsJsonArray; QJsonArray photoUrlsJsonArray;
toJsonArray((QList<void*>*)photoUrls, &photoUrlsJsonArray, "photoUrls", "QString"); toJsonArray((QList
<void*>*)photoUrls, &photoUrlsJsonArray, "photoUrls", "QString");
obj->insert("photoUrls", photoUrlsJsonArray); obj->insert("photoUrls", photoUrlsJsonArray);
@ -123,7 +128,8 @@ SWGPet::asJsonObject() {
QList<SWGTag*>* tagsList = tags; QList<SWGTag*>* tagsList = tags;
QJsonArray tagsJsonArray; QJsonArray tagsJsonArray;
toJsonArray((QList<void*>*)tags, &tagsJsonArray, "tags", "SWGTag"); toJsonArray((QList
<void*>*)tags, &tagsJsonArray, "tags", "SWGTag");
obj->insert("tags", tagsJsonArray); obj->insert("tags", tagsJsonArray);
@ -137,63 +143,70 @@ SWGPet::asJsonObject() {
return obj; return obj;
} }
qint64
SWGPet::getId() { qint64
SWGPet::getId() {
return id; return id;
} }
void void
SWGPet::setId(qint64 id) { SWGPet::setId(qint64 id) {
this->id = id; this->id = id;
} }
SWGCategory*
SWGPet::getCategory() { SWGCategory*
SWGPet::getCategory() {
return category; return category;
} }
void void
SWGPet::setCategory(SWGCategory* category) { SWGPet::setCategory(SWGCategory* category) {
this->category = category; this->category = category;
} }
QString*
SWGPet::getName() { QString*
SWGPet::getName() {
return name; return name;
} }
void void
SWGPet::setName(QString* name) { SWGPet::setName(QString* name) {
this->name = name; this->name = name;
} }
QList<QString*>*
SWGPet::getPhotoUrls() { QList<QString*>*
SWGPet::getPhotoUrls() {
return photoUrls; return photoUrls;
} }
void void
SWGPet::setPhotoUrls(QList<QString*>* photoUrls) { SWGPet::setPhotoUrls(QList<QString*>* photoUrls) {
this->photoUrls = photoUrls; this->photoUrls = photoUrls;
} }
QList<SWGTag*>*
SWGPet::getTags() { QList<SWGTag*>*
SWGPet::getTags() {
return tags; return tags;
} }
void void
SWGPet::setTags(QList<SWGTag*>* tags) { SWGPet::setTags(QList<SWGTag*>* tags) {
this->tags = tags; this->tags = tags;
} }
QString*
SWGPet::getStatus() { QString*
SWGPet::getStatus() {
return status; return status;
} }
void void
SWGPet::setStatus(QString* status) { SWGPet::setStatus(QString* status) {
this->status = status; this->status = status;
} }
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -1,13 +1,14 @@
/* /*
* SWGPet.h * SWGPet.h
* *
* *
*/ */
#ifndef SWGPet_H_ #ifndef SWGPet_H_
#define SWGPet_H_ #define SWGPet_H_
#include <QJsonObject> #include
<QJsonObject>
#include "SWGTag.h" #include "SWGTag.h"
@ -15,13 +16,13 @@
#include "SWGCategory.h" #include "SWGCategory.h"
#include <QString> #include <QString>
#include "SWGObject.h" #include "SWGObject.h"
namespace Swagger { namespace Swagger {
class SWGPet: public SWGObject { class SWGPet: public SWGObject {
public: public:
SWGPet(); SWGPet();
SWGPet(QString* json); SWGPet(QString* json);
virtual ~SWGPet(); virtual ~SWGPet();
@ -47,7 +48,7 @@ public:
void setStatus(QString* status); void setStatus(QString* status);
private: private:
qint64 id; qint64 id;
SWGCategory* category; SWGCategory* category;
QString* name; QString* name;
@ -55,8 +56,8 @@ private:
QList<SWGTag*>* tags; QList<SWGTag*>* tags;
QString* status; QString* status;
}; };
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* SWGPet_H_ */ #endif /* SWGPet_H_ */

View File

@ -2,21 +2,25 @@
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include "SWGModelFactory.h" #include "SWGModelFactory.h"
#include <QJsonArray> #include
#include <QJsonDocument> <QJsonArray>
#include
<QJsonDocument>
namespace Swagger { namespace Swagger {
SWGPetApi::SWGPetApi() {} SWGPetApi::SWGPetApi() {}
SWGPetApi::~SWGPetApi() {} SWGPetApi::~SWGPetApi() {}
SWGPetApi::SWGPetApi(QString host, QString basePath) { SWGPetApi::SWGPetApi(QString host, QString basePath) {
this->host = host; this->host = host;
this->basePath = basePath; this->basePath = basePath;
} }
void
SWGPetApi::updatePet(SWGPet body) {
void
SWGPetApi::updatePet(SWGPet body) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet"); fullPath.append(this->host).append(this->basePath).append("/pet");
@ -44,10 +48,10 @@ SWGPetApi::updatePet(SWGPet body) {
&SWGPetApi::updatePetCallback); &SWGPetApi::updatePetCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGPetApi::updatePetCallback(HttpRequestWorker * worker) { SWGPetApi::updatePetCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -62,9 +66,10 @@ SWGPetApi::updatePetCallback(HttpRequestWorker * worker) {
emit updatePetSignal(); emit updatePetSignal();
} }
void
SWGPetApi::addPet(SWGPet body) { void
SWGPetApi::addPet(SWGPet body) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet"); fullPath.append(this->host).append(this->basePath).append("/pet");
@ -92,10 +97,10 @@ SWGPetApi::addPet(SWGPet body) {
&SWGPetApi::addPetCallback); &SWGPetApi::addPetCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGPetApi::addPetCallback(HttpRequestWorker * worker) { SWGPetApi::addPetCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -110,9 +115,10 @@ SWGPetApi::addPetCallback(HttpRequestWorker * worker) {
emit addPetSignal(); emit addPetSignal();
} }
void
SWGPetApi::findPetsByStatus(QList<QString*>* status) { void
SWGPetApi::findPetsByStatus(QList<QString*>* status) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/findByStatus"); fullPath.append(this->host).append(this->basePath).append("/pet/findByStatus");
@ -181,10 +187,10 @@ SWGPetApi::findPetsByStatus(QList<QString*>* status) {
&SWGPetApi::findPetsByStatusCallback); &SWGPetApi::findPetsByStatusCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGPetApi::findPetsByStatusCallback(HttpRequestWorker * worker) { SWGPetApi::findPetsByStatusCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -215,9 +221,10 @@ SWGPetApi::findPetsByStatusCallback(HttpRequestWorker * worker) {
emit findPetsByStatusSignal(output); emit findPetsByStatusSignal(output);
} }
void
SWGPetApi::findPetsByTags(QList<QString*>* tags) { void
SWGPetApi::findPetsByTags(QList<QString*>* tags) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/findByTags"); fullPath.append(this->host).append(this->basePath).append("/pet/findByTags");
@ -286,10 +293,10 @@ SWGPetApi::findPetsByTags(QList<QString*>* tags) {
&SWGPetApi::findPetsByTagsCallback); &SWGPetApi::findPetsByTagsCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGPetApi::findPetsByTagsCallback(HttpRequestWorker * worker) { SWGPetApi::findPetsByTagsCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -320,9 +327,10 @@ SWGPetApi::findPetsByTagsCallback(HttpRequestWorker * worker) {
emit findPetsByTagsSignal(output); emit findPetsByTagsSignal(output);
} }
void
SWGPetApi::getPetById(qint64 petId) { void
SWGPetApi::getPetById(qint64 petId) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
@ -348,10 +356,10 @@ SWGPetApi::getPetById(qint64 petId) {
&SWGPetApi::getPetByIdCallback); &SWGPetApi::getPetByIdCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGPetApi::getPetByIdCallback(HttpRequestWorker * worker) { SWGPetApi::getPetByIdCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -366,7 +374,8 @@ SWGPetApi::getPetByIdCallback(HttpRequestWorker * worker) {
QString json(worker->response); QString json(worker->response);
SWGPet* output = static_cast<SWGPet*>(create(json, QString("SWGPet"))); SWGPet* output = static_cast<SWGPet*>(create(json,
QString("SWGPet")));
@ -375,9 +384,12 @@ SWGPetApi::getPetByIdCallback(HttpRequestWorker * worker) {
emit getPetByIdSignal(output); emit getPetByIdSignal(output);
} }
void
SWGPetApi::updatePetWithForm(QString* petId, QString* name, QString* status) { void
SWGPetApi::updatePetWithForm(QString* petId
, QString* name
, QString* status) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
@ -411,10 +423,10 @@ SWGPetApi::updatePetWithForm(QString* petId, QString* name, QString* status) {
&SWGPetApi::updatePetWithFormCallback); &SWGPetApi::updatePetWithFormCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGPetApi::updatePetWithFormCallback(HttpRequestWorker * worker) { SWGPetApi::updatePetWithFormCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -429,9 +441,11 @@ SWGPetApi::updatePetWithFormCallback(HttpRequestWorker * worker) {
emit updatePetWithFormSignal(); emit updatePetWithFormSignal();
} }
void
SWGPetApi::deletePet(QString* apiKey, qint64 petId) { void
SWGPetApi::deletePet(QString* apiKey
, qint64 petId) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}"); fullPath.append(this->host).append(this->basePath).append("/pet/{petId}");
@ -459,10 +473,10 @@ SWGPetApi::deletePet(QString* apiKey, qint64 petId) {
&SWGPetApi::deletePetCallback); &SWGPetApi::deletePetCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGPetApi::deletePetCallback(HttpRequestWorker * worker) { SWGPetApi::deletePetCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -477,9 +491,12 @@ SWGPetApi::deletePetCallback(HttpRequestWorker * worker) {
emit deletePetSignal(); emit deletePetSignal();
} }
void
SWGPetApi::uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file) { void
SWGPetApi::uploadFile(qint64 petId
, QString* additionalMetadata
, SWGHttpRequestInputFileElement* file) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/pet/{petId}/uploadImage"); fullPath.append(this->host).append(this->basePath).append("/pet/{petId}/uploadImage");
@ -509,10 +526,10 @@ SWGPetApi::uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestI
&SWGPetApi::uploadFileCallback); &SWGPetApi::uploadFileCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGPetApi::uploadFileCallback(HttpRequestWorker * worker) { SWGPetApi::uploadFileCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -527,5 +544,7 @@ SWGPetApi::uploadFileCallback(HttpRequestWorker * worker) {
emit uploadFileSignal(); emit uploadFileSignal();
} }
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -7,14 +7,15 @@
#include <QString> #include <QString>
#include "SWGHttpRequest.h" #include "SWGHttpRequest.h"
#include <QObject> #include
<QObject>
namespace Swagger { namespace Swagger {
class SWGPetApi: public QObject { class SWGPetApi: public QObject {
Q_OBJECT Q_OBJECT
public: public:
SWGPetApi(); SWGPetApi();
SWGPetApi(QString host, QString basePath); SWGPetApi(QString host, QString basePath);
~SWGPetApi(); ~SWGPetApi();
@ -27,11 +28,16 @@ public:
void findPetsByStatus(QList<QString*>* status); void findPetsByStatus(QList<QString*>* status);
void findPetsByTags(QList<QString*>* tags); void findPetsByTags(QList<QString*>* tags);
void getPetById(qint64 petId); void getPetById(qint64 petId);
void updatePetWithForm(QString* petId, QString* name, QString* status); void updatePetWithForm(QString* petId
void deletePet(QString* apiKey, qint64 petId); , QString* name
void uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file); , QString* status);
void deletePet(QString* apiKey
, qint64 petId);
void uploadFile(qint64 petId
, QString* additionalMetadata
, SWGHttpRequestInputFileElement* file);
private: private:
void updatePetCallback (HttpRequestWorker * worker); void updatePetCallback (HttpRequestWorker * worker);
void addPetCallback (HttpRequestWorker * worker); void addPetCallback (HttpRequestWorker * worker);
void findPetsByStatusCallback (HttpRequestWorker * worker); void findPetsByStatusCallback (HttpRequestWorker * worker);
@ -41,7 +47,7 @@ private:
void deletePetCallback (HttpRequestWorker * worker); void deletePetCallback (HttpRequestWorker * worker);
void uploadFileCallback (HttpRequestWorker * worker); void uploadFileCallback (HttpRequestWorker * worker);
signals: signals:
void updatePetSignal(); void updatePetSignal();
void addPetSignal(); void addPetSignal();
void findPetsByStatusSignal(QList<SWGPet*>* summary); void findPetsByStatusSignal(QList<SWGPet*>* summary);
@ -51,6 +57,6 @@ signals:
void deletePetSignal(); void deletePetSignal();
void uploadFileSignal(); void uploadFileSignal();
}; };
} }
#endif #endif

View File

@ -2,21 +2,25 @@
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include "SWGModelFactory.h" #include "SWGModelFactory.h"
#include <QJsonArray> #include
#include <QJsonDocument> <QJsonArray>
#include
<QJsonDocument>
namespace Swagger { namespace Swagger {
SWGStoreApi::SWGStoreApi() {} SWGStoreApi::SWGStoreApi() {}
SWGStoreApi::~SWGStoreApi() {} SWGStoreApi::~SWGStoreApi() {}
SWGStoreApi::SWGStoreApi(QString host, QString basePath) { SWGStoreApi::SWGStoreApi(QString host, QString basePath) {
this->host = host; this->host = host;
this->basePath = basePath; this->basePath = basePath;
} }
void
SWGStoreApi::getInventory() {
void
SWGStoreApi::getInventory() {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/inventory"); fullPath.append(this->host).append(this->basePath).append("/store/inventory");
@ -39,10 +43,10 @@ SWGStoreApi::getInventory() {
&SWGStoreApi::getInventoryCallback); &SWGStoreApi::getInventoryCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGStoreApi::getInventoryCallback(HttpRequestWorker * worker) { SWGStoreApi::getInventoryCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -77,9 +81,10 @@ SWGStoreApi::getInventoryCallback(HttpRequestWorker * worker) {
emit getInventorySignal(output); emit getInventorySignal(output);
} }
void
SWGStoreApi::placeOrder(SWGOrder body) { void
SWGStoreApi::placeOrder(SWGOrder body) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order"); fullPath.append(this->host).append(this->basePath).append("/store/order");
@ -107,10 +112,10 @@ SWGStoreApi::placeOrder(SWGOrder body) {
&SWGStoreApi::placeOrderCallback); &SWGStoreApi::placeOrderCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGStoreApi::placeOrderCallback(HttpRequestWorker * worker) { SWGStoreApi::placeOrderCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -125,7 +130,8 @@ SWGStoreApi::placeOrderCallback(HttpRequestWorker * worker) {
QString json(worker->response); QString json(worker->response);
SWGOrder* output = static_cast<SWGOrder*>(create(json, QString("SWGOrder"))); SWGOrder* output = static_cast<SWGOrder*>(create(json,
QString("SWGOrder")));
@ -134,9 +140,10 @@ SWGStoreApi::placeOrderCallback(HttpRequestWorker * worker) {
emit placeOrderSignal(output); emit placeOrderSignal(output);
} }
void
SWGStoreApi::getOrderById(QString* orderId) { void
SWGStoreApi::getOrderById(QString* orderId) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}"); fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
@ -162,10 +169,10 @@ SWGStoreApi::getOrderById(QString* orderId) {
&SWGStoreApi::getOrderByIdCallback); &SWGStoreApi::getOrderByIdCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGStoreApi::getOrderByIdCallback(HttpRequestWorker * worker) { SWGStoreApi::getOrderByIdCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -180,7 +187,8 @@ SWGStoreApi::getOrderByIdCallback(HttpRequestWorker * worker) {
QString json(worker->response); QString json(worker->response);
SWGOrder* output = static_cast<SWGOrder*>(create(json, QString("SWGOrder"))); SWGOrder* output = static_cast<SWGOrder*>(create(json,
QString("SWGOrder")));
@ -189,9 +197,10 @@ SWGStoreApi::getOrderByIdCallback(HttpRequestWorker * worker) {
emit getOrderByIdSignal(output); emit getOrderByIdSignal(output);
} }
void
SWGStoreApi::deleteOrder(QString* orderId) { void
SWGStoreApi::deleteOrder(QString* orderId) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}"); fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
@ -217,10 +226,10 @@ SWGStoreApi::deleteOrder(QString* orderId) {
&SWGStoreApi::deleteOrderCallback); &SWGStoreApi::deleteOrderCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGStoreApi::deleteOrderCallback(HttpRequestWorker * worker) { SWGStoreApi::deleteOrderCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -235,5 +244,7 @@ SWGStoreApi::deleteOrderCallback(HttpRequestWorker * worker) {
emit deleteOrderSignal(); emit deleteOrderSignal();
} }
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -7,14 +7,15 @@
#include "SWGOrder.h" #include "SWGOrder.h"
#include <QString> #include <QString>
#include <QObject> #include
<QObject>
namespace Swagger { namespace Swagger {
class SWGStoreApi: public QObject { class SWGStoreApi: public QObject {
Q_OBJECT Q_OBJECT
public: public:
SWGStoreApi(); SWGStoreApi();
SWGStoreApi(QString host, QString basePath); SWGStoreApi(QString host, QString basePath);
~SWGStoreApi(); ~SWGStoreApi();
@ -27,18 +28,18 @@ public:
void getOrderById(QString* orderId); void getOrderById(QString* orderId);
void deleteOrder(QString* orderId); void deleteOrder(QString* orderId);
private: private:
void getInventoryCallback (HttpRequestWorker * worker); void getInventoryCallback (HttpRequestWorker * worker);
void placeOrderCallback (HttpRequestWorker * worker); void placeOrderCallback (HttpRequestWorker * worker);
void getOrderByIdCallback (HttpRequestWorker * worker); void getOrderByIdCallback (HttpRequestWorker * worker);
void deleteOrderCallback (HttpRequestWorker * worker); void deleteOrderCallback (HttpRequestWorker * worker);
signals: signals:
void getInventorySignal(QMap<QString, qint32>* summary); void getInventorySignal(QMap<QString, qint32>* summary);
void placeOrderSignal(SWGOrder* summary); void placeOrderSignal(SWGOrder* summary);
void getOrderByIdSignal(SWGOrder* summary); void getOrderByIdSignal(SWGOrder* summary);
void deleteOrderSignal(); void deleteOrderSignal();
}; };
} }
#endif #endif

View File

@ -1,73 +1,77 @@
#include "SWGTag.h" #include "SWGTag.h"
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include <QJsonDocument> #include
#include <QJsonArray> <QJsonDocument>
#include <QObject> #include
#include <QDebug> <QJsonArray>
#include
<QObject>
#include
<QDebug>
namespace Swagger { namespace Swagger {
SWGTag::SWGTag(QString* json) { SWGTag::SWGTag(QString* json) {
init(); init();
this->fromJson(*json); this->fromJson(*json);
} }
SWGTag::SWGTag() { SWGTag::SWGTag() {
init(); init();
} }
SWGTag::~SWGTag() { SWGTag::~SWGTag() {
this->cleanup(); this->cleanup();
} }
void void
SWGTag::init() { SWGTag::init() {
id = 0L; id = 0L;
name = new QString(""); name = new QString("");
} }
void void
SWGTag::cleanup() { SWGTag::cleanup() {
if(name != NULL) { if(name != NULL) {
delete name; delete name;
} }
} }
SWGTag* SWGTag*
SWGTag::fromJson(QString &json) { SWGTag::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object(); QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject); this->fromJsonObject(jsonObject);
return this; return this;
} }
void void
SWGTag::fromJsonObject(QJsonObject &pJson) { SWGTag::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", ""); setValue(&id, pJson["id"], "qint64", "");
setValue(&name, pJson["name"], "QString", "QString"); setValue(&name, pJson["name"], "QString", "QString");
} }
QString QString
SWGTag::asJson () SWGTag::asJson ()
{ {
QJsonObject* obj = this->asJsonObject(); QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj); QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
return QString(bytes); return QString(bytes);
} }
QJsonObject* QJsonObject*
SWGTag::asJsonObject() { SWGTag::asJsonObject() {
QJsonObject* obj = new QJsonObject(); QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
@ -79,27 +83,30 @@ SWGTag::asJsonObject() {
return obj; return obj;
} }
qint64
SWGTag::getId() { qint64
SWGTag::getId() {
return id; return id;
} }
void void
SWGTag::setId(qint64 id) { SWGTag::setId(qint64 id) {
this->id = id; this->id = id;
} }
QString*
SWGTag::getName() { QString*
SWGTag::getName() {
return name; return name;
} }
void void
SWGTag::setName(QString* name) { SWGTag::setName(QString* name) {
this->name = name; this->name = name;
} }
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -1,24 +1,25 @@
/* /*
* SWGTag.h * SWGTag.h
* *
* *
*/ */
#ifndef SWGTag_H_ #ifndef SWGTag_H_
#define SWGTag_H_ #define SWGTag_H_
#include <QJsonObject> #include
<QJsonObject>
#include <QString> #include <QString>
#include "SWGObject.h" #include "SWGObject.h"
namespace Swagger { namespace Swagger {
class SWGTag: public SWGObject { class SWGTag: public SWGObject {
public: public:
SWGTag(); SWGTag();
SWGTag(QString* json); SWGTag(QString* json);
virtual ~SWGTag(); virtual ~SWGTag();
@ -36,12 +37,12 @@ public:
void setName(QString* name); void setName(QString* name);
private: private:
qint64 id; qint64 id;
QString* name; QString* name;
}; };
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* SWGTag_H_ */ #endif /* SWGTag_H_ */

View File

@ -1,31 +1,35 @@
#include "SWGUser.h" #include "SWGUser.h"
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include <QJsonDocument> #include
#include <QJsonArray> <QJsonDocument>
#include <QObject> #include
#include <QDebug> <QJsonArray>
#include
<QObject>
#include
<QDebug>
namespace Swagger { namespace Swagger {
SWGUser::SWGUser(QString* json) { SWGUser::SWGUser(QString* json) {
init(); init();
this->fromJson(*json); this->fromJson(*json);
} }
SWGUser::SWGUser() { SWGUser::SWGUser() {
init(); init();
} }
SWGUser::~SWGUser() { SWGUser::~SWGUser() {
this->cleanup(); this->cleanup();
} }
void void
SWGUser::init() { SWGUser::init() {
id = 0L; id = 0L;
username = new QString(""); username = new QString("");
firstName = new QString(""); firstName = new QString("");
@ -35,10 +39,10 @@ SWGUser::init() {
phone = new QString(""); phone = new QString("");
userStatus = 0; userStatus = 0;
} }
void void
SWGUser::cleanup() { SWGUser::cleanup() {
if(username != NULL) { if(username != NULL) {
delete username; delete username;
@ -60,19 +64,19 @@ SWGUser::cleanup() {
} }
} }
SWGUser* SWGUser*
SWGUser::fromJson(QString &json) { SWGUser::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object(); QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject); this->fromJsonObject(jsonObject);
return this; return this;
} }
void void
SWGUser::fromJsonObject(QJsonObject &pJson) { SWGUser::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", ""); setValue(&id, pJson["id"], "qint64", "");
setValue(&username, pJson["username"], "QString", "QString"); setValue(&username, pJson["username"], "QString", "QString");
setValue(&firstName, pJson["firstName"], "QString", "QString"); setValue(&firstName, pJson["firstName"], "QString", "QString");
@ -82,20 +86,20 @@ SWGUser::fromJsonObject(QJsonObject &pJson) {
setValue(&phone, pJson["phone"], "QString", "QString"); setValue(&phone, pJson["phone"], "QString", "QString");
setValue(&userStatus, pJson["userStatus"], "qint32", ""); setValue(&userStatus, pJson["userStatus"], "qint32", "");
} }
QString QString
SWGUser::asJson () SWGUser::asJson ()
{ {
QJsonObject* obj = this->asJsonObject(); QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj); QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
return QString(bytes); return QString(bytes);
} }
QJsonObject* QJsonObject*
SWGUser::asJsonObject() { SWGUser::asJsonObject() {
QJsonObject* obj = new QJsonObject(); QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
@ -138,81 +142,90 @@ SWGUser::asJsonObject() {
return obj; return obj;
} }
qint64
SWGUser::getId() { qint64
SWGUser::getId() {
return id; return id;
} }
void void
SWGUser::setId(qint64 id) { SWGUser::setId(qint64 id) {
this->id = id; this->id = id;
} }
QString*
SWGUser::getUsername() { QString*
SWGUser::getUsername() {
return username; return username;
} }
void void
SWGUser::setUsername(QString* username) { SWGUser::setUsername(QString* username) {
this->username = username; this->username = username;
} }
QString*
SWGUser::getFirstName() { QString*
SWGUser::getFirstName() {
return firstName; return firstName;
} }
void void
SWGUser::setFirstName(QString* firstName) { SWGUser::setFirstName(QString* firstName) {
this->firstName = firstName; this->firstName = firstName;
} }
QString*
SWGUser::getLastName() { QString*
SWGUser::getLastName() {
return lastName; return lastName;
} }
void void
SWGUser::setLastName(QString* lastName) { SWGUser::setLastName(QString* lastName) {
this->lastName = lastName; this->lastName = lastName;
} }
QString*
SWGUser::getEmail() { QString*
SWGUser::getEmail() {
return email; return email;
} }
void void
SWGUser::setEmail(QString* email) { SWGUser::setEmail(QString* email) {
this->email = email; this->email = email;
} }
QString*
SWGUser::getPassword() { QString*
SWGUser::getPassword() {
return password; return password;
} }
void void
SWGUser::setPassword(QString* password) { SWGUser::setPassword(QString* password) {
this->password = password; this->password = password;
} }
QString*
SWGUser::getPhone() { QString*
SWGUser::getPhone() {
return phone; return phone;
} }
void void
SWGUser::setPhone(QString* phone) { SWGUser::setPhone(QString* phone) {
this->phone = phone; this->phone = phone;
} }
qint32
SWGUser::getUserStatus() { qint32
SWGUser::getUserStatus() {
return userStatus; return userStatus;
} }
void void
SWGUser::setUserStatus(qint32 userStatus) { SWGUser::setUserStatus(qint32 userStatus) {
this->userStatus = userStatus; this->userStatus = userStatus;
} }
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -1,24 +1,25 @@
/* /*
* SWGUser.h * SWGUser.h
* *
* *
*/ */
#ifndef SWGUser_H_ #ifndef SWGUser_H_
#define SWGUser_H_ #define SWGUser_H_
#include <QJsonObject> #include
<QJsonObject>
#include <QString> #include <QString>
#include "SWGObject.h" #include "SWGObject.h"
namespace Swagger { namespace Swagger {
class SWGUser: public SWGObject { class SWGUser: public SWGObject {
public: public:
SWGUser(); SWGUser();
SWGUser(QString* json); SWGUser(QString* json);
virtual ~SWGUser(); virtual ~SWGUser();
@ -48,7 +49,7 @@ public:
void setUserStatus(qint32 userStatus); void setUserStatus(qint32 userStatus);
private: private:
qint64 id; qint64 id;
QString* username; QString* username;
QString* firstName; QString* firstName;
@ -58,8 +59,8 @@ private:
QString* phone; QString* phone;
qint32 userStatus; qint32 userStatus;
}; };
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* SWGUser_H_ */ #endif /* SWGUser_H_ */

View File

@ -2,21 +2,25 @@
#include "SWGHelpers.h" #include "SWGHelpers.h"
#include "SWGModelFactory.h" #include "SWGModelFactory.h"
#include <QJsonArray> #include
#include <QJsonDocument> <QJsonArray>
#include
<QJsonDocument>
namespace Swagger { namespace Swagger {
SWGUserApi::SWGUserApi() {} SWGUserApi::SWGUserApi() {}
SWGUserApi::~SWGUserApi() {} SWGUserApi::~SWGUserApi() {}
SWGUserApi::SWGUserApi(QString host, QString basePath) { SWGUserApi::SWGUserApi(QString host, QString basePath) {
this->host = host; this->host = host;
this->basePath = basePath; this->basePath = basePath;
} }
void
SWGUserApi::createUser(SWGUser body) {
void
SWGUserApi::createUser(SWGUser body) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user"); fullPath.append(this->host).append(this->basePath).append("/user");
@ -44,10 +48,10 @@ SWGUserApi::createUser(SWGUser body) {
&SWGUserApi::createUserCallback); &SWGUserApi::createUserCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGUserApi::createUserCallback(HttpRequestWorker * worker) { SWGUserApi::createUserCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -62,9 +66,10 @@ SWGUserApi::createUserCallback(HttpRequestWorker * worker) {
emit createUserSignal(); emit createUserSignal();
} }
void
SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) { void
SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithArray"); fullPath.append(this->host).append(this->basePath).append("/user/createWithArray");
@ -80,7 +85,9 @@ SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) {
QJsonArray* bodyArray = new QJsonArray(); QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList<void*>*)body, bodyArray, QString("body"), QString("SWGUser*")); toJsonArray((QList
<void
*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray); QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
@ -97,10 +104,10 @@ SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) {
&SWGUserApi::createUsersWithArrayInputCallback); &SWGUserApi::createUsersWithArrayInputCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGUserApi::createUsersWithArrayInputCallback(HttpRequestWorker * worker) { SWGUserApi::createUsersWithArrayInputCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -115,9 +122,10 @@ SWGUserApi::createUsersWithArrayInputCallback(HttpRequestWorker * worker) {
emit createUsersWithArrayInputSignal(); emit createUsersWithArrayInputSignal();
} }
void
SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) { void
SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithList"); fullPath.append(this->host).append(this->basePath).append("/user/createWithList");
@ -133,7 +141,9 @@ SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) {
QJsonArray* bodyArray = new QJsonArray(); QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList<void*>*)body, bodyArray, QString("body"), QString("SWGUser*")); toJsonArray((QList
<void
*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray); QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson(); QByteArray bytes = doc.toJson();
@ -150,10 +160,10 @@ SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) {
&SWGUserApi::createUsersWithListInputCallback); &SWGUserApi::createUsersWithListInputCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGUserApi::createUsersWithListInputCallback(HttpRequestWorker * worker) { SWGUserApi::createUsersWithListInputCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -168,9 +178,11 @@ SWGUserApi::createUsersWithListInputCallback(HttpRequestWorker * worker) {
emit createUsersWithListInputSignal(); emit createUsersWithListInputSignal();
} }
void
SWGUserApi::loginUser(QString* username, QString* password) { void
SWGUserApi::loginUser(QString* username
, QString* password) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/login"); fullPath.append(this->host).append(this->basePath).append("/user/login");
@ -217,10 +229,10 @@ SWGUserApi::loginUser(QString* username, QString* password) {
&SWGUserApi::loginUserCallback); &SWGUserApi::loginUserCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGUserApi::loginUserCallback(HttpRequestWorker * worker) { SWGUserApi::loginUserCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -235,7 +247,8 @@ SWGUserApi::loginUserCallback(HttpRequestWorker * worker) {
QString json(worker->response); QString json(worker->response);
QString* output = static_cast<QString*>(create(json, QString("QString"))); QString* output = static_cast<QString*>(create(json,
QString("QString")));
@ -244,9 +257,10 @@ SWGUserApi::loginUserCallback(HttpRequestWorker * worker) {
emit loginUserSignal(output); emit loginUserSignal(output);
} }
void
SWGUserApi::logoutUser() { void
SWGUserApi::logoutUser() {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/logout"); fullPath.append(this->host).append(this->basePath).append("/user/logout");
@ -269,10 +283,10 @@ SWGUserApi::logoutUser() {
&SWGUserApi::logoutUserCallback); &SWGUserApi::logoutUserCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGUserApi::logoutUserCallback(HttpRequestWorker * worker) { SWGUserApi::logoutUserCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -287,9 +301,10 @@ SWGUserApi::logoutUserCallback(HttpRequestWorker * worker) {
emit logoutUserSignal(); emit logoutUserSignal();
} }
void
SWGUserApi::getUserByName(QString* username) { void
SWGUserApi::getUserByName(QString* username) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}"); fullPath.append(this->host).append(this->basePath).append("/user/{username}");
@ -315,10 +330,10 @@ SWGUserApi::getUserByName(QString* username) {
&SWGUserApi::getUserByNameCallback); &SWGUserApi::getUserByNameCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) { SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -333,7 +348,8 @@ SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) {
QString json(worker->response); QString json(worker->response);
SWGUser* output = static_cast<SWGUser*>(create(json, QString("SWGUser"))); SWGUser* output = static_cast<SWGUser*>(create(json,
QString("SWGUser")));
@ -342,9 +358,11 @@ SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) {
emit getUserByNameSignal(output); emit getUserByNameSignal(output);
} }
void
SWGUserApi::updateUser(QString* username, SWGUser body) { void
SWGUserApi::updateUser(QString* username
, SWGUser body) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}"); fullPath.append(this->host).append(this->basePath).append("/user/{username}");
@ -375,10 +393,10 @@ SWGUserApi::updateUser(QString* username, SWGUser body) {
&SWGUserApi::updateUserCallback); &SWGUserApi::updateUserCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGUserApi::updateUserCallback(HttpRequestWorker * worker) { SWGUserApi::updateUserCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -393,9 +411,10 @@ SWGUserApi::updateUserCallback(HttpRequestWorker * worker) {
emit updateUserSignal(); emit updateUserSignal();
} }
void
SWGUserApi::deleteUser(QString* username) { void
SWGUserApi::deleteUser(QString* username) {
QString fullPath; QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}"); fullPath.append(this->host).append(this->basePath).append("/user/{username}");
@ -421,10 +440,10 @@ SWGUserApi::deleteUser(QString* username) {
&SWGUserApi::deleteUserCallback); &SWGUserApi::deleteUserCallback);
worker->execute(&input); worker->execute(&input);
} }
void void
SWGUserApi::deleteUserCallback(HttpRequestWorker * worker) { SWGUserApi::deleteUserCallback(HttpRequestWorker * worker) {
QString msg; QString msg;
if (worker->error_type == QNetworkReply::NoError) { if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = QString("Success! %1 bytes").arg(worker->response.length());
@ -439,5 +458,7 @@ SWGUserApi::deleteUserCallback(HttpRequestWorker * worker) {
emit deleteUserSignal(); emit deleteUserSignal();
} }
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -7,14 +7,15 @@
#include <QList> #include <QList>
#include <QString> #include <QString>
#include <QObject> #include
<QObject>
namespace Swagger { namespace Swagger {
class SWGUserApi: public QObject { class SWGUserApi: public QObject {
Q_OBJECT Q_OBJECT
public: public:
SWGUserApi(); SWGUserApi();
SWGUserApi(QString host, QString basePath); SWGUserApi(QString host, QString basePath);
~SWGUserApi(); ~SWGUserApi();
@ -25,13 +26,15 @@ public:
void createUser(SWGUser body); void createUser(SWGUser body);
void createUsersWithArrayInput(QList<SWGUser*>* body); void createUsersWithArrayInput(QList<SWGUser*>* body);
void createUsersWithListInput(QList<SWGUser*>* body); void createUsersWithListInput(QList<SWGUser*>* body);
void loginUser(QString* username, QString* password); void loginUser(QString* username
, QString* password);
void logoutUser(); void logoutUser();
void getUserByName(QString* username); void getUserByName(QString* username);
void updateUser(QString* username, SWGUser body); void updateUser(QString* username
, SWGUser body);
void deleteUser(QString* username); void deleteUser(QString* username);
private: private:
void createUserCallback (HttpRequestWorker * worker); void createUserCallback (HttpRequestWorker * worker);
void createUsersWithArrayInputCallback (HttpRequestWorker * worker); void createUsersWithArrayInputCallback (HttpRequestWorker * worker);
void createUsersWithListInputCallback (HttpRequestWorker * worker); void createUsersWithListInputCallback (HttpRequestWorker * worker);
@ -41,7 +44,7 @@ private:
void updateUserCallback (HttpRequestWorker * worker); void updateUserCallback (HttpRequestWorker * worker);
void deleteUserCallback (HttpRequestWorker * worker); void deleteUserCallback (HttpRequestWorker * worker);
signals: signals:
void createUserSignal(); void createUserSignal();
void createUsersWithArrayInputSignal(); void createUsersWithArrayInputSignal();
void createUsersWithListInputSignal(); void createUsersWithListInputSignal();
@ -51,6 +54,6 @@ signals:
void updateUserSignal(); void updateUserSignal();
void deleteUserSignal(); void deleteUserSignal();
}; };
} }
#endif #endif

View File

@ -1,4 +1,4 @@
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
@ -77,7 +77,8 @@
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source>src/main/java</source> <source>
src/main/java</source>
</sources> </sources>
</configuration> </configuration>
</execution> </execution>
@ -89,7 +90,8 @@
</goals> </goals>
<configuration> <configuration>
<sources> <sources>
<source>src/test/java</source> <source>
src/test/java</source>
</sources> </sources>
</configuration> </configuration>
</execution> </execution>
@ -100,7 +102,8 @@
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source>1.6</source> <source>
1.6</source>
<target>1.6</target> <target>1.6</target>
</configuration> </configuration>
</plugin> </plugin>

View File

@ -6,11 +6,10 @@ import retrofit.RestAdapter;
import retrofit.converter.GsonConverter; import retrofit.converter.GsonConverter;
public class ServiceGenerator { public class ServiceGenerator {
// No need to instantiate this class. // No need to instantiate this class.
private ServiceGenerator() { private ServiceGenerator() { }
}
public static <S> S createService(Class<S> serviceClass) { public static <S> S createService(Class<S> serviceClass) {
Gson gson = new GsonBuilder() Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.create(); .create();
@ -21,4 +20,4 @@ public class ServiceGenerator {
return adapter.create(serviceClass); return adapter.create(serviceClass);
} }
} }

View File

@ -1,12 +1,15 @@
package io.swagger.client.api; package io.swagger.client.api;
import io.swagger.client.model.Pet; import io.swagger.client.model.*;
import retrofit.http.*; import retrofit.http.*;
import retrofit.mime.*; import retrofit.mime.*;
import java.util.*;
import java.util.List; import io.swagger.client.model.Pet;
import java.io.File;
public interface PetApi { public interface PetApi {
/** /**
* Update an existing pet * Update an existing pet
@ -35,7 +38,6 @@ public interface PetApi {
/** /**
* Finds Pets by status * Finds Pets by status
* Multiple status values can be provided with comma seperated strings * Multiple status values can be provided with comma seperated strings
*
* @param status Status values that need to be considered for filter * @param status Status values that need to be considered for filter
* @return List<Pet> * @return List<Pet>
*/ */
@ -48,7 +50,6 @@ public interface PetApi {
/** /**
* Finds Pets by tags * Finds Pets by tags
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
*
* @param tags Tags to filter by * @param tags Tags to filter by
* @return List<Pet> * @return List<Pet>
*/ */
@ -61,7 +62,6 @@ public interface PetApi {
/** /**
* Find pet by ID * Find pet by ID
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions * Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
*
* @param petId ID of pet that needs to be fetched * @param petId ID of pet that needs to be fetched
* @return Pet * @return Pet
*/ */
@ -83,7 +83,7 @@ public interface PetApi {
@FormUrlEncoded @FormUrlEncoded
@POST("/pet/{petId}") @POST("/pet/{petId}")
Void updatePetWithForm( Void updatePetWithForm(
@Path("petId") String petId, @Field("name") String name, @Field("status") String status @Path("petId") String petId,@Field("name") String name,@Field("status") String status
); );
/** /**
@ -96,7 +96,7 @@ public interface PetApi {
@DELETE("/pet/{petId}") @DELETE("/pet/{petId}")
Void deletePet( Void deletePet(
@Header("api_key") String apiKey, @Path("petId") Long petId @Header("api_key") String apiKey,@Path("petId") Long petId
); );
/** /**
@ -111,7 +111,7 @@ public interface PetApi {
@Multipart @Multipart
@POST("/pet/{petId}/uploadImage") @POST("/pet/{petId}/uploadImage")
Void uploadFile( Void uploadFile(
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file @Path("petId") Long petId,@Part("additionalMetadata") String additionalMetadata,@Part("file") TypedFile file
); );
} }

View File

@ -1,17 +1,19 @@
package io.swagger.client.api; package io.swagger.client.api;
import io.swagger.client.model.Order; import io.swagger.client.model.*;
import retrofit.http.*; import retrofit.http.*;
import retrofit.mime.*; import retrofit.mime.*;
import java.util.*;
import java.util.Map; import java.util.Map;
import io.swagger.client.model.Order;
public interface StoreApi { public interface StoreApi {
/** /**
* Returns pet inventories by status * Returns pet inventories by status
* Returns a map of status codes to quantities * Returns a map of status codes to quantities
*
* @return Map<String, Integer> * @return Map<String, Integer>
*/ */
@ -34,7 +36,6 @@ public interface StoreApi {
/** /**
* Find purchase order by ID * Find purchase order by ID
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions * For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
*
* @param orderId ID of pet that needs to be fetched * @param orderId ID of pet that needs to be fetched
* @return Order * @return Order
*/ */
@ -47,7 +48,6 @@ public interface StoreApi {
/** /**
* Delete purchase order by ID * Delete purchase order by ID
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors * For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* @param orderId ID of the order that needs to be deleted * @param orderId ID of the order that needs to be deleted
* @return Void * @return Void
*/ */
@ -57,4 +57,4 @@ public interface StoreApi {
@Path("orderId") String orderId @Path("orderId") String orderId
); );
} }

View File

@ -1,17 +1,19 @@
package io.swagger.client.api; package io.swagger.client.api;
import io.swagger.client.model.User; import io.swagger.client.model.*;
import retrofit.http.*; import retrofit.http.*;
import retrofit.mime.*; import retrofit.mime.*;
import java.util.*;
import java.util.List; import io.swagger.client.model.User;
import java.util.*;
public interface UserApi { public interface UserApi {
/** /**
* Create user * Create user
* This can only be done by the logged in user. * This can only be done by the logged in user.
*
* @param body Created user object * @param body Created user object
* @return Void * @return Void
*/ */
@ -55,7 +57,7 @@ public interface UserApi {
@GET("/user/login") @GET("/user/login")
String loginUser( String loginUser(
@Query("username") String username, @Query("password") String password @Query("username") String username,@Query("password") String password
); );
/** /**
@ -83,7 +85,6 @@ public interface UserApi {
/** /**
* Updated user * Updated user
* This can only be done by the logged in user. * This can only be done by the logged in user.
*
* @param username name that need to be deleted * @param username name that need to be deleted
* @param body Updated user object * @param body Updated user object
* @return Void * @return Void
@ -91,13 +92,12 @@ public interface UserApi {
@PUT("/user/{username}") @PUT("/user/{username}")
Void updateUser( Void updateUser(
@Path("username") String username, @Body User body @Path("username") String username,@Body User body
); );
/** /**
* Delete user * Delete user
* This can only be done by the logged in user. * This can only be done by the logged in user.
*
* @param username The name that needs to be deleted * @param username The name that needs to be deleted
* @return Void * @return Void
*/ */
@ -107,4 +107,4 @@ public interface UserApi {
@Path("username") String username @Path("username") String username
); );
} }

View File

@ -1,11 +1,12 @@
package io.swagger.client.model; package io.swagger.client.model;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Category { public class Category {
/** /**
@ -24,7 +25,6 @@ public class Category {
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
@ -32,7 +32,6 @@ public class Category {
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@ -47,4 +46,5 @@ public class Category {
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@ -1,12 +1,13 @@
package io.swagger.client.model; package io.swagger.client.model;
import com.google.gson.annotations.SerializedName;
import java.util.Date; import java.util.Date;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class Order { @ApiModel(description = "")
public class Order {
/** /**
@ -32,6 +33,10 @@ public class Order {
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("shipDate") @SerializedName("shipDate")
private Date shipDate = null; private Date shipDate = null;
public enum StatusEnum {
placed, approved, delivered,
};
/** /**
* Order Status * Order Status
**/ **/
@ -39,17 +44,16 @@ public class Order {
@SerializedName("status") @SerializedName("status")
private StatusEnum status = null; private StatusEnum status = null;
;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("complete") @SerializedName("complete")
private Boolean complete = null; private Boolean complete = null;
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
@ -57,7 +61,6 @@ public class Order {
public Long getPetId() { public Long getPetId() {
return petId; return petId;
} }
public void setPetId(Long petId) { public void setPetId(Long petId) {
this.petId = petId; this.petId = petId;
} }
@ -65,7 +68,6 @@ public class Order {
public Integer getQuantity() { public Integer getQuantity() {
return quantity; return quantity;
} }
public void setQuantity(Integer quantity) { public void setQuantity(Integer quantity) {
this.quantity = quantity; this.quantity = quantity;
} }
@ -73,7 +75,6 @@ public class Order {
public Date getShipDate() { public Date getShipDate() {
return shipDate; return shipDate;
} }
public void setShipDate(Date shipDate) { public void setShipDate(Date shipDate) {
this.shipDate = shipDate; this.shipDate = shipDate;
} }
@ -81,7 +82,6 @@ public class Order {
public StatusEnum getStatus() { public StatusEnum getStatus() {
return status; return status;
} }
public void setStatus(StatusEnum status) { public void setStatus(StatusEnum status) {
this.status = status; this.status = status;
} }
@ -89,7 +89,6 @@ public class Order {
public Boolean getComplete() { public Boolean getComplete() {
return complete; return complete;
} }
public void setComplete(Boolean complete) { public void setComplete(Boolean complete) {
this.complete = complete; this.complete = complete;
} }
@ -108,8 +107,5 @@ public class Order {
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
public enum StatusEnum {
placed, approved, delivered,
} }
}

View File

@ -1,15 +1,15 @@
package io.swagger.client.model; package io.swagger.client.model;
import com.google.gson.annotations.SerializedName;
import io.swagger.client.model.Category; import io.swagger.client.model.Category;
import io.swagger.client.model.Tag; import io.swagger.client.model.Tag;
import java.util.*;
import java.util.ArrayList; import io.swagger.annotations.*;
import java.util.List; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Pet { public class Pet {
/** /**
@ -34,13 +34,17 @@ public class Pet {
**/ **/
@ApiModelProperty(required = true, value = "") @ApiModelProperty(required = true, value = "")
@SerializedName("photoUrls") @SerializedName("photoUrls")
private List<String> photoUrls = new ArrayList<String>(); private List<String> photoUrls = new ArrayList<String>() ;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("tags") @SerializedName("tags")
private List<Tag> tags = new ArrayList<Tag>(); private List<Tag> tags = new ArrayList<Tag>() ;
public enum StatusEnum {
available, pending, sold,
};
/** /**
* pet status in the store * pet status in the store
**/ **/
@ -48,12 +52,10 @@ public class Pet {
@SerializedName("status") @SerializedName("status")
private StatusEnum status = null; private StatusEnum status = null;
;
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
@ -61,7 +63,6 @@ public class Pet {
public Category getCategory() { public Category getCategory() {
return category; return category;
} }
public void setCategory(Category category) { public void setCategory(Category category) {
this.category = category; this.category = category;
} }
@ -69,7 +70,6 @@ public class Pet {
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@ -77,7 +77,6 @@ public class Pet {
public List<String> getPhotoUrls() { public List<String> getPhotoUrls() {
return photoUrls; return photoUrls;
} }
public void setPhotoUrls(List<String> photoUrls) { public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls; this.photoUrls = photoUrls;
} }
@ -85,7 +84,6 @@ public class Pet {
public List<Tag> getTags() { public List<Tag> getTags() {
return tags; return tags;
} }
public void setTags(List<Tag> tags) { public void setTags(List<Tag> tags) {
this.tags = tags; this.tags = tags;
} }
@ -93,7 +91,6 @@ public class Pet {
public StatusEnum getStatus() { public StatusEnum getStatus() {
return status; return status;
} }
public void setStatus(StatusEnum status) { public void setStatus(StatusEnum status) {
this.status = status; this.status = status;
} }
@ -112,8 +109,5 @@ public class Pet {
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
public enum StatusEnum {
available, pending, sold,
} }
}

View File

@ -1,11 +1,12 @@
package io.swagger.client.model; package io.swagger.client.model;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class Tag { public class Tag {
/** /**
@ -24,7 +25,6 @@ public class Tag {
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
@ -32,7 +32,6 @@ public class Tag {
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
@ -47,4 +46,5 @@ public class Tag {
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@ -1,11 +1,12 @@
package io.swagger.client.model; package io.swagger.client.model;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@ApiModel(description = "") @ApiModel(description = "")
public class User { public class User {
/** /**
@ -61,7 +62,6 @@ public class User {
public Long getId() { public Long getId() {
return id; return id;
} }
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
@ -69,7 +69,6 @@ public class User {
public String getUsername() { public String getUsername() {
return username; return username;
} }
public void setUsername(String username) { public void setUsername(String username) {
this.username = username; this.username = username;
} }
@ -77,7 +76,6 @@ public class User {
public String getFirstName() { public String getFirstName() {
return firstName; return firstName;
} }
public void setFirstName(String firstName) { public void setFirstName(String firstName) {
this.firstName = firstName; this.firstName = firstName;
} }
@ -85,7 +83,6 @@ public class User {
public String getLastName() { public String getLastName() {
return lastName; return lastName;
} }
public void setLastName(String lastName) { public void setLastName(String lastName) {
this.lastName = lastName; this.lastName = lastName;
} }
@ -93,7 +90,6 @@ public class User {
public String getEmail() { public String getEmail() {
return email; return email;
} }
public void setEmail(String email) { public void setEmail(String email) {
this.email = email; this.email = email;
} }
@ -101,7 +97,6 @@ public class User {
public String getPassword() { public String getPassword() {
return password; return password;
} }
public void setPassword(String password) { public void setPassword(String password) {
this.password = password; this.password = password;
} }
@ -109,7 +104,6 @@ public class User {
public String getPhone() { public String getPhone() {
return phone; return phone;
} }
public void setPhone(String phone) { public void setPhone(String phone) {
this.phone = phone; this.phone = phone;
} }
@ -117,7 +111,6 @@ public class User {
public Integer getUserStatus() { public Integer getUserStatus() {
return userStatus; return userStatus;
} }
public void setUserStatus(Integer userStatus) { public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus; this.userStatus = userStatus;
} }
@ -138,4 +131,5 @@ public class User {
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@ -8,18 +8,22 @@ require 'swagger_client/swagger/version'
# Models # Models
require 'swagger_client/models/base_object' require 'swagger_client/models/base_object'
require 'swagger_client/models/user' require 'swagger_client/models/user'
require 'swagger_client/models/category' require 'swagger_client/models/category'
require 'swagger_client/models/pet' require 'swagger_client/models/pet'
require 'swagger_client/models/tag' require 'swagger_client/models/tag'
require 'swagger_client/models/order' require 'swagger_client/models/order'
# APIs # APIs
require 'swagger_client/api/user_api'
require 'swagger_client/api/pet_api' require 'swagger_client/api/user_api'
require 'swagger_client/api/store_api'
require 'swagger_client/api/pet_api'
require 'swagger_client/api/store_api'
module SwaggerClient module SwaggerClient
# Initialize the default configuration # Initialize the default configuration
Swagger.configuration ||= Swagger::Configuration.new Swagger.configuration ||= Swagger::Configuration.new
end end

View File

@ -5,6 +5,7 @@ module SwaggerClient
basePath = "http://petstore.swagger.io/v2" basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker # apiInvoker = APIInvoker
# Update an existing pet # Update an existing pet
# #
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -42,6 +43,7 @@ module SwaggerClient
nil nil
end end
# Add a new pet to the store # Add a new pet to the store
# #
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -79,6 +81,7 @@ module SwaggerClient
nil nil
end end
# Finds Pets by status # Finds Pets by status
# Multiple status values can be provided with comma seperated strings # Multiple status values can be provided with comma seperated strings
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -117,6 +120,7 @@ module SwaggerClient
response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } response.map {|response| obj = Pet.new() and obj.build_from_hash(response) }
end end
# Finds Pets by tags # Finds Pets by tags
# Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. # Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -155,6 +159,7 @@ module SwaggerClient
response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } response.map {|response| obj = Pet.new() and obj.build_from_hash(response) }
end end
# Find pet by ID # Find pet by ID
# Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions # Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
# @param pet_id ID of pet that needs to be fetched # @param pet_id ID of pet that needs to be fetched
@ -195,6 +200,7 @@ module SwaggerClient
obj = Pet.new() and obj.build_from_hash(response) obj = Pet.new() and obj.build_from_hash(response)
end end
# Updates a pet in the store with form data # Updates a pet in the store with form data
# #
# @param pet_id ID of pet that needs to be updated # @param pet_id ID of pet that needs to be updated
@ -239,6 +245,7 @@ module SwaggerClient
nil nil
end end
# Deletes a pet # Deletes a pet
# #
# @param pet_id Pet id to delete # @param pet_id Pet id to delete
@ -281,6 +288,7 @@ module SwaggerClient
nil nil
end end
# uploads an image # uploads an image
# #
# @param pet_id ID of pet to update # @param pet_id ID of pet to update
@ -324,5 +332,6 @@ module SwaggerClient
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil nil
end end
end end
end end

View File

@ -5,6 +5,7 @@ module SwaggerClient
basePath = "http://petstore.swagger.io/v2" basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker # apiInvoker = APIInvoker
# Returns pet inventories by status # Returns pet inventories by status
# Returns a map of status codes to quantities # Returns a map of status codes to quantities
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -41,6 +42,7 @@ module SwaggerClient
response.map {|response| obj = map.new() and obj.build_from_hash(response) } response.map {|response| obj = map.new() and obj.build_from_hash(response) }
end end
# Place an order for a pet # Place an order for a pet
# #
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -78,6 +80,7 @@ module SwaggerClient
obj = Order.new() and obj.build_from_hash(response) obj = Order.new() and obj.build_from_hash(response)
end end
# Find purchase order by ID # Find purchase order by ID
# For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions # For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
# @param order_id ID of pet that needs to be fetched # @param order_id ID of pet that needs to be fetched
@ -118,6 +121,7 @@ module SwaggerClient
obj = Order.new() and obj.build_from_hash(response) obj = Order.new() and obj.build_from_hash(response)
end end
# Delete purchase order by ID # Delete purchase order by ID
# For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors # For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
# @param order_id ID of the order that needs to be deleted # @param order_id ID of the order that needs to be deleted
@ -157,5 +161,6 @@ module SwaggerClient
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil nil
end end
end end
end end

View File

@ -5,6 +5,7 @@ module SwaggerClient
basePath = "http://petstore.swagger.io/v2" basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker # apiInvoker = APIInvoker
# Create user # Create user
# This can only be done by the logged in user. # This can only be done by the logged in user.
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -42,6 +43,7 @@ module SwaggerClient
nil nil
end end
# Creates list of users with given input array # Creates list of users with given input array
# #
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -79,6 +81,7 @@ module SwaggerClient
nil nil
end end
# Creates list of users with given input array # Creates list of users with given input array
# #
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -116,6 +119,7 @@ module SwaggerClient
nil nil
end end
# Logs user into the system # Logs user into the system
# #
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -156,6 +160,7 @@ module SwaggerClient
obj = string.new() and obj.build_from_hash(response) obj = string.new() and obj.build_from_hash(response)
end end
# Logs out current logged in user session # Logs out current logged in user session
# #
# @param [Hash] opts the optional parameters # @param [Hash] opts the optional parameters
@ -192,6 +197,7 @@ module SwaggerClient
nil nil
end end
# Get user by user name # Get user by user name
# #
# @param username The name that needs to be fetched. Use user1 for testing. # @param username The name that needs to be fetched. Use user1 for testing.
@ -232,6 +238,7 @@ module SwaggerClient
obj = User.new() and obj.build_from_hash(response) obj = User.new() and obj.build_from_hash(response)
end end
# Updated user # Updated user
# This can only be done by the logged in user. # This can only be done by the logged in user.
# @param username name that need to be deleted # @param username name that need to be deleted
@ -273,6 +280,7 @@ module SwaggerClient
nil nil
end end
# Delete user # Delete user
# This can only be done by the logged in user. # This can only be done by the logged in user.
# @param username The name that needs to be deleted # @param username The name that needs to be deleted
@ -312,5 +320,6 @@ module SwaggerClient
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil nil
end end
end end
end end

View File

@ -1,83 +1,83 @@
module SwaggerClient module SwaggerClient
# base class containing fundamental method such as to_hash, build_from_hash and more # base class containing fundamental method such as to_hash, build_from_hash and more
class BaseObject class BaseObject
# return the object in the form of hash # return the object in the form of hash
def to_body def to_body
body = {} body = {}
self.class.attribute_map.each_pair do |key, value| self.class.attribute_map.each_pair do |key, value|
body[value] = self.send(key) unless self.send(key).nil? body[value] = self.send(key) unless self.send(key).nil?
end end
body body
end end
# build the object from hash # build the object from hash
def build_from_hash(attributes) def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash) return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type| self.class.swagger_types.each_pair do |key, type|
if type =~ /^array\[(.*)\]/i if type =~ /^array\[(.*)\]/i
if attributes[self.class.attribute_map[key]].is_a?(Array) if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
else else
#TODO show warning in debug mode #TODO show warning in debug mode
end end
elsif !attributes[self.class.attribute_map[key]].nil? elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
else else
# data not found in attributes(hash), not an issue as the data can be optional # data not found in attributes(hash), not an issue as the data can be optional
end end
end end
self self
end end
def _deserialize(type, value) def _deserialize(type, value)
case type.to_sym case type.to_sym
when :DateTime when :DateTime
DateTime.parse(value) DateTime.parse(value)
when :string when :string
value.to_s value.to_s
when :int when :int
value.to_i value.to_i
when :double when :double
value.to_f value.to_f
when :boolean when :boolean
if value =~ /^(true|t|yes|y|1)$/i if value =~ /^(true|t|yes|y|1)$/i
true true
else else
false false
end end
else # model else # model
_model = SwaggerClient.const_get(type).new _model = SwaggerClient.const_get(type).new
_model.build_from_hash(value) _model.build_from_hash(value)
end end
end end
# to_body is an alias to to_body (backward compatibility) # to_body is an alias to to_body (backward compatibility)
def to_hash def to_hash
hash = {} hash = {}
self.class.attribute_map.each_pair do |key, value| self.class.attribute_map.each_pair do |key, value|
if self.send(key).is_a?(Array) if self.send(key).is_a?(Array)
next if self.send(key).empty? 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? hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil?
else else
unless (_tmp_value = _to_hash self.send(key)).nil? unless (_tmp_value = _to_hash self.send(key)).nil?
hash[value] = _tmp_value hash[value] = _tmp_value
end end
end end
end end
hash hash
end end
# Method to output non-array value in the form of hash # Method to output non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value # For object, use to_hash. Otherwise, just return the value
def _to_hash(value) def _to_hash(value)
if value.respond_to? :to_hash if value.respond_to? :to_hash
value.to_hash value.to_hash
else else
value value
end end
end end
end end
end end

View File

@ -1,44 +1,37 @@
module SwaggerClient module SwaggerClient
# #
class Category < BaseObject class Category < BaseObject
attr_accessor :id, :name attr_accessor :id, :name
# attribute mapping from ruby-style variable name to JSON key # attribute mapping from ruby-style variable name to JSON key
def self.attribute_map def self.attribute_map
{ {
# #
:'id' => :'id', :'id' => :'id',
# #
:'name' => :'name' :'name' => :'name'
}
end
} # attribute type
end def self.swagger_types
{
:'id' => :'int',
:'name' => :'string'
}
end
# attribute type def initialize(attributes = {})
def self.swagger_types return if !attributes.is_a?(Hash) || attributes.empty?
{
:'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}
# convert string to symbol for hash key
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
if attributes[:'id'] if attributes[:'id']
@id = attributes[:'id'] @id = attributes[:'id']
end end
if attributes[:'name'] if attributes[:'name']
@name = attributes[:'name'] @name = attributes[:'name']
end end
end
end end
end
end end

View File

@ -1,76 +1,61 @@
module SwaggerClient module SwaggerClient
# #
class Order < BaseObject class Order < BaseObject
attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete
# attribute mapping from ruby-style variable name to JSON key # attribute mapping from ruby-style variable name to JSON key
def self.attribute_map def self.attribute_map
{ {
# #
:'id' => :'id', :'id' => :'id',
# #
:'pet_id' => :'petId', :'pet_id' => :'petId',
# #
:'quantity' => :'quantity', :'quantity' => :'quantity',
# #
:'ship_date' => :'shipDate', :'ship_date' => :'shipDate',
# Order Status # Order Status
:'status' => :'status', :'status' => :'status',
# #
:'complete' => :'complete' :'complete' => :'complete'
}
end
} # attribute type
end def self.swagger_types
{
:'id' => :'int',
:'pet_id' => :'int',
:'quantity' => :'int',
:'ship_date' => :'DateTime',
:'status' => :'string',
:'complete' => :'boolean'
}
end
# attribute type def initialize(attributes = {})
def self.swagger_types return if !attributes.is_a?(Hash) || attributes.empty?
{
:'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}
# convert string to symbol for hash key
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
if attributes[:'id'] if attributes[:'id']
@id = attributes[:'id'] @id = attributes[:'id']
end end
if attributes[:'petId'] if attributes[:'petId']
@pet_id = attributes[:'petId'] @pet_id = attributes[:'petId']
end end
if attributes[:'quantity'] if attributes[:'quantity']
@quantity = attributes[:'quantity'] @quantity = attributes[:'quantity']
end end
if attributes[:'shipDate'] if attributes[:'shipDate']
@ship_date = attributes[:'shipDate'] @ship_date = attributes[:'shipDate']
end end
if attributes[:'status'] if attributes[:'status']
@status = attributes[:'status'] @status = attributes[:'status']
end end
if attributes[:'complete'] if attributes[:'complete']
@complete = attributes[:'complete'] @complete = attributes[:'complete']
end end
end
end end
end
end end

View File

@ -1,80 +1,65 @@
module SwaggerClient module SwaggerClient
# #
class Pet < BaseObject class Pet < BaseObject
attr_accessor :id, :category, :name, :photo_urls, :tags, :status attr_accessor :id, :category, :name, :photo_urls, :tags, :status
# attribute mapping from ruby-style variable name to JSON key # attribute mapping from ruby-style variable name to JSON key
def self.attribute_map def self.attribute_map
{ {
# #
:'id' => :'id', :'id' => :'id',
# #
:'category' => :'category', :'category' => :'category',
# #
:'name' => :'name', :'name' => :'name',
# #
:'photo_urls' => :'photoUrls', :'photo_urls' => :'photoUrls',
# #
:'tags' => :'tags', :'tags' => :'tags',
# pet status in the store # pet status in the store
:'status' => :'status' :'status' => :'status'
}
end
} # attribute type
end def self.swagger_types
{
:'id' => :'int',
:'category' => :'Category',
:'name' => :'string',
:'photo_urls' => :'array[string]',
:'tags' => :'array[Tag]',
:'status' => :'string'
}
end
# attribute type def initialize(attributes = {})
def self.swagger_types return if !attributes.is_a?(Hash) || attributes.empty?
{
:'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}
# convert string to symbol for hash key
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
if attributes[:'id'] if attributes[:'id']
@id = attributes[:'id'] @id = attributes[:'id']
end end
if attributes[:'category'] if attributes[:'category']
@category = attributes[:'category'] @category = attributes[:'category']
end end
if attributes[:'name'] if attributes[:'name']
@name = attributes[:'name'] @name = attributes[:'name']
end end
if attributes[:'photoUrls'] if attributes[:'photoUrls']
if (value = attributes[:'photoUrls']).is_a?(Array) if (value = attributes[:'photoUrls']).is_a?(Array)
@photo_urls = value @photo_urls = value
end end
end end
if attributes[:'tags'] if attributes[:'tags']
if (value = attributes[:'tags']).is_a?(Array) if (value = attributes[:'tags']).is_a?(Array)
@tags = value @tags = value
end end
end end
if attributes[:'status'] if attributes[:'status']
@status = attributes[:'status'] @status = attributes[:'status']
end end
end
end end
end
end end

View File

@ -1,44 +1,37 @@
module SwaggerClient module SwaggerClient
# #
class Tag < BaseObject class Tag < BaseObject
attr_accessor :id, :name attr_accessor :id, :name
# attribute mapping from ruby-style variable name to JSON key # attribute mapping from ruby-style variable name to JSON key
def self.attribute_map def self.attribute_map
{ {
# #
:'id' => :'id', :'id' => :'id',
# #
:'name' => :'name' :'name' => :'name'
}
end
} # attribute type
end def self.swagger_types
{
:'id' => :'int',
:'name' => :'string'
}
end
# attribute type def initialize(attributes = {})
def self.swagger_types return if !attributes.is_a?(Hash) || attributes.empty?
{
:'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}
# convert string to symbol for hash key
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
if attributes[:'id'] if attributes[:'id']
@id = attributes[:'id'] @id = attributes[:'id']
end end
if attributes[:'name'] if attributes[:'name']
@name = attributes[:'name'] @name = attributes[:'name']
end end
end
end end
end
end end

View File

@ -1,92 +1,73 @@
module SwaggerClient module SwaggerClient
# #
class User < BaseObject class User < BaseObject
attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status
# attribute mapping from ruby-style variable name to JSON key # attribute mapping from ruby-style variable name to JSON key
def self.attribute_map def self.attribute_map
{ {
# #
:'id' => :'id', :'id' => :'id',
# #
:'username' => :'username', :'username' => :'username',
# #
:'first_name' => :'firstName', :'first_name' => :'firstName',
# #
:'last_name' => :'lastName', :'last_name' => :'lastName',
# #
:'email' => :'email', :'email' => :'email',
# #
:'password' => :'password', :'password' => :'password',
# #
:'phone' => :'phone', :'phone' => :'phone',
# User Status # User Status
:'user_status' => :'userStatus' :'user_status' => :'userStatus'
}
end
} # attribute type
end def self.swagger_types
{
:'id' => :'int',
:'username' => :'string',
:'first_name' => :'string',
:'last_name' => :'string',
:'email' => :'string',
:'password' => :'string',
:'phone' => :'string',
:'user_status' => :'int'
}
end
# attribute type def initialize(attributes = {})
def self.swagger_types return if !attributes.is_a?(Hash) || attributes.empty?
{
:'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}
# convert string to symbol for hash key
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
if attributes[:'id'] if attributes[:'id']
@id = attributes[:'id'] @id = attributes[:'id']
end end
if attributes[:'username'] if attributes[:'username']
@username = attributes[:'username'] @username = attributes[:'username']
end end
if attributes[:'firstName'] if attributes[:'firstName']
@first_name = attributes[:'firstName'] @first_name = attributes[:'firstName']
end end
if attributes[:'lastName'] if attributes[:'lastName']
@last_name = attributes[:'lastName'] @last_name = attributes[:'lastName']
end end
if attributes[:'email'] if attributes[:'email']
@email = attributes[:'email'] @email = attributes[:'email']
end end
if attributes[:'password'] if attributes[:'password']
@password = attributes[:'password'] @password = attributes[:'password']
end end
if attributes[:'phone'] if attributes[:'phone']
@phone = attributes[:'phone'] @phone = attributes[:'phone']
end end
if attributes[:'userStatus'] if attributes[:'userStatus']
@user_status = attributes[:'userStatus'] @user_status = attributes[:'userStatus']
end end
end
end end
end
end end

View File

@ -1,90 +1,90 @@
# module Swagger # module Swagger
class Object class Object
unless Object.method_defined? :blank? unless Object.method_defined? :blank?
def blank? def blank?
respond_to?(:empty?) ? empty? : !self respond_to?(:empty?) ? empty? : !self
end end
end end
unless Object.method_defined? :present? unless Object.method_defined? :present?
def present? def present?
!blank? !blank?
end end
end end
end end
class String class String
unless String.method_defined? :underscore unless String.method_defined? :underscore
def underscore def underscore
self.gsub(/::/, '/'). self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_"). tr("-", "_").
downcase downcase
end end
end end
unless String.method_defined? :camelize unless String.method_defined? :camelize
def camelize(first_letter_in_uppercase = true) def camelize(first_letter_in_uppercase = true)
if first_letter_in_uppercase != :lower if first_letter_in_uppercase != :lower
self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
else else
self.to_s[0].chr.downcase + camelize(self)[1..-1] self.to_s[0].chr.downcase + camelize(self)[1..-1]
end end
end end
end end
end end
class Hash class Hash
unless Hash.method_defined? :stringify_keys unless Hash.method_defined? :stringify_keys
def stringify_keys def stringify_keys
inject({}) do |options, (key, value)| inject({}) do |options, (key, value)|
options[key.to_s] = value options[key.to_s] = value
options options
end end
end end
end end
unless Hash.method_defined? :stringify_keys! unless Hash.method_defined? :stringify_keys!
def stringify_keys! def stringify_keys!
self.replace(self.stringify_keys) self.replace(self.stringify_keys)
end end
end end
unless Hash.method_defined? :symbolize_keys unless Hash.method_defined? :symbolize_keys
def symbolize_keys def symbolize_keys
inject({}) do |options, (key, value)| inject({}) do |options, (key, value)|
options[(key.to_sym rescue key) || key] = value options[(key.to_sym rescue key) || key] = value
options options
end end
end end
end end
unless Hash.method_defined? :symbolize_keys! unless Hash.method_defined? :symbolize_keys!
def symbolize_keys! def symbolize_keys!
self.replace(self.symbolize_keys) self.replace(self.symbolize_keys)
end end
end end
unless Hash.method_defined? :symbolize_and_underscore_keys unless Hash.method_defined? :symbolize_and_underscore_keys
def symbolize_and_underscore_keys def symbolize_and_underscore_keys
inject({}) do |options, (key, value)| inject({}) do |options, (key, value)|
options[(key.to_s.underscore.to_sym rescue key) || key] = value options[(key.to_s.underscore.to_sym rescue key) || key] = value
options options
end end
end end
end end
unless Hash.method_defined? :symbolize_and_underscore_keys! unless Hash.method_defined? :symbolize_and_underscore_keys!
def symbolize_and_underscore_keys! def symbolize_and_underscore_keys!
self.replace(self.symbolize_and_underscore_keys) self.replace(self.symbolize_and_underscore_keys)
end end
end end
end end
# end # end

View File

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

View File

@ -1,29 +1,29 @@
module SwaggerClient module SwaggerClient
module Swagger module Swagger
class Configuration class Configuration
attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl
# Defaults go in here.. # Defaults go in here..
def initialize def initialize
@format = 'json' @format = 'json'
@scheme = 'http' @scheme = 'http'
@host = 'petstore.swagger.io' @host = 'petstore.swagger.io'
@base_path = '/v2' @base_path = '/v2'
@user_agent = "ruby-swagger-#{Swagger::VERSION}" @user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = false @inject_format = false
@force_ending_format = false @force_ending_format = false
@camelize_params = true @camelize_params = true
# keys for API key authentication (param-name => api-key) # keys for API key authentication (param-name => api-key)
@api_key = {} @api_key = {}
# api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix) # api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix)
@api_key_prefix = {} @api_key_prefix = {}
# whether to verify SSL certificate, default to true # whether to verify SSL certificate, default to true
# Note: do NOT set it to false in production code, otherwise you would # Note: do NOT set it to false in production code, otherwise you would
# face multiple types of cryptographic attacks # face multiple types of cryptographic attacks
@verify_ssl = true @verify_ssl = true
end end
end end
end end
end end

View File

@ -1,271 +1,270 @@
module SwaggerClient module SwaggerClient
module Swagger module Swagger
class Request class Request
require 'uri' require 'uri'
require 'addressable/uri' require 'addressable/uri'
require 'typhoeus' require 'typhoeus'
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names
# All requests must have an HTTP method and a path # All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host # Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes={}) def initialize(http_method, path, attributes={})
attributes[:format] ||= Swagger.configuration.format attributes[:format] ||= Swagger.configuration.format
attributes[:params] ||= {} attributes[:params] ||= {}
# Set default headers # Set default headers
default_headers = { default_headers = {
'Content-Type' => "application/#{attributes[:format].downcase}", 'Content-Type' => "application/#{attributes[:format].downcase}",
'User-Agent' => Swagger.configuration.user_agent 'User-Agent' => Swagger.configuration.user_agent
} }
# Merge argument headers into defaults # Merge argument headers into defaults
attributes[:headers] = default_headers.merge(attributes[:headers] || {}) attributes[:headers] = default_headers.merge(attributes[:headers] || {})
# Stick in the auth token if there is one # Stick in the auth token if there is one
if Swagger.authenticated? if Swagger.authenticated?
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
end end
self.http_method = http_method.to_sym self.http_method = http_method.to_sym
self.path = path self.path = path
attributes.each do |name, value| attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value) send("#{name.to_s.underscore.to_sym}=", value)
end end
update_params_for_auth! update_params_for_auth!
end end
# Update hearder and query params based on authentication settings. # Update hearder and query params based on authentication settings.
def update_params_for_auth! def update_params_for_auth!
(@auth_names || []).each do |auth_name| (@auth_names || []).each do |auth_name|
case auth_name case auth_name
when 'api_key' when 'api_key'
@headers ||= {} @headers ||= {}
@headers['api_key'] = get_api_key_with_prefix('api_key') @headers['api_key'] = get_api_key_with_prefix('api_key')
when 'petstore_auth' when 'petstore_auth'
# TODO: support oauth # TODO: support oauth
end
end end
end end
end
# Get API key (with prefix if set).
# Get API key (with prefix if set). # @param [String] param_name the parameter name of API key auth
# @param [String] param_name the parameter name of API key auth def get_api_key_with_prefix(param_name)
def get_api_key_with_prefix(param_name) if Swagger.configuration.api_key_prefix[param_name].present?
if Swagger.configuration.api_key_prefix[param_name].present? "#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}"
"#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}" else
else Swagger.configuration.api_key[param_name]
Swagger.configuration.api_key[param_name] end
end end
end
# Construct a base URL
# Construct a base URL def url(options = {})
def url(options = {}) u = Addressable::URI.new(
u = Addressable::URI.new( :scheme => Swagger.configuration.scheme,
:scheme => Swagger.configuration.scheme, :host => Swagger.configuration.host,
:host => Swagger.configuration.host, :path => self.interpreted_path,
:path => self.interpreted_path, :query => self.query_string.sub(/\?/, '')
:query => self.query_string.sub(/\?/, '') ).to_s
).to_s
# Drop trailing question mark, if present
# Drop trailing question mark, if present u.sub! /\?$/, ''
u.sub! /\?$/, ''
u
u end
end
# Iterate over the params hash, injecting any path values into the path string
# Iterate over the params hash, injecting any path values into the path string # e.g. /word.{format}/{word}/entries => /word.json/cat/entries
# e.g. /word.{format}/{word}/entries => /word.json/cat/entries def interpreted_path
def interpreted_path p = self.path.dup
p = self.path.dup
# Stick a .{format} placeholder into the path if there isn't
# Stick a .{format} placeholder into the path if there isn't # one already or an actual format like json or xml
# one already or an actual format like json or xml # e.g. /words/blah => /words.{format}/blah
# e.g. /words/blah => /words.{format}/blah if Swagger.configuration.inject_format
if Swagger.configuration.inject_format unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } p = p.sub(/^(\/?\w+)/, "\\1.#{format}")
p = p.sub(/^(\/?\w+)/, "\\1.#{format}") end
end end
end
# Stick a .{format} placeholder on the end of the path if there isn't
# Stick a .{format} placeholder on the end of the path if there isn't # one already or an actual format like json or xml
# one already or an actual format like json or xml # e.g. /words/blah => /words/blah.{format}
# e.g. /words/blah => /words/blah.{format} if Swagger.configuration.force_ending_format
if Swagger.configuration.force_ending_format unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } p = "#{p}.#{format}"
p = "#{p}.#{format}" end
end end
end
p = p.sub("{format}", self.format.to_s)
p = p.sub("{format}", self.format.to_s)
URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') end
end
# Massage the request body into a state of readiness
# Massage the request body into a state of readiness # If body is a hash, camelize all keys then convert to a json string
# If body is a hash, camelize all keys then convert to a json string def body=(value)
def body=(value) if value.is_a?(Hash)
if value.is_a?(Hash) value = value.inject({}) do |memo, (k,v)|
value = value.inject({}) do |memo, (k,v)| memo[k.to_s.camelize(:lower).to_sym] = v
memo[k.to_s.camelize(:lower).to_sym] = v memo
memo end
end end
end @body = value
@body = value end
end
# If body is an object, JSONify it before making the actual request.
# If body is an object, JSONify it before making the actual request. # For form parameters, remove empty value
# For form parameters, remove empty value def outgoing_body
def outgoing_body # http form
# http form if headers['Content-Type'] == 'application/x-www-form-urlencoded'
if headers['Content-Type'] == 'application/x-www-form-urlencoded' data = form_params.dup
data = form_params.dup data.each do |key, value|
data.each do |key, value| data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter
data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter end
end data
data elsif @body # http body is JSON
elsif @body # http body is JSON @body.is_a?(String) ? @body : @body.to_json
@body.is_a?(String) ? @body : @body.to_json else
else nil
nil end
end end
end
# Construct a query string from the query-string-type params
# Construct a query string from the query-string-type params def query_string
def query_string # Iterate over all params,
# Iterate over all params, # .. removing the ones that are part of the path itself.
# .. removing the ones that are part of the path itself. # .. stringifying values so Addressable doesn't blow up.
# .. stringifying values so Addressable doesn't blow up. query_values = {}
query_values = {} self.params.each_pair do |key, value|
self.params.each_pair do |key, value| next if self.path.include? "{#{key}}" # skip path params
next if self.path.include? "{#{key}}" # skip path params next if value.blank? && value.class != FalseClass # skip empties
next if value.blank? && value.class != FalseClass # skip empties if Swagger.configuration.camelize_params
if Swagger.configuration.camelize_params key = key.to_s.camelize(:lower).to_sym
key = key.to_s.camelize(:lower).to_sym end
end query_values[key] = value.to_s
query_values[key] = value.to_s end
end
# We don't want to end up with '?' as our query string
# We don't want to end up with '?' as our query string # if there aren't really any params
# if there aren't really any params return "" if query_values.blank?
return "" if query_values.blank?
# Addressable requires query_values to be set after initialization..
# Addressable requires query_values to be set after initialization.. qs = Addressable::URI.new
qs = Addressable::URI.new qs.query_values = query_values
qs.query_values = query_values qs.to_s
qs.to_s end
end
def make
def make #TODO use configuration setting to determine if debugging
#TODO use configuration setting to determine if debugging #logger = Logger.new STDOUT
#logger = Logger.new STDOUT #logger.debug self.url
#logger.debug self.url
request_options = {
request_options = { :ssl_verifypeer => Swagger.configuration.verify_ssl,
:ssl_verifypeer => Swagger.configuration.verify_ssl, :headers => self.headers.stringify_keys
:headers => self.headers.stringify_keys }
} response = case self.http_method.to_sym
response = case self.http_method.to_sym when :get,:GET
when :get,:GET Typhoeus::Request.get(
Typhoeus::Request.get( self.url,
self.url, request_options
request_options )
)
when :post,:POST
when :post,:POST Typhoeus::Request.post(
Typhoeus::Request.post( self.url,
self.url, request_options.merge(:body => self.outgoing_body)
request_options.merge(:body => self.outgoing_body) )
)
when :patch,:PATCH
when :patch,:PATCH Typhoeus::Request.patch(
Typhoeus::Request.patch( self.url,
self.url, request_options.merge(:body => self.outgoing_body)
request_options.merge(:body => self.outgoing_body) )
)
when :put,:PUT
when :put,:PUT Typhoeus::Request.put(
Typhoeus::Request.put( self.url,
self.url, request_options.merge(:body => self.outgoing_body)
request_options.merge(:body => self.outgoing_body) )
)
when :delete,:DELETE
when :delete,:DELETE Typhoeus::Request.delete(
Typhoeus::Request.delete( self.url,
self.url, request_options.merge(:body => self.outgoing_body)
request_options.merge(:body => self.outgoing_body) )
) end
end Response.new(response)
Response.new(response) end
end
def response
def response self.make
self.make end
end
def response_code_pretty
def response_code_pretty return unless @response.present?
return unless @response.present? @response.code.to_s
@response.code.to_s end
end
def response_headers_pretty
def response_headers_pretty return unless @response.present?
return unless @response.present? # JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
# JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient @response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus end
end
# return 'Accept' based on an array of accept provided
# return 'Accept' based on an array of accept provided # @param [Array] header_accept_array Array fo 'Accept'
# @param [Array] header_accept_array Array fo 'Accept' # @return String Accept (e.g. application/json)
# @return String Accept (e.g. application/json) def self.select_header_accept header_accept_array
def self.select_header_accept header_accept_array if header_accept_array.empty?
if header_accept_array.empty? return
return elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 }
elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } 'application/json' # look for json data by default
'application/json' # look for json data by default else
else header_accept_array.join(',')
header_accept_array.join(',') end
end end
end
# return the content type based on an array of content-type provided
# return the content type based on an array of content-type provided # @param [Array] content_type_array Array fo content-type
# @param [Array] content_type_array Array fo content-type # @return String Content-Type (e.g. application/json)
# @return String Content-Type (e.g. application/json) def self.select_header_content_type content_type_array
def self.select_header_content_type content_type_array if content_type_array.empty?
if content_type_array.empty? 'application/json' # use application/json by default
'application/json' # use application/json by default elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 }
elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } 'application/json' # use application/json if it's included
'application/json' # use application/json if it's included else
else content_type_array[0]; # otherwise, use the first one
content_type_array[0]; # otherwise, use the first one end
end end
end
# static method to convert object (array, hash, object, etc) to JSON string
# static method to convert object (array, hash, object, etc) to JSON string # @param model object to be converted into JSON string
# @param model object to be converted into JSON string # @return string JSON string representation of the object
# @return string JSON string representation of the object def self.object_to_http_body model
def self.object_to_http_body model return if model.nil?
return if model.nil? _body = nil
_body = nil if model.is_a?(Array)
if model.is_a?(Array) _body = model.map{|m| object_to_hash(m) }
_body = model.map{|m| object_to_hash(m) } else
else _body = object_to_hash(model)
_body = object_to_hash(model) end
end _body.to_json
_body.to_json end
end
# static method to convert object(non-array) to hash
# static method to convert object(non-array) to hash # @param obj object to be converted into JSON string
# @param obj object to be converted into JSON string # @return string JSON string representation of the object
# @return string JSON string representation of the object def self.object_to_hash obj
def self.object_to_hash obj if obj.respond_to?(:to_hash)
if obj.respond_to?(:to_hash) obj.to_hash
obj.to_hash else
else obj
obj end
end end
end
end
end end
end
end end

View File

@ -1,70 +1,70 @@
module SwaggerClient module SwaggerClient
module Swagger module Swagger
class Response class Response
require 'json' require 'json'
attr_accessor :raw attr_accessor :raw
def initialize(raw) def initialize(raw)
self.raw = raw self.raw = raw
case self.code case self.code
when 500..510 then raise(ServerError, self.error_message) when 500..510 then raise(ServerError, self.error_message)
when 299..426 then raise(ClientError, self.error_message) when 299..426 then raise(ClientError, self.error_message)
end end
end end
def code def code
raw.code raw.code
end end
# Account for error messages that take different forms... # Account for error messages that take different forms...
def error_message def error_message
body['message'] body['message']
rescue rescue
body body
end end
# If body is JSON, parse it # If body is JSON, parse it
# Otherwise return raw string # Otherwise return raw string
def body def body
JSON.parse(raw.body, :symbolize_names => true) JSON.parse(raw.body, :symbolize_names => true)
rescue rescue
raw.body raw.body
end end
# `headers_hash` is a Typhoeus-specific extension of Hash, # `headers_hash` is a Typhoeus-specific extension of Hash,
# so simplify it back into a regular old Hash. # so simplify it back into a regular old Hash.
def headers def headers
h = {} h = {}
raw.headers_hash.each {|k,v| h[k] = v } raw.headers_hash.each {|k,v| h[k] = v }
h h
end end
# Extract the response format from the header hash # Extract the response format from the header hash
# e.g. {'Content-Type' => 'application/json'} # e.g. {'Content-Type' => 'application/json'}
def format def format
headers['Content-Type'].split("/").last.downcase headers['Content-Type'].split("/").last.downcase
end end
def json? def json?
format == 'json' format == 'json'
end end
def xml? def xml?
format == 'xml' format == 'xml'
end end
def pretty_body def pretty_body
return unless body.present? return unless body.present?
case format case format
when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>') when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
end end
end end
def pretty_headers def pretty_headers
JSON.pretty_generate(headers).gsub(/\n/, '<br/>') JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end end
end end
end end
end end

View File

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

View File

@ -3,30 +3,30 @@ $:.push File.expand_path("../lib", __FILE__)
require "swagger_client/swagger/version" require "swagger_client/swagger/version"
Gem::Specification.new do |s| Gem::Specification.new do |s|
s.name = "swagger_client" s.name = "swagger_client"
s.version = SwaggerClient::Swagger::VERSION s.version = SwaggerClient::Swagger::VERSION
s.platform = Gem::Platform::RUBY s.platform = Gem::Platform::RUBY
s.authors = ["Zeke Sikelianos", "Tony Tam"] s.authors = ["Zeke Sikelianos", "Tony Tam"]
s.email = ["zeke@wordnik.com", "fehguy@gmail.com"] s.email = ["zeke@wordnik.com", "fehguy@gmail.com"]
s.homepage = "http://swagger.io" s.homepage = "http://swagger.io"
s.summary = %q{A ruby wrapper for the swagger APIs} s.summary = %q{A ruby wrapper for the swagger APIs}
s.description = %q{This gem maps to a swagger API} s.description = %q{This gem maps to a swagger API}
s.license = "Apache-2.0" s.license = "Apache-2.0"
s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1'
s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4' s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4'
s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6'
s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0' s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0'
s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3' s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3'
s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2' 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', '~> 4.4', '>= 4.4.6'
s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' 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-growl', '~> 0.2', '>= 0.2.16'
s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10'
s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? }
s.test_files = `find spec/*`.split("\n") s.test_files = `find spec/*`.split("\n")
s.executables = [] s.executables = []
s.require_paths = ["lib"] s.require_paths = ["lib"]
end end

Some files were not shown because too many files have changed in this diff Show More