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

@@ -6,423 +6,535 @@ using IO.Swagger.Client;
using IO.Swagger.Model; using IO.Swagger.Model;
namespace IO.Swagger.Api { namespace IO.Swagger.Api {
public interface IStoreApi { public interface IStoreApi {
/// <summary> ///
/// Returns pet inventories by status Returns a map of status codes to quantities <summary>
/// </summary> /// Returns pet inventories by status Returns a map of status codes to quantities
///
/// <returns>Dictionary<String, int?></returns> </summary>
Dictionary<String, int?> GetInventory ();
///
<returns>Dictionary<String, int?></returns>
Dictionary<String, int?> GetInventory ();
/// <summary> ///
/// Returns pet inventories by status Returns a map of status codes to quantities <summary>
/// </summary> /// Returns pet inventories by status Returns a map of status codes to quantities
///
</summary>
///
<returns>Dictionary<String, int?></returns>
Task<Dictionary<String, int?>> GetInventoryAsync ();
/// <returns>Dictionary<String, int?></returns> ///
Task<Dictionary<String, int?>> GetInventoryAsync (); <summary>
/// Place an order for a pet
///
</summary>
///
<param name="Body">order placed for purchasing the pet</param>
///
<returns>Order</returns>
Order PlaceOrder (Order Body);
///
<summary>
/// Place an order for a pet
///
</summary>
///
<param name="Body">order placed for purchasing the pet</param>
///
<returns>Order</returns>
Task<Order> PlaceOrderAsync (Order Body);
/// <summary> ///
/// Place an order for a pet <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
/// <param name="Body">order placed for purchasing the pet</param> ///
/// <returns>Order</returns> </summary>
Order PlaceOrder (Order Body); ///
<param name="OrderId">ID of pet that needs to be fetched</param>
///
<returns>Order</returns>
Order GetOrderById (string OrderId);
/// <summary> ///
/// Place an order for a pet <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
/// <param name="Body">order placed for purchasing the pet</param> ///
/// <returns>Order</returns> </summary>
Task<Order> PlaceOrderAsync (Order Body); ///
<param name="OrderId">ID of pet that needs to be fetched</param>
///
<returns>Order</returns>
Task<Order> GetOrderByIdAsync (string OrderId);
/// <summary> ///
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions <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
/// <param name="OrderId">ID of pet that needs to be fetched</param> ///
/// <returns>Order</returns> </summary>
Order GetOrderById (string OrderId); ///
<param name="OrderId">ID of the order that needs to be deleted</param>
///
<returns></returns>
void DeleteOrder (string OrderId);
/// <summary> ///
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions <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
/// <param name="OrderId">ID of pet that needs to be fetched</param> ///
/// <returns>Order</returns> </summary>
Task<Order> GetOrderByIdAsync (string OrderId); ///
<param name="OrderId">ID of the order that needs to be deleted</param>
///
<returns></returns>
Task DeleteOrderAsync (string OrderId);
/// <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
/// </summary>
/// <param name="OrderId">ID of the order that needs to be deleted</param>
/// <returns></returns>
void DeleteOrder (string OrderId);
/// <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
/// </summary>
/// <param name="OrderId">ID of the order that needs to be deleted</param>
/// <returns></returns>
Task DeleteOrderAsync (string OrderId);
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class StoreApi : IStoreApi {
/// <summary>
/// Initializes a new instance of the <see cref="StoreApi"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)
/// <returns></returns>
public StoreApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient;
} else {
this.apiClient = apiClient;
}
} }
/// <summary> ///
/// Initializes a new instance of the <see cref="StoreApi"/> class. <summary>
/// </summary> /// Represents a collection of functions to interact with the API endpoints
/// <returns></returns> ///
</summary>
public class StoreApi : IStoreApi {
///
<summary>
/// Initializes a new instance of the
<see cref="StoreApi"/>
class.
///
</summary>
///
<param name="apiClient"> an instance of ApiClient (optional)
///
<returns></returns>
public StoreApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient;
} else {
this.apiClient = apiClient;
}
}
///
<summary>
/// Initializes a new instance of the
<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> ///
/// Sets the base path of the API client. <summary>
/// </summary> /// Sets the base path of the API client.
/// <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> ///
/// Gets the base path of the API client. <summary>
/// </summary> /// Gets the base path of the API client.
/// <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> ///
/// Gets or sets the API client. <summary>
/// </summary> /// Gets or sets the API client.
/// <value>The API client</value> ///
</summary>
///
<value>The API client</value>
public ApiClient apiClient {get; set;} public ApiClient apiClient {get; set;}
/// <summary> ///
/// Returns pet inventories by status Returns a map of status codes to quantities <summary>
/// </summary> /// Returns pet inventories by status Returns a map of status codes to quantities
///
/// <returns>Dictionary<String, int?></returns> </summary>
public Dictionary<String, int?> GetInventory () {
///
<returns>Dictionary<String, int?></returns>
public Dictionary<String, int?> GetInventory () {
var path = "/store/inventory"; var path = "/store/inventory";
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>();
String postBody = null; var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null;
// authentication setting, if any // authentication setting, if any
String[] authSettings = new String[] { "api_key" }; String[] authSettings = new String[] { "api_key" };
// make the HTTP request // make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) { if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content);
} }
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>
/// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary>
/// <returns>Dictionary<String, int?></returns>
public async Task<Dictionary<String, int?>> GetInventoryAsync () {
///
<summary>
/// Returns pet inventories by status Returns a map of status codes to quantities
///
</summary>
///
<returns>Dictionary<String, int?></returns>
public async Task<Dictionary<String, int?>> GetInventoryAsync () {
var path = "/store/inventory";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var path = "/store/inventory";
var headerParams = new Dictionary<String, String>(); path = path.Replace("{format}", "json");
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
var queryParams = new Dictionary
<String, String>();
var headerParams = new Dictionary
<String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null;
// authentication setting, if any
String[] authSettings = new String[] { "api_key" };
// make the HTTP request // authentication setting, if any
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); String[] authSettings = new String[] { "api_key" };
if (((int)response.StatusCode) >= 400) {
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content);
} }
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> ///
/// Place an order for a pet <summary>
/// </summary> /// Place an order for a pet
/// <param name="Body">order placed for purchasing the pet</param> ///
/// <returns>Order</returns> </summary>
public Order PlaceOrder (Order Body) { ///
<param name="Body">order placed for purchasing the pet</param>
///
<returns>Order</returns>
public Order PlaceOrder (Order Body) {
var path = "/store/order"; var path = "/store/order";
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>();
String postBody = null; var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null;
postBody = apiClient.Serialize(Body); // http body (model) parameter postBody = apiClient.Serialize(Body); // http body (model) parameter
// authentication setting, if any // authentication setting, if any
String[] authSettings = new String[] { }; String[] authSettings = new String[] { };
// make the HTTP request // make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) { if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content);
} }
return (Order) apiClient.Deserialize(response.Content, typeof(Order)); return (Order) apiClient.Deserialize(response.Content, typeof(Order));
} }
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name="Body">order placed for purchasing the pet</param>
/// <returns>Order</returns>
public async Task<Order> PlaceOrderAsync (Order Body) {
///
<summary>
/// Place an order for a pet
///
</summary>
///
<param name="Body">order placed for purchasing the pet</param>
///
<returns>Order</returns>
public async Task<Order> PlaceOrderAsync (Order Body) {
var path = "/store/order";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>(); var path = "/store/order";
var headerParams = new Dictionary<String, String>(); path = path.Replace("{format}", "json");
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
var queryParams = new Dictionary
<String, String>();
var headerParams = new Dictionary
postBody = apiClient.Serialize(Body); // http body (model) parameter <String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null;
// authentication setting, if any
String[] authSettings = new String[] { };
postBody = apiClient.Serialize(Body); // http body (model) parameter
// make the HTTP request // authentication setting, if any
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings); String[] authSettings = new String[] { };
if (((int)response.StatusCode) >= 400) {
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content); throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content, response.Content);
} }
return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order));
} }
/// <summary> ///
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions <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
/// <param name="OrderId">ID of pet that needs to be fetched</param> ///
/// <returns>Order</returns> </summary>
public Order GetOrderById (string OrderId) { ///
<param name="OrderId">ID of pet that needs to be fetched</param>
///
<returns>Order</returns>
public Order GetOrderById (string OrderId) {
// verify the required parameter 'OrderId' is set // verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById"); if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById");
var path = "/store/order/{orderId}"; var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
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>();
String postBody = null; var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null;
// authentication setting, if any // authentication setting, if any
String[] authSettings = new String[] { }; String[] authSettings = new String[] { };
// make the HTTP request // make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) { if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content);
} }
return (Order) apiClient.Deserialize(response.Content, typeof(Order)); return (Order) apiClient.Deserialize(response.Content, typeof(Order));
} }
/// <summary>
/// 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>
/// <returns>Order</returns>
public async Task<Order> GetOrderByIdAsync (string OrderId) {
///
// verify the required parameter 'OrderId' is set <summary>
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById"); /// 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>
///
<returns>Order</returns>
public async Task<Order> GetOrderByIdAsync (string OrderId) {
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json"); // verify the required parameter 'OrderId' is set
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById");
var queryParams = new Dictionary<String, String>(); var path = "/store/order/{orderId}";
var headerParams = new Dictionary<String, String>(); path = path.Replace("{format}", "json");
var formParams = new Dictionary<String, String>(); path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
var fileParams = new Dictionary<String, String>();
String postBody = null;
var queryParams = new Dictionary
<String, String>();
var headerParams = new Dictionary
<String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null;
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request // authentication setting, if any
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings); String[] authSettings = new String[] { };
if (((int)response.StatusCode) >= 400) {
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content); throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content, response.Content);
} }
return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order));
} }
/// <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 <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
/// <param name="OrderId">ID of the order that needs to be deleted</param> ///
/// <returns></returns> </summary>
public void DeleteOrder (string OrderId) { ///
<param name="OrderId">ID of the order that needs to be deleted</param>
///
<returns></returns>
public void DeleteOrder (string OrderId) {
// verify the required parameter 'OrderId' is set // verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder"); if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder");
var path = "/store/order/{orderId}"; var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json"); path = path.Replace("{format}", "json");
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>();
String postBody = null; var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null;
// authentication setting, if any // authentication setting, if any
String[] authSettings = new String[] { }; String[] authSettings = new String[] { };
// make the HTTP request // make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) { if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content);
} }
return; return;
} }
/// <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
/// </summary>
/// <param name="OrderId">ID of the order that needs to be deleted</param>
/// <returns></returns>
public async Task DeleteOrderAsync (string OrderId) {
///
// verify the required parameter 'OrderId' is set <summary>
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder"); /// 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>
///
<returns></returns>
public async Task DeleteOrderAsync (string OrderId) {
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json"); // verify the required parameter 'OrderId' is set
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId)); if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder");
var queryParams = new Dictionary<String, String>(); var path = "/store/order/{orderId}";
var headerParams = new Dictionary<String, String>(); path = path.Replace("{format}", "json");
var formParams = new Dictionary<String, String>(); path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
var fileParams = new Dictionary<String, String>();
String postBody = null;
var queryParams = new Dictionary
<String, String>();
var headerParams = new Dictionary
<String, String>();
var formParams = new Dictionary
<String, String>();
var fileParams = new Dictionary
<String, String>();
String postBody = null;
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request // authentication setting, if any
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings); String[] authSettings = new String[] { };
if (((int)response.StatusCode) >= 400) {
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content); throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content, response.Content);
} }
return; return;
} }
} }
} }

View File

@@ -5,50 +5,58 @@ using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class Category {
namespace IO.Swagger.Model {
///
<summary>
///
///
</summary>
[DataContract]
public class Category {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
///
<summary>
/// Get the string presentation of the object
///
</summary>
///
<returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class Category {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
///
<summary>
/// Get the JSON string presentation of the object
///
</summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class Category {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
} }

View File

@@ -5,78 +5,86 @@ using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace IO.Swagger.Model {
namespace IO.Swagger.Model {
/// <summary> ///
/// <summary>
/// </summary> ///
[DataContract] ///
public class Order { </summary>
[DataContract]
public class Order {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="petId", EmitDefaultValue=false)] [DataMember(Name="petId", EmitDefaultValue=false)]
public long? PetId { get; set; } public long? PetId { get; set; }
[DataMember(Name="quantity", EmitDefaultValue=false)] [DataMember(Name="quantity", EmitDefaultValue=false)]
public int? Quantity { get; set; } public int? Quantity { get; set; }
[DataMember(Name="shipDate", EmitDefaultValue=false)] [DataMember(Name="shipDate", EmitDefaultValue=false)]
public DateTime? ShipDate { get; set; } public DateTime? ShipDate { get; set; }
/* Order Status */
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
[DataMember(Name="complete", EmitDefaultValue=false)]
public bool? Complete { get; set; }
///
<summary>
/// Get the string presentation of the object
///
</summary>
///
<returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class Order {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" PetId: ").Append(PetId).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" ShipDate: ").Append(ShipDate).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Complete: ").Append(Complete).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
///
<summary>
/// Get the JSON string presentation of the object
///
</summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
/* Order Status */
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
[DataMember(Name="complete", EmitDefaultValue=false)]
public bool? Complete { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class Order {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" PetId: ").Append(PetId).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" ShipDate: ").Append(ShipDate).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Complete: ").Append(Complete).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
} }

View File

@@ -5,78 +5,86 @@ using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace IO.Swagger.Model {
namespace IO.Swagger.Model {
/// <summary> ///
/// <summary>
/// </summary> ///
[DataContract] ///
public class Pet { </summary>
[DataContract]
public class Pet {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="category", EmitDefaultValue=false)] [DataMember(Name="category", EmitDefaultValue=false)]
public Category Category { get; set; } public Category Category { get; set; }
[DataMember(Name="name", EmitDefaultValue=false)] [DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; } public string Name { get; set; }
[DataMember(Name="photoUrls", EmitDefaultValue=false)] [DataMember(Name="photoUrls", EmitDefaultValue=false)]
public List<string> PhotoUrls { get; set; } public List<string> PhotoUrls { get; set; }
[DataMember(Name="tags", EmitDefaultValue=false)]
public List<Tag> Tags { get; set; }
/* pet status in the store */
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
///
<summary>
/// Get the string presentation of the object
///
</summary>
///
<returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class Pet {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Category: ").Append(Category).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n");
sb.Append(" Tags: ").Append(Tags).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
///
<summary>
/// Get the JSON string presentation of the object
///
</summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
[DataMember(Name="tags", EmitDefaultValue=false)]
public List<Tag> Tags { get; set; }
/* pet status in the store */
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class Pet {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Category: ").Append(Category).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n");
sb.Append(" Tags: ").Append(Tags).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
} }

View File

@@ -5,50 +5,58 @@ using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class Tag {
namespace IO.Swagger.Model {
///
<summary>
///
///
</summary>
[DataContract]
public class Tag {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
///
<summary>
/// Get the string presentation of the object
///
</summary>
///
<returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class Tag {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
///
<summary>
/// Get the JSON string presentation of the object
///
</summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class Tag {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
} }

View File

@@ -5,92 +5,100 @@ using System.Collections.Generic;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace IO.Swagger.Model {
namespace IO.Swagger.Model {
/// <summary> ///
/// <summary>
/// </summary> ///
[DataContract] ///
public class User { </summary>
[DataContract]
public class User {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="username", EmitDefaultValue=false)] [DataMember(Name="username", EmitDefaultValue=false)]
public string Username { get; set; } public string Username { get; set; }
[DataMember(Name="firstName", EmitDefaultValue=false)] [DataMember(Name="firstName", EmitDefaultValue=false)]
public string FirstName { get; set; } public string FirstName { get; set; }
[DataMember(Name="lastName", EmitDefaultValue=false)] [DataMember(Name="lastName", EmitDefaultValue=false)]
public string LastName { get; set; } public string LastName { get; set; }
[DataMember(Name="email", EmitDefaultValue=false)] [DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; } public string Email { get; set; }
[DataMember(Name="password", EmitDefaultValue=false)] [DataMember(Name="password", EmitDefaultValue=false)]
public string Password { get; set; } public string Password { get; set; }
[DataMember(Name="phone", EmitDefaultValue=false)]
public string Phone { get; set; }
/* User Status */
[DataMember(Name="userStatus", EmitDefaultValue=false)]
public int? UserStatus { get; set; }
///
<summary>
/// Get the string presentation of the object
///
</summary>
///
<returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class User {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Username: ").Append(Username).Append("\n");
sb.Append(" FirstName: ").Append(FirstName).Append("\n");
sb.Append(" LastName: ").Append(LastName).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" Password: ").Append(Password).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" UserStatus: ").Append(UserStatus).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
///
<summary>
/// Get the JSON string presentation of the object
///
</summary>
///
<returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
[DataMember(Name="phone", EmitDefaultValue=false)]
public string Phone { get; set; }
/* User Status */
[DataMember(Name="userStatus", EmitDefaultValue=false)]
public int? UserStatus { get; set; }
/// <summary>
/// Get the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() {
var sb = new StringBuilder();
sb.Append("class User {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Username: ").Append(Username).Append("\n");
sb.Append(" FirstName: ").Append(FirstName).Append("\n");
sb.Append(" LastName: ").Append(LastName).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" Password: ").Append(Password).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" UserStatus: ").Append(UserStatus).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Get the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson() {
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
}
} }

View File

@@ -9,214 +9,310 @@ using Newtonsoft.Json;
using RestSharp; using RestSharp;
namespace IO.Swagger.Client { namespace IO.Swagger.Client {
/// <summary> ///
/// API client is mainly responible for making the HTTP call to the API backend <summary>
/// </summary> /// API client is mainly responible for making the HTTP call to the API backend
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,
Dictionary
<String
, String> HeaderParams, Dictionary
<String
, String> FormParams, Dictionary
<String
, String> FileParams, String[] AuthSettings) {
var request = new RestRequest(Path, Method);
UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings);
// add default header, if any
foreach(KeyValuePair
<string
, string> defaultHeader in this.defaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(KeyValuePair
<string
, string> param in HeaderParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(KeyValuePair
<string
, string> param in QueryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(KeyValuePair
<string
, string> param in FormParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(KeyValuePair
<string
, string> param in FileParams)
request.AddFile(param.Key, param.Value);
if (PostBody != null) {
request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter
} }
public async Task<Object> CallApiAsync(String Path, RestSharp.Method Method, Dictionary<String, String> QueryParams, String PostBody, return (Object) await restClient.ExecuteTaskAsync(request);
Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) {
var request = new RestRequest(Path, Method);
UpdateParamsForAuth(QueryParams, HeaderParams, AuthSettings);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in this.defaultHeaderMap)
request.AddHeader(defaultHeader.Key, defaultHeader.Value);
// add header parameter, if any
foreach(KeyValuePair<string, string> param in HeaderParams)
request.AddHeader(param.Key, param.Value);
// add query parameter, if any
foreach(KeyValuePair<string, string> param in QueryParams)
request.AddQueryParameter(param.Key, param.Value);
// add form parameter, if any
foreach(KeyValuePair<string, string> param in FormParams)
request.AddParameter(param.Key, param.Value);
// add file parameter, if any
foreach(KeyValuePair<string, string> param in FileParams)
request.AddFile(param.Key, param.Value);
if (PostBody != null) {
request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter
}
return (Object) await restClient.ExecuteTaskAsync(request);
} }
/// <summary> ///
/// Add default header <summary>
/// </summary> /// Add default header
/// <param name="key"> Header field name ///
/// <param name="value"> Header field value </summary>
/// <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> ///
/// Get default header <summary>
/// </summary> /// Get default header
/// <returns>Dictionary of default header</returns> ///
public Dictionary<String, String> GetDefaultHeader() { </summary>
return defaultHeaderMap; ///
<returns>Dictionary of default header</returns>
public Dictionary
<String
, String> GetDefaultHeader() {
return defaultHeaderMap;
} }
/// <summary> ///
/// escape string (url-encoded) <summary>
/// </summary> /// escape string (url-encoded)
/// <param name="str"> String to be escaped ///
/// <returns>Escaped string</returns> </summary>
///
<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> ///
/// if parameter is DateTime, output in ISO8601 format <summary>
/// if parameter is a list of string, join the list with "," /// if parameter is DateTime, output in ISO8601 format
/// otherwise just return the string /// if parameter is a list of string, join the list with ","
/// </summary> /// otherwise just return the string
/// <param name="obj"> The parameter (header, path, query, form) ///
/// <returns>Formatted string</returns> </summary>
///
<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>) {
} else { return String.Join(",", obj as List
return Convert.ToString (obj); <string>);
} } else {
} return Convert.ToString (obj);
}
}
/// <summary> ///
/// Deserialize the JSON string into a proper object <summary>
/// </summary> /// Deserialize the JSON string into a proper object
/// <param name="json"> JSON string ///
/// <param name="type"> Object type </summary>
/// <returns>Object representation of the JSON string</returns> ///
public object Deserialize(string content, Type type) { <param name="json">
if (type.GetType() == typeof(Object)) JSON string
return (Object)content; ///
<param name="type">
Object type
///
<returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type) {
if (type.GetType() == typeof(Object))
return (Object)content;
try try
{ {
return JsonConvert.DeserializeObject(content, type); return JsonConvert.DeserializeObject(content, type);
} }
catch (IOException e) { catch (IOException e) {
throw new ApiException(500, e.Message); throw new ApiException(500, e.Message);
} }
} }
/// <summary> ///
/// Serialize an object into JSON string <summary>
/// </summary> /// Serialize an object into JSON string
/// <param name="obj"> Object ///
/// <returns>JSON string</returns> </summary>
public string Serialize(object obj) { ///
try <param name="obj">
{ Object
return obj != null ? JsonConvert.SerializeObject(obj) : null; ///
} <returns>JSON string</returns>
catch (Exception e) { public string Serialize(object obj) {
throw new ApiException(500, e.Message); try
} {
} return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
/// <summary> ///
/// Get the API key with prefix <summary>
/// </summary> /// Get the API key with prefix
/// <param name="obj"> Object ///
/// <returns>API key with prefix</returns> </summary>
public string GetApiKeyWithPrefix (string apiKey) ///
{ <param name="obj">
var apiKeyValue = ""; Object
Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue); ///
var apiKeyPrefix = ""; <returns>API key with prefix</returns>
if (Configuration.apiKeyPrefix.TryGetValue (apiKey, out apiKeyPrefix)) { public string GetApiKeyWithPrefix (string apiKey)
return apiKeyPrefix + " " + apiKeyValue; {
} else { var apiKeyValue = "";
return apiKeyValue; Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue);
} var apiKeyPrefix = "";
} if (Configuration.apiKeyPrefix.TryGetValue (apiKey, out apiKeyPrefix)) {
return apiKeyPrefix + " " + apiKeyValue;
} else {
return apiKeyValue;
}
}
/// <summary> ///
/// Update parameters based on authentication <summary>
/// </summary> /// Update parameters based on authentication
/// <param name="QueryParams">Query parameters</param> ///
/// <param name="HeaderParams">Header parameters</param> </summary>
/// <param name="AuthSettings">Authentication settings</param> ///
public void UpdateParamsForAuth(Dictionary<String, String> QueryParams, Dictionary<String, String> HeaderParams, string[] AuthSettings) { <param name="QueryParams">
if (AuthSettings == null || AuthSettings.Length == 0) Query parameters</param>
return; ///
<param name="HeaderParams">
foreach (string auth in AuthSettings) { Header parameters</param>
// determine which one to use ///
switch(auth) { <param name="AuthSettings">
Authentication settings</param>
case "api_key": public void UpdateParamsForAuth(Dictionary
HeaderParams["api_key"] = GetApiKeyWithPrefix("api_key"); <String
, String> QueryParams, Dictionary
<String
, String> HeaderParams, string[] AuthSettings) {
if (AuthSettings == null || AuthSettings.Length == 0)
return;
foreach (string auth in AuthSettings) {
// determine which one to use
switch(auth) {
break; case "api_key":
HeaderParams["api_key"] = GetApiKeyWithPrefix("api_key
case "petstore_auth": ");
break;
//TODO support oauth case "petstore_auth":
break;
//TODO support oauth
default: break;
default:
//TODO show warning about security definition not found //TODO show warning about security definition not found
break; break;
} }
} }
} }
/// <summary> ///
/// Encode string in base64 format <summary>
/// </summary> /// Encode string in base64 format
/// <param name="text">String to be encoded</param> ///
public static string Base64Encode(string text) { </summary>
var textByte = System.Text.Encoding.UTF8.GetBytes(text); ///
return System.Convert.ToBase64String(textByte); <param name="text">
} String to be encoded</param>
public static string Base64Encode(string text) {
var textByte = System.Text.Encoding.UTF8.GetBytes(text);
return System.Convert.ToBase64String(textByte);
}
} }
} }

View File

@@ -1,42 +1,61 @@
using System; using System;
namespace IO.Swagger.Client { namespace IO.Swagger.Client {
/// <summary> ///
/// API Exception <summary>
/// </summary> /// API Exception
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> ///
/// Represents a set of configuration settings <summary>
/// </summary> /// Represents a set of configuration settings
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> ///
/// Gets or sets the API key based on the authentication name <summary>
/// </summary> /// Gets or sets the API key based on the authentication name
/// <value>The API key.</value> ///
public static Dictionary<String, String> apiKey = new Dictionary<String, String>(); </summary>
///
<value>The API key.</value>
public static Dictionary
<String, String> apiKey = new Dictionary
<String, String>();
/// <summary> ///
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name <summary>
/// </summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name
/// <value>The prefix of the API key.</value> ///
public static Dictionary<String, String> apiKeyPrefix = new Dictionary<String, String>(); </summary>
///
<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 @protocol SWGCategory
@end @end
@interface SWGCategory : SWGObject
@interface SWGCategory : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSString* name;
@property(nonatomic) NSString* name; @end
@end

View File

@@ -1,22 +1,24 @@
#import "SWGCategory.h"
#import "SWGCategory.h"
@implementation SWGCategory @implementation SWGCategory
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }];
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName + (JSONKeyMapper *)keyMapper
{ {
NSArray *optionalProperties = @[@"_id", @"name"]; return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }];
}
if ([optionalProperties containsObject:propertyName]) { + (BOOL)propertyIsOptional:(NSString *)propertyName
return YES; {
} NSArray *optionalProperties = @[@"_id", @"name"];
else {
return NO;
}
}
@end if ([optionalProperties containsObject:propertyName]) {
return YES;
}
else {
return NO;
}
}
@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,81 +12,81 @@
#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",
@"key": @"api_key", @"key": @"api_key",
@"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 @protocol SWGOrder
@end @end
@interface SWGOrder : SWGObject
@interface SWGOrder : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* petId;
@property(nonatomic) NSNumber* quantity;
@property(nonatomic) NSDate* shipDate;
/* Order Status [optional]
*/
@property(nonatomic) NSString* status;
@property(nonatomic) BOOL complete;
@property(nonatomic) NSNumber* petId; @end
@property(nonatomic) NSNumber* quantity;
@property(nonatomic) NSDate* shipDate;
/* Order Status [optional]
*/
@property(nonatomic) NSString* status;
@property(nonatomic) BOOL complete;
@end

View File

@@ -1,22 +1,24 @@
#import "SWGOrder.h"
#import "SWGOrder.h"
@implementation SWGOrder @implementation SWGOrder
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }];
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName + (JSONKeyMapper *)keyMapper
{ {
NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"]; return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }];
}
if ([optionalProperties containsObject:propertyName]) { + (BOOL)propertyIsOptional:(NSString *)propertyName
return YES; {
} NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"];
else {
return NO;
}
}
@end if ([optionalProperties containsObject:propertyName]) {
return YES;
}
else {
return NO;
}
}
@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 @protocol SWGPet
@end @end
@interface SWGPet : SWGObject
@interface SWGPet : SWGObject
@property(nonatomic) NSNumber* _id;
@property(nonatomic) NSNumber* _id;
@property(nonatomic) SWGCategory* category;
@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) SWGCategory* category; @end
@property(nonatomic) NSString* name;
@property(nonatomic) NSArray* photoUrls;
@property(nonatomic) NSArray<SWGTag>* tags;
/* pet status in the store [optional]
*/
@property(nonatomic) NSString* status;
@end

View File

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

View File

@@ -1,157 +1,167 @@
#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
@param body Pet object that needs to be added to the store
return type:
*/
-(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body
/**
Update an existing pet
@param body Pet object that needs to be added to the store
return type:
*/
-(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock;
completionHandler: (void (^)(NSError* error))completionBlock; /**
Add a new pet to the store
/** @param body Pet object that needs to be added to the store
Add a new pet to the store return type:
*/
-(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body
completionHandler: (void (^)(NSError* error))completionBlock;
@param body Pet object that needs to be added to the store
return type:
*/
-(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body
/**
Finds Pets by status
Multiple status values can be provided with comma seperated strings
@param status Status values that need to be considered for filter
return type: NSArray<SWGPet>*
*/
-(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock;
completionHandler: (void (^)(NSError* error))completionBlock; /**
Finds Pets by tags
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
/** @param tags Tags to filter by
Finds Pets by status return type: NSArray<SWGPet>*
Multiple status values can be provided with comma seperated strings */
-(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock;
@param status Status values that need to be considered for filter
return type: NSArray<SWGPet>*
*/
-(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock; /**
Find pet by ID
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
return type: SWGPet*
*/
-(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock;
/**
Updates a pet in the store with form data
/** @param petId ID of pet that needs to be updated
@param name Updated name of the pet
@param status Updated status of the pet
Finds Pets by tags return type:
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. */
-(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId
name:(NSString*) name
status:(NSString*) status
completionHandler: (void (^)(NSError* error))completionBlock;
@param tags Tags to filter by
return type: NSArray<SWGPet>*
*/
-(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error))completionBlock; /**
Deletes a pet
@param apiKey
@param petId Pet id to delete
return type:
*/
-(NSNumber*) deletePetWithCompletionBlock :(NSString*) apiKey
petId:(NSNumber*) petId
completionHandler: (void (^)(NSError* error))completionBlock;
/**
uploads an image
/** @param petId ID of pet to update
@param additionalMetadata Additional data to pass to server
@param file file to upload
Find pet by ID return type:
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions */
-(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId
additionalMetadata:(NSString*) additionalMetadata
file:(SWGFile*) file
completionHandler: (void (^)(NSError* error))completionBlock;
@param petId ID of pet that needs to be fetched
return type: SWGPet*
*/
-(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock;
/**
Updates a pet in the store with form data
@param petId ID of pet that needs to be updated
@param name Updated name of the pet
@param status Updated status of the pet
return type:
*/
-(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId
name:(NSString*) name
status:(NSString*) status
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Deletes a pet
@param apiKey
@param petId Pet id to delete
return type:
*/
-(NSNumber*) deletePetWithCompletionBlock :(NSString*) apiKey
petId:(NSNumber*) petId
completionHandler: (void (^)(NSError* error))completionBlock;
/**
uploads an image
@param petId ID of pet to update
@param additionalMetadata Additional data to pass to server
@param file file to upload
return type:
*/
-(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId
additionalMetadata:(NSString*) additionalMetadata
file:(SWGFile*) file
completionHandler: (void (^)(NSError* error))completionBlock;
@end @end

File diff suppressed because it is too large Load Diff

View File

@@ -1,80 +1,86 @@
#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 a map of status codes to quantities
return type: NSDictionary*
*/
-(NSNumber*) getInventoryWithCompletionBlock :
(void (^)(NSDictionary* output, NSError* error))completionBlock;
/**
Returns pet inventories by status
Returns a map of status codes to quantities
/**
Place an order for a pet return type: NSDictionary*
*/
-(NSNumber*) getInventoryWithCompletionBlock :
(void (^)(NSDictionary* output, NSError* error))completionBlock;
@param body order placed for purchasing the pet
return type: SWGOrder*
*/
-(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; /**
Place an order for a pet
@param body order placed for purchasing the pet
return type: SWGOrder*
*/
-(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock;
/**
Find purchase order by ID
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
Find purchase order by ID return type: SWGOrder*
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions */
-(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock;
@param orderId ID of pet that needs to be fetched
return type: SWGOrder*
*/
-(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; /**
Delete purchase order by ID
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
return type:
*/
-(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Delete purchase order by ID
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
return type:
*/
-(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId
completionHandler: (void (^)(NSError* error))completionBlock;
@end @end

View File

@@ -1,478 +1,478 @@
#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) {
self.apiClient = apiClient; self.apiClient = apiClient;
} }
else { else {
self.apiClient = [SWGApiClient sharedClientFromPool:basePath]; self.apiClient = [SWGApiClient sharedClientFromPool:basePath];
} }
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) {
singletonAPI = [[SWGStoreApi alloc] init]; singletonAPI = [[SWGStoreApi alloc] init];
[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 a map of status codes to quantities * Returns pet inventories by status
* \returns NSDictionary* * Returns a map of status codes to quantities
*/ * \returns NSDictionary*
-(NSNumber*) getInventoryWithCompletionBlock: */
-(NSNumber*) getInventoryWithCompletionBlock:
(void (^)(NSDictionary* output, NSError* error))completionBlock (void (^)(NSDictionary* output, NSError* error))completionBlock
{ {
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath]; NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath];
// remove format in URL if needed // remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
// HTTP header `Accept` // HTTP header `Accept`
headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]];
if ([headerParams[@"Accept"] length] == 0) { if ([headerParams[@"Accept"] length] == 0) {
[headerParams removeObjectForKey:@"Accept"]; [headerParams removeObjectForKey:@"Accept"];
} }
// response content type // response content type
NSString *responseContentType; NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) { if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
} }
else { else {
responseContentType = @""; responseContentType = @"";
} }
// request content type // request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting // Authentication setting
NSArray *authSettings = @[@"api_key"]; NSArray *authSettings = @[@"api_key"];
id bodyDictionary = nil;
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; id bodyDictionary = nil;
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
// response is in a container
// map container response type
return [self.apiClient dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
NSDictionary *result = nil;
if (data) {
result = [[NSDictionary alloc]initWithDictionary: data];
}
completionBlock(data, nil);
}];
// response is in a container
// map container response type
return [self.apiClient dictionary: requestUrl
method: @"GET"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
} }
NSDictionary *result = nil;
if (data) {
result = [[NSDictionary alloc]initWithDictionary: data];
}
completionBlock(data, nil);
}];
/*!
* Place an order for a pet
*
* \param body order placed for purchasing the pet
* \returns SWGOrder* }
*/
-(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body
/*!
* Place an order for a pet
*
* \param body order placed for purchasing the pet
* \returns SWGOrder*
*/
-(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
{ {
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath]; NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath];
// remove format in URL if needed // remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
// HTTP header `Accept` // HTTP header `Accept`
headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]];
if ([headerParams[@"Accept"] length] == 0) { if ([headerParams[@"Accept"] length] == 0) {
[headerParams removeObjectForKey:@"Accept"]; [headerParams removeObjectForKey:@"Accept"];
} }
// response content type // response content type
NSString *responseContentType; NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) { if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
} }
else { else {
responseContentType = @""; responseContentType = @"";
} }
// request content type // request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting // Authentication setting
NSArray *authSettings = @[]; NSArray *authSettings = @[];
id bodyDictionary = nil;
id __body = body;
if(__body != nil && [__body isKindOfClass:[NSArray class]]){ id bodyDictionary = nil;
NSMutableArray * objs = [[NSMutableArray alloc] init];
for (id dict in (NSArray*)__body) { id __body = body;
if(__body != nil && [__body isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] init];
for (id dict in (NSArray*)__body) {
if([dict respondsToSelector:@selector(toDictionary)]) { if([dict respondsToSelector:@selector(toDictionary)]) {
[objs addObject:[(SWGObject*)dict toDictionary]]; [objs addObject:[(SWGObject*)dict toDictionary]];
} }
else{ else{
[objs addObject:dict]; [objs addObject:dict];
} }
} }
bodyDictionary = objs; bodyDictionary = objs;
} }
else if([__body respondsToSelector:@selector(toDictionary)]) { else if([__body respondsToSelector:@selector(toDictionary)]) {
bodyDictionary = [(SWGObject*)__body toDictionary]; bodyDictionary = [(SWGObject*)__body toDictionary];
} }
else if([__body isKindOfClass:[NSString class]]) { else if([__body isKindOfClass:[NSString class]]) {
// convert it to a dictionary // convert it to a dictionary
NSError * error; NSError * error;
NSString * str = (NSString*)__body; NSString * str = (NSString*)__body;
NSDictionary *JSON = NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers options: NSJSONReadingMutableContainers
error: &error]; error: &error];
bodyDictionary = JSON; bodyDictionary = JSON;
} }
// non container response
// complex response
// comples response type
// non container response
// complex response
// comples response type
return [self.apiClient dictionary: requestUrl return [self.apiClient dictionary: 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: ^(NSDictionary *data, NSError *error) { completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) { if (error) {
completionBlock(nil, error); completionBlock(nil, error);
return;
}
SWGOrder* result = nil;
if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
return;
}
SWGOrder* result = nil;
if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
}
/*!
* Find purchase order by ID
} * 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
/*! * \returns SWGOrder*
* Find purchase order by ID */
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId
* \param orderId ID of pet that needs to be fetched
* \returns SWGOrder*
*/
-(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
{ {
// verify the required parameter 'orderId' is set // verify the required parameter 'orderId' is set
NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling getOrderById"); NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling getOrderById");
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath];
// remove format in URL if needed // remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]];
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
// HTTP header `Accept`
headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]];
if ([headerParams[@"Accept"] length] == 0) {
[headerParams removeObjectForKey:@"Accept"];
}
// response content type
NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
}
else {
responseContentType = @"";
}
// request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting
NSArray *authSettings = @[];
id bodyDictionary = nil;
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
// non container response
// complex response
// comples response type
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
// HTTP header `Accept`
headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]];
if ([headerParams[@"Accept"] length] == 0) {
[headerParams removeObjectForKey:@"Accept"];
}
// response content type
NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
}
else {
responseContentType = @"";
}
// request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting
NSArray *authSettings = @[];
id bodyDictionary = nil;
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
// non container response
// complex response
// comples 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;
}
SWGOrder* result = nil;
if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
return;
}
SWGOrder* result = nil;
if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
}
/*!
* Delete purchase order by ID
} * 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
/*! * \returns void
* Delete purchase order by ID */
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId
* \param orderId ID of the order that needs to be deleted
* \returns void
*/
-(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(NSError* error))completionBlock { completionHandler: (void (^)(NSError* error))completionBlock {
// verify the required parameter 'orderId' is set // verify the required parameter 'orderId' is set
NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling deleteOrder"); NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling deleteOrder");
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath];
// remove format in URL if needed // remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]];
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
// HTTP header `Accept` // HTTP header `Accept`
headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]]; headerParams[@"Accept"] = [SWGApiClient selectHeaderAccept:@[@"application/json", @"application/xml"]];
if ([headerParams[@"Accept"] length] == 0) { if ([headerParams[@"Accept"] length] == 0) {
[headerParams removeObjectForKey:@"Accept"]; [headerParams removeObjectForKey:@"Accept"];
} }
// response content type // response content type
NSString *responseContentType; NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) { if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0]; responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
} }
else { else {
responseContentType = @""; responseContentType = @"";
} }
// request content type // request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting // Authentication setting
NSArray *authSettings = @[]; NSArray *authSettings = @[];
id bodyDictionary = nil;
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; id bodyDictionary = nil;
NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init];
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
// it's void
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"DELETE"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
} }
completionBlock(nil);
}];
}
@end @end

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,148 +1,158 @@
#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
This can only be done by the logged in user.
@param body Created user object
return type:
*/
-(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body
/**
Create user
This can only be done by the logged in user.
@param body Created user object
return type:
*/
-(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock;
completionHandler: (void (^)(NSError* error))completionBlock; /**
Creates list of users with given input array
/** @param body List of user object
Creates list of users with given input array return type:
*/
-(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error))completionBlock;
@param body List of user object
return type:
*/
-(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray<SWGUser>*) body
/**
Creates list of users with given input array
@param body List of user object
return type:
*/
-(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error))completionBlock;
completionHandler: (void (^)(NSError* error))completionBlock; /**
Logs user into the system
/** @param username The user name for login
@param password The password for login in clear text
Creates list of users with given input array return type: NSString*
*/
-(NSNumber*) loginUserWithCompletionBlock :(NSString*) username
password:(NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error))completionBlock;
@param body List of user object
return type:
*/
-(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray<SWGUser>*) body
/**
Logs out current logged in user session
return type:
*/
-(NSNumber*) logoutUserWithCompletionBlock :
(void (^)(NSError* error))completionBlock;
completionHandler: (void (^)(NSError* error))completionBlock; /**
Get user by user name
/** @param username The name that needs to be fetched. Use user1 for testing.
Logs user into the system return type: SWGUser*
*/
-(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock;
@param username The user name for login
@param password The password for login in clear text
return type: NSString*
*/
-(NSNumber*) loginUserWithCompletionBlock :(NSString*) username
password:(NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error))completionBlock; /**
Updated user
This can only be done by the logged in user.
@param username name that need to be deleted
@param body Updated user object
return type:
*/
-(NSNumber*) updateUserWithCompletionBlock :(NSString*) username
body:(SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Delete user
This can only be done by the logged in user.
/** @param username The name that needs to be deleted
Logs out current logged in user session return type:
*/
-(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username
completionHandler: (void (^)(NSError* error))completionBlock;
return type:
*/
-(NSNumber*) logoutUserWithCompletionBlock :
(void (^)(NSError* error))completionBlock;
/**
Get user by user name
@param username The name that needs to be fetched. Use user1 for testing.
return type: SWGUser*
*/
-(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock;
/**
Updated user
This can only be done by the logged in user.
@param username name that need to be deleted
@param body Updated user object
return type:
*/
-(NSNumber*) updateUserWithCompletionBlock :(NSString*) username
body:(SWGUser*) body
completionHandler: (void (^)(NSError* error))completionBlock;
/**
Delete user
This can only be done by the logged in user.
@param username The name that needs to be deleted
return type:
*/
-(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username
completionHandler: (void (^)(NSError* error))completionBlock;
@end @end

File diff suppressed because it is too large Load Diff

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 // one endpoint can have more than 1 auth settings
foreach($authSettings as $auth) { foreach($authSettings as $auth) {
// determine which one to use // determine which one to use
switch($auth) { 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
break;
//TODO support oauth default:
break; //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) {
# determine authentication setting $headers = array();
$this->updateParamsForAuth($headerParams, $queryParams, $authSettings);
# construct the http header # determine authentication setting
$headerParams = array_merge((array)self::$default_header, (array)$headerParams); $this->updateParamsForAuth($headerParams, $queryParams, $authSettings);
foreach ($headerParams as $key => $val) { # construct the http header
$headers[] = "$key: $val"; $headerParams = array_merge((array)self::$default_header, (array)$headerParams);
}
// form data foreach ($headerParams as $key => $val) {
if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { $headers[] = "$key: $val";
$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; // form data
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));
}
$curl = curl_init(); $url = $this->host . $resourcePath;
// 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); $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);
if (! empty($queryParams)) { curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$url = ($url . '?' . http_build_query($queryParams));
}
if ($method == self::$POST) { if (! empty($queryParams)) {
curl_setopt($curl, CURLOPT_POST, true); $url = ($url . '?' . http_build_query($queryParams));
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 if ($method == self::$POST) {
curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); 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);
// debugging for curl // Set user agent
if (Configuration::$debug) { curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file);
curl_setopt($curl, CURLOPT_VERBOSE, 1); // debugging for curl
curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a')); if (Configuration::$debug) {
} else { error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file);
curl_setopt($curl, CURLOPT_VERBOSE, 0);
}
// obtain the HTTP response headers curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1); curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a'));
} else {
curl_setopt($curl, CURLOPT_VERBOSE, 0);
}
// Make the request // obtain the HTTP response headers
$response = curl_exec($curl); curl_setopt($curl, CURLOPT_HEADER, 1);
$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);
// debug HTTP response body // Make the request
if (Configuration::$debug) { $response = curl_exec($curl);
error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file); $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);
// Handle the response // debug HTTP response body
if ($response_info['http_code'] == 0) { if (Configuration::$debug) {
throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file);
} 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
* Build a JSON POST object if ($response_info['http_code'] == 0) {
*/ throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null);
protected function sanitizeForSerialization($data) } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) {
{ $data = json_decode($http_body);
if (is_scalar($data) || null === $data) { if (json_last_error() > 0) { // if response is a string
$sanitized = $data; $data = $http_body;
} else if ($data instanceof \DateTime) { }
$sanitized = $data->format(\DateTime::ISO8601); } else {
} else if (is_array($data)) { throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)",
foreach ($data as $property => $value) { $response_info['http_code'], $http_header, $http_body);
$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 query, by imploding comma-separated if it's an object. * the path, by url-encoding.
* If it's a string, pass through unchanged. It will be url-encoded * @param string $value a string which will be part of the path
* later. * @return string the serialized object
* @param object $object an object to be serialized to a string */
* @return string the serialized object public static function toPathValue($value) {
*/ 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 header. If it's a string, pass through unchanged * the query, by imploding comma-separated if it's an object.
* If it's a datetime object, format it in ISO8601 * If it's a string, pass through unchanged. It will be url-encoded
* @param string $value a string which will be part of the header * later.
* @return string the header string * @param object $object an object to be serialized to a string
*/ * @return string the serialized object
public static function toHeaderValue($value) { */
return 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 http body (form parameter). If it's a string, pass through unchanged * the header. 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 a string which will be part of the header
* @return string the form string * @return string the header string
*/ */
public static function toFormValue($value) { public static function toHeaderValue($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 parameter. 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 the value of the parameter * @param string $value the value of the form parameter
* @return string the header string * @return string the form string
*/ */
public static function toString($value) { public static function toFormValue($value) {
if ($value instanceof \DateTime) { // datetime in ISO8601 format return self::toString($value);
return $value->format(\DateTime::ISO8601); }
}
else {
return $value;
}
}
/** /**
* Deserialize a JSON string into an object * Take value and turn it into a string suitable for inclusion in
* * the parameter. If it's a string, pass through unchanged
* @param object $object object or primitive to be deserialized * If it's a datetime object, format it in ISO8601
* @param string $class class name is passed as a string * @param string $value the value of the parameter
* @return object an instance of $class * @return string the header string
*/ */
public static function deserialize($data, $class) public static function toString($value) {
{ if ($value instanceof \DateTime) { // datetime in ISO8601 format
if (null === $data) { return $value->format(\DateTime::ISO8601);
$deserialized = null; }
} elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] else {
$inner = substr($class, 4, -1); return $value;
$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 content type based on an array of content-type provided * return the header 'Accept' based on an array of Accept provided
* *
* @param array[string] content_type_array Array fo content-type * @param array[string] $accept Array of header
* @return string Content-Type (e.g. application/json) * @return string Accept (e.g. application/json)
*/ */
public static function selectHeaderContentType($content_type) { public static function selectHeaderAccept($accept) {
if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) {
return 'application/json'; return NULL;
} elseif (preg_grep("/application\/json/i", $content_type)) { } elseif (preg_grep("/application\/json/i", $accept)) {
return 'application/json'; return 'application/json';
} else { } else {
return implode(',', $content_type); return implode(',', $accept);
} }
} }
/*
* 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,515 +29,506 @@ 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
/**
* get the API client
*/
public function getApiClient() {
return $this->apiClient;
}
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
/**
* updatePet
*
* Update an existing pet
*
* @param Pet $body Pet object that needs to be added to the store (required)
* @return void
*/
public function updatePet($body) {
// parse inputs
$resourcePath = "/pet";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "PUT";
$httpBody = '';
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
} }
} $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml'));
private $apiClient; // instance of the ApiClient
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
/** // for model (json/xml)
* get the API client if (isset($_tempBody)) {
*/ $httpBody = $_tempBody; // $_tempBody is the method argument, if present
public function getApiClient() { } else if (count($formParams) > 0) {
return $this->apiClient; // for HTTP post (form)
} $httpBody = $formParams;
}
/** // authentication setting, if any
* set the API client $authSettings = array('petstore_auth');
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
// make the API Call
/** $response = $this->apiClient->callAPI($resourcePath, $method,
* updatePet $queryParams, $httpBody,
* $headerParams, $authSettings);
* Update an existing pet
*
* @param Pet $body Pet object that needs to be added to the store (required)
* @return void
*/
public function updatePet($body) {
// parse inputs
$resourcePath = "/pet"; }
$resourcePath = str_replace("{format}", "json", $resourcePath); /**
$method = "PUT"; * addPet
$httpBody = ''; *
$queryParams = array(); * Add a new pet to the store
$headerParams = array(); *
$formParams = array(); * @param Pet $body Pet object that needs to be added to the store (required)
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); * @return void
if (!is_null($_header_accept)) { */
$headerParams['Accept'] = $_header_accept; public function addPet($body) {
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml'));
// parse inputs
$resourcePath = "/pet";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "POST";
// body params $httpBody = '';
$_tempBody = null; $queryParams = array();
if (isset($body)) { $headerParams = array();
$_tempBody = $body; $formParams = array();
} $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml'));
// for model (json/xml)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form) // body params
$httpBody = $formParams; $_tempBody = null;
} if (isset($body)) {
$_tempBody = $body;
}
// authentication setting, if any // for model (json/xml)
$authSettings = array('petstore_auth'); if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
// make the API Call // authentication setting, if any
$response = $this->apiClient->callAPI($resourcePath, $method, $authSettings = array('petstore_auth');
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
} $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
/** $headerParams, $authSettings);
* addPet
*
* Add a new pet to the store
*
* @param Pet $body Pet object that needs to be added to the store (required)
* @return void
*/
public function addPet($body) {
// parse inputs
$resourcePath = "/pet"; }
$resourcePath = str_replace("{format}", "json", $resourcePath); /**
$method = "POST"; * findPetsByStatus
$httpBody = ''; *
$queryParams = array(); * Finds Pets by status
$headerParams = array(); *
$formParams = array(); * @param array[string] $status Status values that need to be considered for filter (required)
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); * @return array[Pet]
if (!is_null($_header_accept)) { */
$headerParams['Accept'] = $_header_accept; public function findPetsByStatus($status) {
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml'));
// parse inputs
$resourcePath = "/pet/findByStatus";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "GET";
// body params $httpBody = '';
$_tempBody = null; $queryParams = array();
if (isset($body)) { $headerParams = array();
$_tempBody = $body; $formParams = array();
} $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// for model (json/xml) // query params
if (isset($_tempBody)) { if($status !== null) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $queryParams['status'] = $this->apiClient->toQueryValue($status);
} else if (count($formParams) > 0) { }
// for HTTP post (form)
$httpBody = $formParams;
}
// authentication setting, if any // for model (json/xml)
$authSettings = array('petstore_auth'); if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
// make the API Call // authentication setting, if any
$response = $this->apiClient->callAPI($resourcePath, $method, $authSettings = array('petstore_auth');
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
} $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
/** $headerParams, $authSettings);
* findPetsByStatus
*
* Finds Pets by status
*
* @param array[string] $status Status values that need to be considered for filter (required)
* @return array[Pet]
*/
public function findPetsByStatus($status) {
// parse inputs if(! $response) {
$resourcePath = "/pet/findByStatus"; return null;
$resourcePath = str_replace("{format}", "json", $resourcePath); }
$method = "GET";
$httpBody = '';
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// query params $responseObject = $this->apiClient->deserialize($response,'array[Pet]');
if($status !== null) { return $responseObject;
$queryParams['status'] = $this->apiClient->toQueryValue($status); }
} /**
* findPetsByTags
*
* Finds Pets by tags
*
* @param array[string] $tags Tags to filter by (required)
* @return array[Pet]
*/
public function findPetsByTags($tags) {
// for model (json/xml) // parse inputs
if (isset($_tempBody)) { $resourcePath = "/pet/findByTags";
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $resourcePath = str_replace("{format}", "json", $resourcePath);
} else if (count($formParams) > 0) { $method = "GET";
// for HTTP post (form) $httpBody = '';
$httpBody = $formParams; $queryParams = array();
} $headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// authentication setting, if any // query params
$authSettings = array('petstore_auth'); if($tags !== null) {
$queryParams['tags'] = $this->apiClient->toQueryValue($tags);
}
// make the API Call // for model (json/xml)
$response = $this->apiClient->callAPI($resourcePath, $method, if (isset($_tempBody)) {
$queryParams, $httpBody, $httpBody = $_tempBody; // $_tempBody is the method argument, if present
$headerParams, $authSettings); } else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
if(! $response) { // authentication setting, if any
return null; $authSettings = array('petstore_auth');
}
$responseObject = $this->apiClient->deserialize($response,'array[Pet]'); // make the API Call
return $responseObject; $response = $this->apiClient->callAPI($resourcePath, $method,
} $queryParams, $httpBody,
$headerParams, $authSettings);
/**
* findPetsByTags
*
* Finds Pets by tags
*
* @param array[string] $tags Tags to filter by (required)
* @return array[Pet]
*/
public function findPetsByTags($tags) {
// parse inputs if(! $response) {
$resourcePath = "/pet/findByTags"; return null;
$resourcePath = str_replace("{format}", "json", $resourcePath); }
$method = "GET";
$httpBody = '';
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// query params $responseObject = $this->apiClient->deserialize($response,'array[Pet]');
if($tags !== null) { return $responseObject;
$queryParams['tags'] = $this->apiClient->toQueryValue($tags); }
} /**
* getPetById
*
* Find pet by ID
*
* @param int $pet_id ID of pet that needs to be fetched (required)
// for model (json/xml) * @return Pet
if (isset($_tempBody)) { */
$httpBody = $_tempBody; // $_tempBody is the method argument, if present public function getPetById($pet_id) {
} else if (count($formParams) > 0) {
// for HTTP post (form) // verify the required parameter 'pet_id' is set
$httpBody = $formParams; if ($pet_id === null) {
}
// authentication setting, if any
$authSettings = array('petstore_auth');
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
if(! $response) {
return null;
}
$responseObject = $this->apiClient->deserialize($response,'array[Pet]');
return $responseObject;
}
/**
* getPetById
*
* Find pet by ID
*
* @param int $pet_id ID of pet that needs to be fetched (required)
* @return Pet
*/
public function getPetById($pet_id) {
// verify the required parameter 'pet_id' is set
if ($pet_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById');
} }
// parse inputs // parse inputs
$resourcePath = "/pet/{petId}"; $resourcePath = "/pet/{petId}";
$resourcePath = str_replace("{format}", "json", $resourcePath); $resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "GET"; $method = "GET";
$httpBody = ''; $httpBody = '';
$queryParams = array(); $queryParams = array();
$headerParams = array(); $headerParams = array();
$formParams = array(); $formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) { if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept; $headerParams['Accept'] = $_header_accept;
} }
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// path params // path params
if($pet_id !== null) { if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}", $resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath); $this->apiClient->toPathValue($pet_id), $resourcePath);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) { } else if (count($formParams) > 0) {
// for HTTP post (form) // for HTTP post (form)
$httpBody = $formParams; $httpBody = $formParams;
} }
// authentication setting, if any // authentication setting, if any
$authSettings = array('api_key', 'petstore_auth'); $authSettings = array('api_key', 'petstore_auth');
// make the API Call // make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method, $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody, $queryParams, $httpBody,
$headerParams, $authSettings); $headerParams, $authSettings);
if(! $response) { if(! $response) {
return null; return null;
} }
$responseObject = $this->apiClient->deserialize($response,'Pet'); $responseObject = $this->apiClient->deserialize($response,'Pet');
return $responseObject; return $responseObject;
} }
/**
/** * updatePetWithForm
* updatePetWithForm *
* * Updates a pet in the store with form data
* Updates a pet in the store with form data *
* * @param string $pet_id ID of pet that needs to be updated (required)
* @param string $pet_id ID of pet that needs to be updated (required) * @param string $name Updated name of the pet (required)
* @param string $name Updated name of the pet (required) * @param string $status Updated status of the pet (required)
* @param string $status Updated status of the pet (required) * @return void
* @return void */
*/ public function updatePetWithForm($pet_id, $name, $status) {
public function updatePetWithForm($pet_id, $name, $status) {
// verify the required parameter 'pet_id' is set
// verify the required parameter 'pet_id' is set if ($pet_id === null) {
if ($pet_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm');
} }
// parse inputs // parse inputs
$resourcePath = "/pet/{petId}"; $resourcePath = "/pet/{petId}";
$resourcePath = str_replace("{format}", "json", $resourcePath); $resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "POST"; $method = "POST";
$httpBody = ''; $httpBody = '';
$queryParams = array(); $queryParams = array();
$headerParams = array(); $headerParams = array();
$formParams = array(); $formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) { if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept; $headerParams['Accept'] = $_header_accept;
} }
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded')); $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded'));
// path params // path params
if($pet_id !== null) { if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}", $resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath); $this->apiClient->toPathValue($pet_id), $resourcePath);
} }
// form params // form params
if ($name !== null) { if ($name !== null) {
$formParams['name'] = $this->apiClient->toFormValue($name); $formParams['name'] = $this->apiClient->toFormValue($name);
}// form params }// form params
if ($status !== null) { if ($status !== null) {
$formParams['status'] = $this->apiClient->toFormValue($status); $formParams['status'] = $this->apiClient->toFormValue($status);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) { } else if (count($formParams) > 0) {
// for HTTP post (form) // for HTTP post (form)
$httpBody = $formParams; $httpBody = $formParams;
} }
// authentication setting, if any // authentication setting, if any
$authSettings = array('petstore_auth'); $authSettings = array('petstore_auth');
// make the API Call // make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method, $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody, $queryParams, $httpBody,
$headerParams, $authSettings); $headerParams, $authSettings);
} }
/**
/** * deletePet
* deletePet *
* * Deletes a pet
* Deletes a pet *
* * @param string $api_key (required)
* @param string $api_key (required) * @param int $pet_id Pet id to delete (required)
* @param int $pet_id Pet id to delete (required) * @return void
* @return void */
*/ public function deletePet($api_key, $pet_id) {
public function deletePet($api_key, $pet_id) {
// verify the required parameter 'pet_id' is set
// verify the required parameter 'pet_id' is set if ($pet_id === null) {
if ($pet_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet');
} }
// parse inputs // parse inputs
$resourcePath = "/pet/{petId}"; $resourcePath = "/pet/{petId}";
$resourcePath = str_replace("{format}", "json", $resourcePath); $resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "DELETE"; $method = "DELETE";
$httpBody = ''; $httpBody = '';
$queryParams = array(); $queryParams = array();
$headerParams = array(); $headerParams = array();
$formParams = array(); $formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) { if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept; $headerParams['Accept'] = $_header_accept;
} }
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// header params // header params
if($api_key !== null) { if($api_key !== null) {
$headerParams['api_key'] = $this->apiClient->toHeaderValue($api_key); $headerParams['api_key'] = $this->apiClient->toHeaderValue($api_key);
} }
// path params // path params
if($pet_id !== null) { if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}", $resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath); $this->apiClient->toPathValue($pet_id), $resourcePath);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) { } else if (count($formParams) > 0) {
// for HTTP post (form) // for HTTP post (form)
$httpBody = $formParams; $httpBody = $formParams;
} }
// authentication setting, if any // authentication setting, if any
$authSettings = array('petstore_auth'); $authSettings = array('petstore_auth');
// make the API Call // make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method, $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody, $queryParams, $httpBody,
$headerParams, $authSettings); $headerParams, $authSettings);
} }
/**
/** * uploadFile
* uploadFile *
* * uploads an image
* uploads an image *
* * @param int $pet_id ID of pet to update (required)
* @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (required)
* @param string $additional_metadata Additional data to pass to server (required) * @param string $file file to upload (required)
* @param string $file file to upload (required) * @return void
* @return void */
*/ public function uploadFile($pet_id, $additional_metadata, $file) {
public function uploadFile($pet_id, $additional_metadata, $file) {
// verify the required parameter 'pet_id' is set
// verify the required parameter 'pet_id' is set if ($pet_id === null) {
if ($pet_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile');
} }
// parse inputs // parse inputs
$resourcePath = "/pet/{petId}/uploadImage"; $resourcePath = "/pet/{petId}/uploadImage";
$resourcePath = str_replace("{format}", "json", $resourcePath); $resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "POST"; $method = "POST";
$httpBody = ''; $httpBody = '';
$queryParams = array(); $queryParams = array();
$headerParams = array(); $headerParams = array();
$formParams = array(); $formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) { if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept; $headerParams['Accept'] = $_header_accept;
} }
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data')); $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data'));
// path params // path params
if($pet_id !== null) { if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}", $resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath); $this->apiClient->toPathValue($pet_id), $resourcePath);
} }
// form params // form params
if ($additional_metadata !== null) { if ($additional_metadata !== null) {
$formParams['additionalMetadata'] = $this->apiClient->toFormValue($additional_metadata); $formParams['additionalMetadata'] = $this->apiClient->toFormValue($additional_metadata);
}// form params }// form params
if ($file !== null) { if ($file !== null) {
$formParams['file'] = '@' . $this->apiClient->toFormValue($file); $formParams['file'] = '@' . $this->apiClient->toFormValue($file);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) { } else if (count($formParams) > 0) {
// for HTTP post (form) // for HTTP post (form)
$httpBody = $formParams; $httpBody = $formParams;
} }
// authentication setting, if any // authentication setting, if any
$authSettings = array('petstore_auth'); $authSettings = array('petstore_auth');
// make the API Call // make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method, $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody, $queryParams, $httpBody,
$headerParams, $authSettings); $headerParams, $authSettings);
} }
} }

View File

@@ -29,266 +29,261 @@ 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
/**
* get the API client
*/
public function getApiClient() {
return $this->apiClient;
}
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
/**
* getInventory
*
* Returns pet inventories by status
*
* @return map[string,int]
*/
public function getInventory() {
// parse inputs
$resourcePath = "/store/inventory";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "GET";
$httpBody = '';
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
} }
} $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
private $apiClient; // instance of the ApiClient
/** // for model (json/xml)
* get the API client if (isset($_tempBody)) {
*/ $httpBody = $_tempBody; // $_tempBody is the method argument, if present
public function getApiClient() { } else if (count($formParams) > 0) {
return $this->apiClient; // for HTTP post (form)
} $httpBody = $formParams;
}
/** // authentication setting, if any
* set the API client $authSettings = array('api_key');
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
// make the API Call
/** $response = $this->apiClient->callAPI($resourcePath, $method,
* getInventory $queryParams, $httpBody,
* $headerParams, $authSettings);
* Returns pet inventories by status
*
* @return map[string,int]
*/
public function getInventory() {
// parse inputs if(! $response) {
$resourcePath = "/store/inventory"; return null;
$resourcePath = str_replace("{format}", "json", $resourcePath); }
$method = "GET";
$httpBody = '';
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
$responseObject = $this->apiClient->deserialize($response,'map[string,int]');
return $responseObject;
}
/**
* placeOrder
*
* Place an order for a pet
*
* @param Order $body order placed for purchasing the pet (required)
* @return Order
*/
public function placeOrder($body) {
// for model (json/xml) // parse inputs
if (isset($_tempBody)) { $resourcePath = "/store/order";
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $resourcePath = str_replace("{format}", "json", $resourcePath);
} else if (count($formParams) > 0) { $method = "POST";
// for HTTP post (form) $httpBody = '';
$httpBody = $formParams; $queryParams = array();
} $headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// authentication setting, if any
$authSettings = array('api_key');
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// make the API Call // for model (json/xml)
$response = $this->apiClient->callAPI($resourcePath, $method, if (isset($_tempBody)) {
$queryParams, $httpBody, $httpBody = $_tempBody; // $_tempBody is the method argument, if present
$headerParams, $authSettings); } else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
if(! $response) { // authentication setting, if any
return null; $authSettings = array();
}
$responseObject = $this->apiClient->deserialize($response,'map[string,int]'); // make the API Call
return $responseObject; $response = $this->apiClient->callAPI($resourcePath, $method,
} $queryParams, $httpBody,
$headerParams, $authSettings);
/**
* placeOrder
*
* Place an order for a pet
*
* @param Order $body order placed for purchasing the pet (required)
* @return Order
*/
public function placeOrder($body) {
// parse inputs if(! $response) {
$resourcePath = "/store/order"; return null;
$resourcePath = str_replace("{format}", "json", $resourcePath); }
$method = "POST";
$httpBody = '';
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
$responseObject = $this->apiClient->deserialize($response,'Order');
return $responseObject;
}
/**
// body params * getOrderById
$_tempBody = null; *
if (isset($body)) { * Find purchase order by ID
$_tempBody = $body; *
} * @param string $order_id ID of pet that needs to be fetched (required)
* @return Order
// for model (json/xml) */
if (isset($_tempBody)) { public function getOrderById($order_id) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) { // verify the required parameter 'order_id' is set
// for HTTP post (form) if ($order_id === null) {
$httpBody = $formParams;
}
// authentication setting, if any
$authSettings = array();
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
if(! $response) {
return null;
}
$responseObject = $this->apiClient->deserialize($response,'Order');
return $responseObject;
}
/**
* getOrderById
*
* Find purchase order by ID
*
* @param string $order_id ID of pet that needs to be fetched (required)
* @return Order
*/
public function getOrderById($order_id) {
// verify the required parameter 'order_id' is set
if ($order_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById');
} }
// parse inputs // parse inputs
$resourcePath = "/store/order/{orderId}"; $resourcePath = "/store/order/{orderId}";
$resourcePath = str_replace("{format}", "json", $resourcePath); $resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "GET"; $method = "GET";
$httpBody = ''; $httpBody = '';
$queryParams = array(); $queryParams = array();
$headerParams = array(); $headerParams = array();
$formParams = array(); $formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) { if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept; $headerParams['Accept'] = $_header_accept;
} }
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// path params // path params
if($order_id !== null) { if($order_id !== null) {
$resourcePath = str_replace("{" . "orderId" . "}", $resourcePath = str_replace("{" . "orderId" . "}",
$this->apiClient->toPathValue($order_id), $resourcePath); $this->apiClient->toPathValue($order_id), $resourcePath);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) { } else if (count($formParams) > 0) {
// for HTTP post (form) // for HTTP post (form)
$httpBody = $formParams; $httpBody = $formParams;
} }
// authentication setting, if any // authentication setting, if any
$authSettings = array(); $authSettings = array();
// make the API Call // make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method, $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody, $queryParams, $httpBody,
$headerParams, $authSettings); $headerParams, $authSettings);
if(! $response) { if(! $response) {
return null; return null;
} }
$responseObject = $this->apiClient->deserialize($response,'Order'); $responseObject = $this->apiClient->deserialize($response,'Order');
return $responseObject; return $responseObject;
} }
/**
/** * deleteOrder
* deleteOrder *
* * Delete purchase order by ID
* Delete purchase order by ID *
* * @param string $order_id ID of the order that needs to be deleted (required)
* @param string $order_id ID of the order that needs to be deleted (required) * @return void
* @return void */
*/ public function deleteOrder($order_id) {
public function deleteOrder($order_id) {
// verify the required parameter 'order_id' is set
// verify the required parameter 'order_id' is set if ($order_id === null) {
if ($order_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder');
} }
// parse inputs // parse inputs
$resourcePath = "/store/order/{orderId}"; $resourcePath = "/store/order/{orderId}";
$resourcePath = str_replace("{format}", "json", $resourcePath); $resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "DELETE"; $method = "DELETE";
$httpBody = ''; $httpBody = '';
$queryParams = array(); $queryParams = array();
$headerParams = array(); $headerParams = array();
$formParams = array(); $formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) { if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept; $headerParams['Accept'] = $_header_accept;
} }
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// path params // path params
if($order_id !== null) { if($order_id !== null) {
$resourcePath = str_replace("{" . "orderId" . "}", $resourcePath = str_replace("{" . "orderId" . "}",
$this->apiClient->toPathValue($order_id), $resourcePath); $this->apiClient->toPathValue($order_id), $resourcePath);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) { } else if (count($formParams) > 0) {
// for HTTP post (form) // for HTTP post (form)
$httpBody = $formParams; $httpBody = $formParams;
} }
// authentication setting, if any // authentication setting, if any
$authSettings = array(); $authSettings = array();
// make the API Call // make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method, $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody, $queryParams, $httpBody,
$headerParams, $authSettings); $headerParams, $authSettings);
} }
} }

View File

@@ -29,490 +29,481 @@ 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
/**
* get the API client
*/
public function getApiClient() {
return $this->apiClient;
}
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
/**
* createUser
*
* Create user
*
* @param User $body Created user object (required)
* @return void
*/
public function createUser($body) {
// parse inputs
$resourcePath = "/user";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "POST";
$httpBody = '';
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
} }
} $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
private $apiClient; // instance of the ApiClient
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
/** // for model (json/xml)
* get the API client if (isset($_tempBody)) {
*/ $httpBody = $_tempBody; // $_tempBody is the method argument, if present
public function getApiClient() { } else if (count($formParams) > 0) {
return $this->apiClient; // for HTTP post (form)
} $httpBody = $formParams;
}
/** // authentication setting, if any
* set the API client $authSettings = array();
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
// make the API Call
/** $response = $this->apiClient->callAPI($resourcePath, $method,
* createUser $queryParams, $httpBody,
* $headerParams, $authSettings);
* Create user
*
* @param User $body Created user object (required)
* @return void
*/
public function createUser($body) {
// parse inputs
$resourcePath = "/user"; }
$resourcePath = str_replace("{format}", "json", $resourcePath); /**
$method = "POST"; * createUsersWithArrayInput
$httpBody = ''; *
$queryParams = array(); * Creates list of users with given input array
$headerParams = array(); *
$formParams = array(); * @param array[User] $body List of user object (required)
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); * @return void
if (!is_null($_header_accept)) { */
$headerParams['Accept'] = $_header_accept; public function createUsersWithArrayInput($body) {
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// parse inputs
$resourcePath = "/user/createWithArray";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "POST";
// body params $httpBody = '';
$_tempBody = null; $queryParams = array();
if (isset($body)) { $headerParams = array();
$_tempBody = $body; $formParams = array();
} $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// for model (json/xml)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form) // body params
$httpBody = $formParams; $_tempBody = null;
} if (isset($body)) {
$_tempBody = $body;
}
// authentication setting, if any // for model (json/xml)
$authSettings = array(); if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
// make the API Call // authentication setting, if any
$response = $this->apiClient->callAPI($resourcePath, $method, $authSettings = array();
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
} $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
/** $headerParams, $authSettings);
* createUsersWithArrayInput
*
* Creates list of users with given input array
*
* @param array[User] $body List of user object (required)
* @return void
*/
public function createUsersWithArrayInput($body) {
// parse inputs
$resourcePath = "/user/createWithArray"; }
$resourcePath = str_replace("{format}", "json", $resourcePath); /**
$method = "POST"; * createUsersWithListInput
$httpBody = ''; *
$queryParams = array(); * Creates list of users with given input array
$headerParams = array(); *
$formParams = array(); * @param array[User] $body List of user object (required)
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); * @return void
if (!is_null($_header_accept)) { */
$headerParams['Accept'] = $_header_accept; public function createUsersWithListInput($body) {
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// parse inputs
$resourcePath = "/user/createWithList";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "POST";
// body params $httpBody = '';
$_tempBody = null; $queryParams = array();
if (isset($body)) { $headerParams = array();
$_tempBody = $body; $formParams = array();
} $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// for model (json/xml)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form) // body params
$httpBody = $formParams; $_tempBody = null;
} if (isset($body)) {
$_tempBody = $body;
}
// authentication setting, if any // for model (json/xml)
$authSettings = array(); if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
// make the API Call // authentication setting, if any
$response = $this->apiClient->callAPI($resourcePath, $method, $authSettings = array();
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
} $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
/** $headerParams, $authSettings);
* createUsersWithListInput
*
* Creates list of users with given input array
*
* @param array[User] $body List of user object (required)
* @return void
*/
public function createUsersWithListInput($body) {
// parse inputs
$resourcePath = "/user/createWithList"; }
$resourcePath = str_replace("{format}", "json", $resourcePath); /**
$method = "POST"; * loginUser
$httpBody = ''; *
$queryParams = array(); * Logs user into the system
$headerParams = array(); *
$formParams = array(); * @param string $username The user name for login (required)
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); * @param string $password The password for login in clear text (required)
if (!is_null($_header_accept)) { * @return string
$headerParams['Accept'] = $_header_accept; */
} public function loginUser($username, $password) {
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// parse inputs
$resourcePath = "/user/login";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "GET";
// body params $httpBody = '';
$_tempBody = null; $queryParams = array();
if (isset($body)) { $headerParams = array();
$_tempBody = $body; $formParams = array();
} $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// for model (json/xml) // query params
if (isset($_tempBody)) { if($username !== null) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $queryParams['username'] = $this->apiClient->toQueryValue($username);
} else if (count($formParams) > 0) { }// query params
// for HTTP post (form) if($password !== null) {
$httpBody = $formParams; $queryParams['password'] = $this->apiClient->toQueryValue($password);
} }
// authentication setting, if any // for model (json/xml)
$authSettings = array(); if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
// make the API Call // authentication setting, if any
$response = $this->apiClient->callAPI($resourcePath, $method, $authSettings = array();
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
} $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
/** $headerParams, $authSettings);
* loginUser
*
* Logs user into the system
*
* @param string $username The user name for login (required)
* @param string $password The password for login in clear text (required)
* @return string
*/
public function loginUser($username, $password) {
// parse inputs if(! $response) {
$resourcePath = "/user/login"; return null;
$resourcePath = str_replace("{format}", "json", $resourcePath); }
$method = "GET";
$httpBody = '';
$queryParams = array();
$headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// query params $responseObject = $this->apiClient->deserialize($response,'string');
if($username !== null) { return $responseObject;
$queryParams['username'] = $this->apiClient->toQueryValue($username); }
}// query params /**
if($password !== null) { * logoutUser
$queryParams['password'] = $this->apiClient->toQueryValue($password); *
} * Logs out current logged in user session
*
* @return void
*/
public function logoutUser() {
// for model (json/xml) // parse inputs
if (isset($_tempBody)) { $resourcePath = "/user/logout";
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $resourcePath = str_replace("{format}", "json", $resourcePath);
} else if (count($formParams) > 0) { $method = "GET";
// for HTTP post (form) $httpBody = '';
$httpBody = $formParams; $queryParams = array();
} $headerParams = array();
$formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept;
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// authentication setting, if any
$authSettings = array();
// make the API Call // for model (json/xml)
$response = $this->apiClient->callAPI($resourcePath, $method, if (isset($_tempBody)) {
$queryParams, $httpBody, $httpBody = $_tempBody; // $_tempBody is the method argument, if present
$headerParams, $authSettings); } else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
if(! $response) { // authentication setting, if any
return null; $authSettings = array();
}
$responseObject = $this->apiClient->deserialize($response,'string'); // make the API Call
return $responseObject; $response = $this->apiClient->callAPI($resourcePath, $method,
} $queryParams, $httpBody,
$headerParams, $authSettings);
/**
* logoutUser
*
* Logs out current logged in user session
*
* @return void
*/
public function logoutUser() {
// parse inputs
$resourcePath = "/user/logout"; }
$resourcePath = str_replace("{format}", "json", $resourcePath); /**
$method = "GET"; * getUserByName
$httpBody = ''; *
$queryParams = array(); * Get user by user name
$headerParams = array(); *
$formParams = array(); * @param string $username The name that needs to be fetched. Use user1 for testing. (required)
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); * @return User
if (!is_null($_header_accept)) { */
$headerParams['Accept'] = $_header_accept; public function getUserByName($username) {
}
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // verify the required parameter 'username' is set
if ($username === null) {
// for model (json/xml)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
// authentication setting, if any
$authSettings = array();
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
}
/**
* getUserByName
*
* Get user by user name
*
* @param string $username The name that needs to be fetched. Use user1 for testing. (required)
* @return User
*/
public function getUserByName($username) {
// verify the required parameter 'username' is set
if ($username === null) {
throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName');
} }
// parse inputs // parse inputs
$resourcePath = "/user/{username}"; $resourcePath = "/user/{username}";
$resourcePath = str_replace("{format}", "json", $resourcePath); $resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "GET"; $method = "GET";
$httpBody = ''; $httpBody = '';
$queryParams = array(); $queryParams = array();
$headerParams = array(); $headerParams = array();
$formParams = array(); $formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) { if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept; $headerParams['Accept'] = $_header_accept;
} }
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// path params // path params
if($username !== null) { if($username !== null) {
$resourcePath = str_replace("{" . "username" . "}", $resourcePath = str_replace("{" . "username" . "}",
$this->apiClient->toPathValue($username), $resourcePath); $this->apiClient->toPathValue($username), $resourcePath);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) { } else if (count($formParams) > 0) {
// for HTTP post (form) // for HTTP post (form)
$httpBody = $formParams; $httpBody = $formParams;
} }
// authentication setting, if any // authentication setting, if any
$authSettings = array(); $authSettings = array();
// make the API Call // make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method, $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody, $queryParams, $httpBody,
$headerParams, $authSettings); $headerParams, $authSettings);
if(! $response) { if(! $response) {
return null; return null;
} }
$responseObject = $this->apiClient->deserialize($response,'User'); $responseObject = $this->apiClient->deserialize($response,'User');
return $responseObject; return $responseObject;
} }
/**
/** * updateUser
* updateUser *
* * Updated user
* Updated user *
* * @param string $username name that need to be deleted (required)
* @param string $username name that need to be deleted (required) * @param User $body Updated user object (required)
* @param User $body Updated user object (required) * @return void
* @return void */
*/ public function updateUser($username, $body) {
public function updateUser($username, $body) {
// verify the required parameter 'username' is set
// verify the required parameter 'username' is set if ($username === null) {
if ($username === null) {
throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser'); throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser');
} }
// parse inputs // parse inputs
$resourcePath = "/user/{username}"; $resourcePath = "/user/{username}";
$resourcePath = str_replace("{format}", "json", $resourcePath); $resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "PUT"; $method = "PUT";
$httpBody = ''; $httpBody = '';
$queryParams = array(); $queryParams = array();
$headerParams = array(); $headerParams = array();
$formParams = array(); $formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) { if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept; $headerParams['Accept'] = $_header_accept;
} }
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// path params // path params
if($username !== null) { if($username !== null) {
$resourcePath = str_replace("{" . "username" . "}", $resourcePath = str_replace("{" . "username" . "}",
$this->apiClient->toPathValue($username), $resourcePath); $this->apiClient->toPathValue($username), $resourcePath);
} }
// body params // body params
$_tempBody = null; $_tempBody = null;
if (isset($body)) { if (isset($body)) {
$_tempBody = $body; $_tempBody = $body;
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) { } else if (count($formParams) > 0) {
// for HTTP post (form) // for HTTP post (form)
$httpBody = $formParams; $httpBody = $formParams;
} }
// authentication setting, if any // authentication setting, if any
$authSettings = array(); $authSettings = array();
// make the API Call // make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method, $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody, $queryParams, $httpBody,
$headerParams, $authSettings); $headerParams, $authSettings);
} }
/**
/** * deleteUser
* deleteUser *
* * Delete user
* Delete user *
* * @param string $username The name that needs to be deleted (required)
* @param string $username The name that needs to be deleted (required) * @return void
* @return void */
*/ public function deleteUser($username) {
public function deleteUser($username) {
// verify the required parameter 'username' is set
// verify the required parameter 'username' is set if ($username === null) {
if ($username === null) {
throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser');
} }
// parse inputs // parse inputs
$resourcePath = "/user/{username}"; $resourcePath = "/user/{username}";
$resourcePath = str_replace("{format}", "json", $resourcePath); $resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "DELETE"; $method = "DELETE";
$httpBody = ''; $httpBody = '';
$queryParams = array(); $queryParams = array();
$headerParams = array(); $headerParams = array();
$formParams = array(); $formParams = array();
$_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml'));
if (!is_null($_header_accept)) { if (!is_null($_header_accept)) {
$headerParams['Accept'] = $_header_accept; $headerParams['Accept'] = $_header_accept;
} }
$headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array());
// path params // path params
if($username !== null) { if($username !== null) {
$resourcePath = str_replace("{" . "username" . "}", $resourcePath = str_replace("{" . "username" . "}",
$this->apiClient->toPathValue($username), $resourcePath); $this->apiClient->toPathValue($username), $resourcePath);
} }
// for model (json/xml) // for model (json/xml)
if (isset($_tempBody)) { if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present $httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) { } else if (count($formParams) > 0) {
// for HTTP post (form) // for HTTP post (form)
$httpBody = $formParams; $httpBody = $formParams;
} }
// authentication setting, if any // authentication setting, if any
$authSettings = array(); $authSettings = array();
// make the API Call // make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method, $response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody, $queryParams, $httpBody,
$headerParams, $authSettings); $headerParams, $authSettings);
} }
} }

View File

@@ -15,6 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
/** /**
* *
* *
@@ -29,36 +30,37 @@ use \ArrayAccess;
class Category implements ArrayAccess { class Category implements ArrayAccess {
static $swaggerTypes = array( static $swaggerTypes = array(
'id' => 'int', 'id' => 'int',
'name' => 'string' 'name' => 'string'
); );
static $attributeMap = array( static $attributeMap = array(
'id' => 'id', 'id' => 'id',
'name' => 'name' 'name' => 'name'
); );
public $id; /* int */ public $id; /* int */
public $name; /* string */ public $name; /* string */
public function __construct(array $data = null) { public function __construct(array $data = null) {
$this->id = $data["id"]; $this->id = $data["id"];
$this->name = $data["name"]; $this->name = $data["name"];
} }
public function offsetExists($offset) { public function offsetExists($offset) {
return isset($this->$offset); return isset($this->$offset);
} }
public function offsetGet($offset) { public function offsetGet($offset) {
return $this->$offset; return $this->$offset;
} }
public function offsetSet($offset, $value) { public function offsetSet($offset, $value) {
$this->$offset = $value; $this->$offset = $value;
} }
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.
*/ */
/** /**
* *
* *
@@ -29,55 +30,56 @@ use \ArrayAccess;
class Order implements ArrayAccess { class Order implements ArrayAccess {
static $swaggerTypes = array( static $swaggerTypes = array(
'id' => 'int', 'id' => 'int',
'pet_id' => 'int', 'pet_id' => 'int',
'quantity' => 'int', 'quantity' => 'int',
'ship_date' => 'DateTime', 'ship_date' => 'DateTime',
'status' => 'string', 'status' => 'string',
'complete' => 'boolean' 'complete' => 'boolean'
); );
static $attributeMap = array( static $attributeMap = array(
'id' => 'id', 'id' => 'id',
'pet_id' => 'petId', 'pet_id' => 'petId',
'quantity' => 'quantity', 'quantity' => 'quantity',
'ship_date' => 'shipDate', 'ship_date' => 'shipDate',
'status' => 'status', 'status' => 'status',
'complete' => 'complete' 'complete' => 'complete'
); );
public $id; /* int */ public $id; /* int */
public $pet_id; /* int */ public $pet_id; /* int */
public $quantity; /* int */ public $quantity; /* int */
public $ship_date; /* DateTime */ public $ship_date; /* DateTime */
/** /**
* Order Status * Order Status
*/ */
public $status; /* string */ public $status; /* string */
public $complete; /* boolean */ public $complete; /* boolean */
public function __construct(array $data = null) { public function __construct(array $data = null) {
$this->id = $data["id"]; $this->id = $data["id"];
$this->pet_id = $data["pet_id"]; $this->pet_id = $data["pet_id"];
$this->quantity = $data["quantity"]; $this->quantity = $data["quantity"];
$this->ship_date = $data["ship_date"]; $this->ship_date = $data["ship_date"];
$this->status = $data["status"]; $this->status = $data["status"];
$this->complete = $data["complete"]; $this->complete = $data["complete"];
} }
public function offsetExists($offset) { public function offsetExists($offset) {
return isset($this->$offset); return isset($this->$offset);
} }
public function offsetGet($offset) { public function offsetGet($offset) {
return $this->$offset; return $this->$offset;
} }
public function offsetSet($offset, $value) { public function offsetSet($offset, $value) {
$this->$offset = $value; $this->$offset = $value;
} }
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.
*/ */
/** /**
* *
* *
@@ -29,55 +30,56 @@ use \ArrayAccess;
class Pet implements ArrayAccess { class Pet implements ArrayAccess {
static $swaggerTypes = array( static $swaggerTypes = array(
'id' => 'int', 'id' => 'int',
'category' => 'Category', 'category' => 'Category',
'name' => 'string', 'name' => 'string',
'photo_urls' => 'array[string]', 'photo_urls' => 'array[string]',
'tags' => 'array[Tag]', 'tags' => 'array[Tag]',
'status' => 'string' 'status' => 'string'
); );
static $attributeMap = array( static $attributeMap = array(
'id' => 'id', 'id' => 'id',
'category' => 'category', 'category' => 'category',
'name' => 'name', 'name' => 'name',
'photo_urls' => 'photoUrls', 'photo_urls' => 'photoUrls',
'tags' => 'tags', 'tags' => 'tags',
'status' => 'status' 'status' => 'status'
); );
public $id; /* int */ public $id; /* int */
public $category; /* Category */ public $category; /* Category */
public $name; /* string */ public $name; /* string */
public $photo_urls; /* array[string] */ public $photo_urls; /* array[string] */
public $tags; /* array[Tag] */ public $tags; /* array[Tag] */
/** /**
* pet status in the store * pet status in the store
*/ */
public $status; /* string */ public $status; /* string */
public function __construct(array $data = null) { public function __construct(array $data = null) {
$this->id = $data["id"]; $this->id = $data["id"];
$this->category = $data["category"]; $this->category = $data["category"];
$this->name = $data["name"]; $this->name = $data["name"];
$this->photo_urls = $data["photo_urls"]; $this->photo_urls = $data["photo_urls"];
$this->tags = $data["tags"]; $this->tags = $data["tags"];
$this->status = $data["status"]; $this->status = $data["status"];
} }
public function offsetExists($offset) { public function offsetExists($offset) {
return isset($this->$offset); return isset($this->$offset);
} }
public function offsetGet($offset) { public function offsetGet($offset) {
return $this->$offset; return $this->$offset;
} }
public function offsetSet($offset, $value) { public function offsetSet($offset, $value) {
$this->$offset = $value; $this->$offset = $value;
} }
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.
*/ */
/** /**
* *
* *
@@ -29,36 +30,37 @@ use \ArrayAccess;
class Tag implements ArrayAccess { class Tag implements ArrayAccess {
static $swaggerTypes = array( static $swaggerTypes = array(
'id' => 'int', 'id' => 'int',
'name' => 'string' 'name' => 'string'
); );
static $attributeMap = array( static $attributeMap = array(
'id' => 'id', 'id' => 'id',
'name' => 'name' 'name' => 'name'
); );
public $id; /* int */ public $id; /* int */
public $name; /* string */ public $name; /* string */
public function __construct(array $data = null) { public function __construct(array $data = null) {
$this->id = $data["id"]; $this->id = $data["id"];
$this->name = $data["name"]; $this->name = $data["name"];
} }
public function offsetExists($offset) { public function offsetExists($offset) {
return isset($this->$offset); return isset($this->$offset);
} }
public function offsetGet($offset) { public function offsetGet($offset) {
return $this->$offset; return $this->$offset;
} }
public function offsetSet($offset, $value) { public function offsetSet($offset, $value) {
$this->$offset = $value; $this->$offset = $value;
} }
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.
*/ */
/** /**
* *
* *
@@ -29,40 +30,40 @@ use \ArrayAccess;
class User implements ArrayAccess { class User implements ArrayAccess {
static $swaggerTypes = array( static $swaggerTypes = array(
'id' => 'int', 'id' => 'int',
'username' => 'string', 'username' => 'string',
'first_name' => 'string', 'first_name' => 'string',
'last_name' => 'string', 'last_name' => 'string',
'email' => 'string', 'email' => 'string',
'password' => 'string', 'password' => 'string',
'phone' => 'string', 'phone' => 'string',
'user_status' => 'int' 'user_status' => 'int'
); );
static $attributeMap = array( static $attributeMap = array(
'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' => 'userStatus' 'user_status' => 'userStatus'
); );
public $id; /* int */ public $id; /* int */
public $username; /* string */ public $username; /* string */
public $first_name; /* string */ public $first_name; /* string */
public $last_name; /* string */ public $last_name; /* string */
public $email; /* string */ public $email; /* string */
public $password; /* string */ public $password; /* string */
public $phone; /* string */ public $phone; /* string */
/** /**
* User Status * User Status
*/ */
public $user_status; /* int */ public $user_status; /* int */
public function __construct(array $data = null) { public function __construct(array $data = null) {
$this->id = $data["id"]; $this->id = $data["id"];
$this->username = $data["username"]; $this->username = $data["username"];
$this->first_name = $data["first_name"]; $this->first_name = $data["first_name"];
@@ -71,21 +72,22 @@ class User implements ArrayAccess {
$this->password = $data["password"]; $this->password = $data["password"];
$this->phone = $data["phone"]; $this->phone = $data["phone"];
$this->user_status = $data["user_status"]; $this->user_status = $data["user_status"];
} }
public function offsetExists($offset) { public function offsetExists($offset) {
return isset($this->$offset); return isset($this->$offset);
} }
public function offsetGet($offset) { public function offsetGet($offset) {
return $this->$offset; return $this->$offset;
} }
public function offsetSet($offset, $value) { public function offsetSet($offset, $value) {
$this->$offset = $value; $this->$offset = $value;
} }
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,18 +30,18 @@ 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:
self.api_client = api_client self.api_client = api_client
else: else:
if not configuration.api_client: if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2') configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client self.api_client = configuration.api_client
def update_pet(self, **kwargs):
def update_pet(self, **kwargs):
""" """
Update an existing pet Update an existing pet
@@ -55,9 +55,9 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method update_pet" % key) raise TypeError("Got an unexpected keyword argument '%s' to method update_pet" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/pet'.replace('{format}', 'json') resource_path = '/pet'.replace('{format}', 'json')
@@ -74,13 +74,13 @@ class PetApi(object):
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json', 'application/xml']) header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json', 'application/xml'])
@@ -89,10 +89,10 @@ class PetApi(object):
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)
def add_pet(self, **kwargs): def add_pet(self, **kwargs):
""" """
Add a new pet to the store Add a new pet to the store
@@ -106,9 +106,9 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method add_pet" % key) raise TypeError("Got an unexpected keyword argument '%s' to method add_pet" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/pet'.replace('{format}', 'json') resource_path = '/pet'.replace('{format}', 'json')
@@ -125,13 +125,13 @@ class PetApi(object):
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json', 'application/xml']) header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json', 'application/xml'])
@@ -140,10 +140,10 @@ class PetApi(object):
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)
def find_pets_by_status(self, **kwargs): def find_pets_by_status(self, **kwargs):
""" """
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
@@ -157,9 +157,9 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_status" % key) raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_status" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/pet/findByStatus'.replace('{format}', 'json') resource_path = '/pet/findByStatus'.replace('{format}', 'json')
@@ -169,7 +169,7 @@ class PetApi(object):
query_params = {} query_params = {}
if 'status' in params: if 'status' in params:
query_params['status'] = params['status'] query_params['status'] = params['status']
header_params = {} header_params = {}
@@ -182,7 +182,7 @@ class PetApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -191,12 +191,12 @@ class PetApi(object):
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response='list[Pet]', auth_settings=auth_settings) response='list[Pet]', auth_settings=auth_settings)
return response return response
def find_pets_by_tags(self, **kwargs): def find_pets_by_tags(self, **kwargs):
""" """
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.
@@ -210,9 +210,9 @@ class PetApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_tags" % key) raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_tags" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/pet/findByTags'.replace('{format}', 'json') resource_path = '/pet/findByTags'.replace('{format}', 'json')
@@ -222,7 +222,7 @@ class PetApi(object):
query_params = {} query_params = {}
if 'tags' in params: if 'tags' in params:
query_params['tags'] = params['tags'] query_params['tags'] = params['tags']
header_params = {} header_params = {}
@@ -235,7 +235,7 @@ class PetApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -244,12 +244,12 @@ class PetApi(object):
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response='list[Pet]', auth_settings=auth_settings) response='list[Pet]', auth_settings=auth_settings)
return response return response
def get_pet_by_id(self, pet_id, **kwargs): def get_pet_by_id(self, pet_id, **kwargs):
""" """
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
@@ -259,17 +259,17 @@ class PetApi(object):
:return: Pet :return: Pet
""" """
# verify the required parameter 'pet_id' is set # verify the required parameter 'pet_id' is set
if pet_id is None: if pet_id is None:
raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`")
all_params = ['pet_id'] all_params = ['pet_id']
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_pet_by_id" % key) raise TypeError("Got an unexpected keyword argument '%s' to method get_pet_by_id" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/pet/{petId}'.replace('{format}', 'json') resource_path = '/pet/{petId}'.replace('{format}', 'json')
@@ -277,8 +277,8 @@ class PetApi(object):
path_params = {} path_params = {}
if 'pet_id' in params: if 'pet_id' in params:
path_params['petId'] = params['pet_id'] path_params['petId'] = params['pet_id']
query_params = {} query_params = {}
@@ -292,7 +292,7 @@ class PetApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -301,12 +301,12 @@ class PetApi(object):
auth_settings = ['api_key', 'petstore_auth'] auth_settings = ['api_key', 'petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response='Pet', auth_settings=auth_settings) response='Pet', auth_settings=auth_settings)
return response return response
def update_pet_with_form(self, pet_id, **kwargs): def update_pet_with_form(self, pet_id, **kwargs):
""" """
Updates a pet in the store with form data Updates a pet in the store with form data
@@ -318,17 +318,17 @@ class PetApi(object):
:return: None :return: None
""" """
# verify the required parameter 'pet_id' is set # verify the required parameter 'pet_id' is set
if pet_id is None: if pet_id is None:
raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`")
all_params = ['pet_id', 'name', 'status'] all_params = ['pet_id', 'name', 'status']
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method update_pet_with_form" % key) raise TypeError("Got an unexpected keyword argument '%s' to method update_pet_with_form" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/pet/{petId}'.replace('{format}', 'json') resource_path = '/pet/{petId}'.replace('{format}', 'json')
@@ -336,8 +336,8 @@ class PetApi(object):
path_params = {} path_params = {}
if 'pet_id' in params: if 'pet_id' in params:
path_params['petId'] = params['pet_id'] path_params['petId'] = params['pet_id']
query_params = {} query_params = {}
@@ -346,10 +346,10 @@ class PetApi(object):
form_params = {} form_params = {}
files = {} files = {}
if 'name' in params: if 'name' in params:
form_params['name'] = params['name'] form_params['name'] = params['name']
if 'status' in params: if 'status' in params:
form_params['status'] = params['status'] form_params['status'] = params['status']
body_params = None body_params = None
@@ -357,7 +357,7 @@ class PetApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type(['application/x-www-form-urlencoded']) header_params['Content-Type'] = self.api_client.select_header_content_type(['application/x-www-form-urlencoded'])
@@ -366,10 +366,10 @@ class PetApi(object):
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)
def delete_pet(self, pet_id, **kwargs): def delete_pet(self, pet_id, **kwargs):
""" """
Deletes a pet Deletes a pet
@@ -380,17 +380,17 @@ class PetApi(object):
:return: None :return: None
""" """
# verify the required parameter 'pet_id' is set # verify the required parameter 'pet_id' is set
if pet_id is None: if pet_id is None:
raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`")
all_params = ['api_key', 'pet_id'] all_params = ['api_key', 'pet_id']
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method delete_pet" % key) raise TypeError("Got an unexpected keyword argument '%s' to method delete_pet" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/pet/{petId}'.replace('{format}', 'json') resource_path = '/pet/{petId}'.replace('{format}', 'json')
@@ -398,14 +398,14 @@ class PetApi(object):
path_params = {} path_params = {}
if 'pet_id' in params: if 'pet_id' in params:
path_params['petId'] = params['pet_id'] path_params['petId'] = params['pet_id']
query_params = {} query_params = {}
header_params = {} header_params = {}
if 'api_key' in params: if 'api_key' in params:
header_params['api_key'] = params['api_key'] header_params['api_key'] = params['api_key']
form_params = {} form_params = {}
@@ -416,7 +416,7 @@ class PetApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -425,10 +425,10 @@ class PetApi(object):
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)
def upload_file(self, pet_id, **kwargs): def upload_file(self, pet_id, **kwargs):
""" """
uploads an image uploads an image
@@ -440,17 +440,17 @@ class PetApi(object):
:return: None :return: None
""" """
# verify the required parameter 'pet_id' is set # verify the required parameter 'pet_id' is set
if pet_id is None: if pet_id is None:
raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`")
all_params = ['pet_id', 'additional_metadata', 'file'] all_params = ['pet_id', 'additional_metadata', 'file']
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method upload_file" % key) raise TypeError("Got an unexpected keyword argument '%s' to method upload_file" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json')
@@ -458,8 +458,8 @@ class PetApi(object):
path_params = {} path_params = {}
if 'pet_id' in params: if 'pet_id' in params:
path_params['petId'] = params['pet_id'] path_params['petId'] = params['pet_id']
query_params = {} query_params = {}
@@ -468,10 +468,10 @@ class PetApi(object):
form_params = {} form_params = {}
files = {} files = {}
if 'additional_metadata' in params: if 'additional_metadata' in params:
form_params['additionalMetadata'] = params['additional_metadata'] form_params['additionalMetadata'] = params['additional_metadata']
if 'file' in params: if 'file' in params:
files['file'] = params['file'] files['file'] = params['file']
body_params = None body_params = None
@@ -479,7 +479,7 @@ class PetApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type(['multipart/form-data']) header_params['Content-Type'] = self.api_client.select_header_content_type(['multipart/form-data'])
@@ -488,8 +488,8 @@ class PetApi(object):
auth_settings = ['petstore_auth'] auth_settings = ['petstore_auth']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)

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,18 +30,18 @@ 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:
self.api_client = api_client self.api_client = api_client
else: else:
if not configuration.api_client: if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2') configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client self.api_client = configuration.api_client
def get_inventory(self, **kwargs):
def get_inventory(self, **kwargs):
""" """
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
@@ -54,9 +54,9 @@ class StoreApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_inventory" % key) raise TypeError("Got an unexpected keyword argument '%s' to method get_inventory" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/store/inventory'.replace('{format}', 'json') resource_path = '/store/inventory'.replace('{format}', 'json')
@@ -76,7 +76,7 @@ class StoreApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -85,12 +85,12 @@ class StoreApi(object):
auth_settings = ['api_key'] auth_settings = ['api_key']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response='map(String, int)', auth_settings=auth_settings) response='map(String, int)', auth_settings=auth_settings)
return response return response
def place_order(self, **kwargs): def place_order(self, **kwargs):
""" """
Place an order for a pet Place an order for a pet
@@ -104,9 +104,9 @@ class StoreApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method place_order" % key) raise TypeError("Got an unexpected keyword argument '%s' to method place_order" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/store/order'.replace('{format}', 'json') resource_path = '/store/order'.replace('{format}', 'json')
@@ -123,13 +123,13 @@ class StoreApi(object):
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -138,12 +138,12 @@ class StoreApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response='Order', auth_settings=auth_settings) response='Order', auth_settings=auth_settings)
return response return response
def get_order_by_id(self, order_id, **kwargs): def get_order_by_id(self, order_id, **kwargs):
""" """
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
@@ -153,17 +153,17 @@ class StoreApi(object):
:return: Order :return: Order
""" """
# verify the required parameter 'order_id' is set # verify the required parameter 'order_id' is set
if order_id is None: if order_id is None:
raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`")
all_params = ['order_id'] all_params = ['order_id']
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_order_by_id" % key) raise TypeError("Got an unexpected keyword argument '%s' to method get_order_by_id" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/store/order/{orderId}'.replace('{format}', 'json') resource_path = '/store/order/{orderId}'.replace('{format}', 'json')
@@ -171,8 +171,8 @@ class StoreApi(object):
path_params = {} path_params = {}
if 'order_id' in params: if 'order_id' in params:
path_params['orderId'] = params['order_id'] path_params['orderId'] = params['order_id']
query_params = {} query_params = {}
@@ -186,7 +186,7 @@ class StoreApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -195,12 +195,12 @@ class StoreApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response='Order', auth_settings=auth_settings) response='Order', auth_settings=auth_settings)
return response return response
def delete_order(self, order_id, **kwargs): def delete_order(self, order_id, **kwargs):
""" """
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
@@ -210,17 +210,17 @@ class StoreApi(object):
:return: None :return: None
""" """
# verify the required parameter 'order_id' is set # verify the required parameter 'order_id' is set
if order_id is None: if order_id is None:
raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") raise ValueError("Missing the required parameter `order_id` when calling `delete_order`")
all_params = ['order_id'] all_params = ['order_id']
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method delete_order" % key) raise TypeError("Got an unexpected keyword argument '%s' to method delete_order" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/store/order/{orderId}'.replace('{format}', 'json') resource_path = '/store/order/{orderId}'.replace('{format}', 'json')
@@ -228,8 +228,8 @@ class StoreApi(object):
path_params = {} path_params = {}
if 'order_id' in params: if 'order_id' in params:
path_params['orderId'] = params['order_id'] path_params['orderId'] = params['order_id']
query_params = {} query_params = {}
@@ -243,7 +243,7 @@ class StoreApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -252,8 +252,8 @@ class StoreApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)

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,18 +30,18 @@ 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:
self.api_client = api_client self.api_client = api_client
else: else:
if not configuration.api_client: if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2') configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client self.api_client = configuration.api_client
def create_user(self, **kwargs):
def create_user(self, **kwargs):
""" """
Create user Create user
This can only be done by the logged in user. This can only be done by the logged in user.
@@ -55,9 +55,9 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method create_user" % key) raise TypeError("Got an unexpected keyword argument '%s' to method create_user" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/user'.replace('{format}', 'json') resource_path = '/user'.replace('{format}', 'json')
@@ -74,13 +74,13 @@ class UserApi(object):
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -89,10 +89,10 @@ class UserApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)
def create_users_with_array_input(self, **kwargs): def create_users_with_array_input(self, **kwargs):
""" """
Creates list of users with given input array Creates list of users with given input array
@@ -106,9 +106,9 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_array_input" % key) raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_array_input" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/user/createWithArray'.replace('{format}', 'json') resource_path = '/user/createWithArray'.replace('{format}', 'json')
@@ -125,13 +125,13 @@ class UserApi(object):
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -140,10 +140,10 @@ class UserApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)
def create_users_with_list_input(self, **kwargs): def create_users_with_list_input(self, **kwargs):
""" """
Creates list of users with given input array Creates list of users with given input array
@@ -157,9 +157,9 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_list_input" % key) raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_list_input" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/user/createWithList'.replace('{format}', 'json') resource_path = '/user/createWithList'.replace('{format}', 'json')
@@ -176,13 +176,13 @@ class UserApi(object):
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -191,10 +191,10 @@ class UserApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)
def login_user(self, **kwargs): def login_user(self, **kwargs):
""" """
Logs user into the system Logs user into the system
@@ -209,9 +209,9 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method login_user" % key) raise TypeError("Got an unexpected keyword argument '%s' to method login_user" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/user/login'.replace('{format}', 'json') resource_path = '/user/login'.replace('{format}', 'json')
@@ -221,10 +221,10 @@ class UserApi(object):
query_params = {} query_params = {}
if 'username' in params: if 'username' in params:
query_params['username'] = params['username'] query_params['username'] = params['username']
if 'password' in params: if 'password' in params:
query_params['password'] = params['password'] query_params['password'] = params['password']
header_params = {} header_params = {}
@@ -237,7 +237,7 @@ class UserApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -246,12 +246,12 @@ class UserApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response='str', auth_settings=auth_settings) response='str', auth_settings=auth_settings)
return response return response
def logout_user(self, **kwargs): def logout_user(self, **kwargs):
""" """
Logs out current logged in user session Logs out current logged in user session
@@ -264,9 +264,9 @@ class UserApi(object):
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method logout_user" % key) raise TypeError("Got an unexpected keyword argument '%s' to method logout_user" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/user/logout'.replace('{format}', 'json') resource_path = '/user/logout'.replace('{format}', 'json')
@@ -286,7 +286,7 @@ class UserApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -295,10 +295,10 @@ class UserApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)
def get_user_by_name(self, username, **kwargs): def get_user_by_name(self, username, **kwargs):
""" """
Get user by user name Get user by user name
@@ -308,17 +308,17 @@ class UserApi(object):
:return: User :return: User
""" """
# verify the required parameter 'username' is set # verify the required parameter 'username' is set
if username is None: if username is None:
raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`")
all_params = ['username'] all_params = ['username']
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_user_by_name" % key) raise TypeError("Got an unexpected keyword argument '%s' to method get_user_by_name" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/user/{username}'.replace('{format}', 'json') resource_path = '/user/{username}'.replace('{format}', 'json')
@@ -326,8 +326,8 @@ class UserApi(object):
path_params = {} path_params = {}
if 'username' in params: if 'username' in params:
path_params['username'] = params['username'] path_params['username'] = params['username']
query_params = {} query_params = {}
@@ -341,7 +341,7 @@ class UserApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -350,12 +350,12 @@ class UserApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response='User', auth_settings=auth_settings) response='User', auth_settings=auth_settings)
return response return response
def update_user(self, username, **kwargs): def update_user(self, username, **kwargs):
""" """
Updated user Updated user
This can only be done by the logged in user. This can only be done by the logged in user.
@@ -366,17 +366,17 @@ class UserApi(object):
:return: None :return: None
""" """
# verify the required parameter 'username' is set # verify the required parameter 'username' is set
if username is None: if username is None:
raise ValueError("Missing the required parameter `username` when calling `update_user`") raise ValueError("Missing the required parameter `username` when calling `update_user`")
all_params = ['username', 'body'] all_params = ['username', 'body']
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method update_user" % key) raise TypeError("Got an unexpected keyword argument '%s' to method update_user" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/user/{username}'.replace('{format}', 'json') resource_path = '/user/{username}'.replace('{format}', 'json')
@@ -384,8 +384,8 @@ class UserApi(object):
path_params = {} path_params = {}
if 'username' in params: if 'username' in params:
path_params['username'] = params['username'] path_params['username'] = params['username']
query_params = {} query_params = {}
@@ -396,13 +396,13 @@ class UserApi(object):
body_params = None body_params = None
if 'body' in params: if 'body' in params:
body_params = params['body'] body_params = params['body']
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -411,10 +411,10 @@ class UserApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)
def delete_user(self, username, **kwargs): def delete_user(self, username, **kwargs):
""" """
Delete user Delete user
This can only be done by the logged in user. This can only be done by the logged in user.
@@ -424,17 +424,17 @@ class UserApi(object):
:return: None :return: None
""" """
# verify the required parameter 'username' is set # verify the required parameter 'username' is set
if username is None: if username is None:
raise ValueError("Missing the required parameter `username` when calling `delete_user`") raise ValueError("Missing the required parameter `username` when calling `delete_user`")
all_params = ['username'] all_params = ['username']
params = locals() params = locals()
for key, val in iteritems(params['kwargs']): for key, val in iteritems(params['kwargs']):
if key not in all_params: if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method delete_user" % key) raise TypeError("Got an unexpected keyword argument '%s' to method delete_user" % key)
params[key] = val params[key] = val
del params['kwargs'] del params['kwargs']
resource_path = '/user/{username}'.replace('{format}', 'json') resource_path = '/user/{username}'.replace('{format}', 'json')
@@ -442,8 +442,8 @@ class UserApi(object):
path_params = {} path_params = {}
if 'username' in params: if 'username' in params:
path_params['username'] = params['username'] path_params['username'] = params['username']
query_params = {} query_params = {}
@@ -457,7 +457,7 @@ class UserApi(object):
# HTTP header `Accept` # HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']: if not header_params['Accept']:
del header_params['Accept'] del header_params['Accept']
# HTTP header `Content-Type` # HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([]) header_params['Content-Type'] = self.api_client.select_header_content_type([])
@@ -466,8 +466,8 @@ class UserApi(object):
auth_settings = [] auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files, body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings) response=None, auth_settings=auth_settings)

View File

@@ -3,37 +3,37 @@ 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',
'key': 'api_key', 'key': 'api_key',
'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"
# Default api client # Default api client
api_client = None api_client = None
# Authentication settings # Authentication settings
api_key = {} api_key = {}

View File

@@ -4,26 +4,27 @@
""" """
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.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
@@ -31,28 +32,29 @@ class Category(object):
:param dict attributeMap: The key is attribute name and the value is json key in definition. :param dict attributeMap: The key is attribute name and the value is json key in definition.
""" """
self.swagger_types = { self.swagger_types = {
'id': 'int', 'id': 'int',
'name': 'str' 'name': 'str'
} }
self.attribute_map = { self.attribute_map = {
'id': 'id', 'id': 'id',
'name': 'name' 'name': 'name'
} }
self.id = None # int
self.id = None # int
self.name = None # str
self.name = None # str
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@@ -4,26 +4,27 @@
""" """
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.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
@@ -31,48 +32,49 @@ class Order(object):
:param dict attributeMap: The key is attribute name and the value is json key in definition. :param dict attributeMap: The key is attribute name and the value is json key in definition.
""" """
self.swagger_types = { self.swagger_types = {
'id': 'int', 'id': 'int',
'pet_id': 'int', 'pet_id': 'int',
'quantity': 'int', 'quantity': 'int',
'ship_date': 'DateTime', 'ship_date': 'DateTime',
'status': 'str', 'status': 'str',
'complete': 'bool' 'complete': 'bool'
} }
self.attribute_map = { self.attribute_map = {
'id': 'id', 'id': 'id',
'pet_id': 'petId', 'pet_id': 'petId',
'quantity': 'quantity', 'quantity': 'quantity',
'ship_date': 'shipDate', 'ship_date': 'shipDate',
'status': 'status', 'status': 'status',
'complete': 'complete' 'complete': 'complete'
} }
self.id = None # int
self.id = None # int
self.pet_id = None # int
self.quantity = None # int
self.pet_id = None # int
self.ship_date = None # DateTime
# Order Status
self.status = None # str
self.quantity = None # int
self.complete = None # bool
self.ship_date = None # DateTime
# Order Status
self.status = None # str
self.complete = None # bool
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@@ -4,26 +4,27 @@
""" """
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.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
@@ -31,48 +32,49 @@ class Pet(object):
:param dict attributeMap: The key is attribute name and the value is json key in definition. :param dict attributeMap: The key is attribute name and the value is json key in definition.
""" """
self.swagger_types = { self.swagger_types = {
'id': 'int', 'id': 'int',
'category': 'Category', 'category': 'Category',
'name': 'str', 'name': 'str',
'photo_urls': 'list[str]', 'photo_urls': 'list[str]',
'tags': 'list[Tag]', 'tags': 'list[Tag]',
'status': 'str' 'status': 'str'
} }
self.attribute_map = { 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',
'status': 'status' 'status': 'status'
} }
self.id = None # int
self.id = None # int
self.category = None # Category
self.name = None # str
self.category = None # Category
self.photo_urls = None # list[str]
self.tags = None # list[Tag]
self.name = None # str # pet status in the store
self.status = None # str
self.photo_urls = None # list[str]
self.tags = None # list[Tag]
# pet status in the store
self.status = None # str
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@@ -4,26 +4,27 @@
""" """
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.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
@@ -31,28 +32,29 @@ class Tag(object):
:param dict attributeMap: The key is attribute name and the value is json key in definition. :param dict attributeMap: The key is attribute name and the value is json key in definition.
""" """
self.swagger_types = { self.swagger_types = {
'id': 'int', 'id': 'int',
'name': 'str' 'name': 'str'
} }
self.attribute_map = { self.attribute_map = {
'id': 'id', 'id': 'id',
'name': 'name' 'name': 'name'
} }
self.id = None # int
self.id = None # int
self.name = None # str
self.name = None # str
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@@ -4,26 +4,27 @@
""" """
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.
""" """
def __init__(self): def __init__(self):
""" """
Swagger model Swagger model
@@ -31,58 +32,59 @@ class User(object):
:param dict attributeMap: The key is attribute name and the value is json key in definition. :param dict attributeMap: The key is attribute name and the value is json key in definition.
""" """
self.swagger_types = { self.swagger_types = {
'id': 'int', 'id': 'int',
'username': 'str', 'username': 'str',
'first_name': 'str', 'first_name': 'str',
'last_name': 'str', 'last_name': 'str',
'email': 'str', 'email': 'str',
'password': 'str', 'password': 'str',
'phone': 'str', 'phone': 'str',
'user_status': 'int' 'user_status': 'int'
} }
self.attribute_map = { 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': 'userStatus' 'user_status': 'userStatus'
} }
self.id = None # int
self.id = None # int
self.username = None # str
self.first_name = None # str
self.username = None # str
self.last_name = None # str
self.email = None # str
self.first_name = None # str
self.password = None # str
self.phone = None # str
self.last_name = None # str # User Status
self.user_status = None # int
self.email = None # str
self.password = None # str
self.phone = None # str
# User Status
self.user_status = None # int
def __repr__(self): def __repr__(self):
properties = [] properties = []
for p in self.__dict__: for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap': if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
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:
self.body = json.loads(data)
except ValueError:
self.body = data
def __str__(self): try:
""" self.body = json.loads(data)
Custom error response messages except ValueError:
""" self.body = data
return "({0})\n"\
"Reason: {1}\n"\ def __str__(self):
"HTTP response headers: {2}\n"\ """
"HTTP response body: {3}\n".\ Custom error response messages
format(self.status, self.reason, self.headers, self.body) """
return "({0})\n"\
"Reason: {1}\n"\
"HTTP response headers: {2}\n"\
"HTTP response body: {3}\n".\
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,105 +1,112 @@
#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);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject* QJsonDocument doc(*obj);
SWGCategory::asJsonObject() { QByteArray bytes = doc.toJson();
QJsonObject* obj = new QJsonObject(); return QString(bytes);
}
QJsonObject*
SWGCategory::asJsonObject() {
QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
toJsonValue(QString("name"), name, obj, QString("QString")); toJsonValue(QString("name"), name, obj, QString("QString"));
return obj; return obj;
} }
qint64
SWGCategory::getId() { qint64
return id; SWGCategory::getId() {
} return id;
void }
SWGCategory::setId(qint64 id) { void
this->id = id; SWGCategory::setId(qint64 id) {
} this->id = id;
}
QString*
SWGCategory::getName() { QString*
return name; SWGCategory::getName() {
} return name;
void }
SWGCategory::setName(QString* name) { void
this->name = name; SWGCategory::setName(QString* name) {
} this->name = name;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@@ -1,47 +1,48 @@
/* /*
* 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();
void init(); void init();
void cleanup(); void cleanup();
QString asJson (); QString asJson ();
QJsonObject* asJsonObject(); QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json); void fromJsonObject(QJsonObject &json);
SWGCategory* fromJson(QString &jsonString); SWGCategory* fromJson(QString &jsonString);
qint64 getId(); qint64 getId();
void setId(qint64 id); void setId(qint64 id);
QString* getName(); QString* getName();
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,166 +1,201 @@
#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
*val = obj.toBool(); <bool
} *>(value);
else if(QStringLiteral("qint32").compare(type) == 0) { *val = obj.toBool();
qint32 *val = static_cast<qint32*>(value); }
*val = obj.toInt(); else if(QStringLiteral("qint32").compare(type) == 0) {
} qint32 *val = static_cast
else if(QStringLiteral("qint64").compare(type) == 0) { <qint32
qint64 *val = static_cast<qint64*>(value); *>(value);
*val = obj.toVariant().toLongLong(); *val = obj.toInt();
} }
else if (QStringLiteral("QString").compare(type) == 0) { else if(QStringLiteral("qint64").compare(type) == 0) {
QString **val = static_cast<QString**>(value); qint64 *val = static_cast
<qint64
*>(value);
*val = obj.toVariant().toLongLong();
}
else if (QStringLiteral("QString").compare(type) == 0) {
QString **val = static_cast
<QString
**>(value);
if(val != NULL) { if(val != NULL) {
if(!obj.isNull()) { if(!obj.isNull()) {
// create a new value and return // create a new value and return
delete *val; delete *val;
*val = new QString(obj.toString()); *val = new QString(obj.toString());
return; return;
} }
else { else {
// set target to NULL // set target to NULL
delete *val; delete *val;
*val = NULL; *val = NULL;
} }
} }
else { else {
qDebug() << "Can't set value because the target pointer is NULL"; qDebug() << "Can't set value because the target pointer is NULL";
} }
} }
else if(type.startsWith("SWG") && obj.isObject()) { else if(type.startsWith("SWG") && obj.isObject()) {
// complex type // complex type
QJsonObject jsonObj = obj.toObject(); QJsonObject jsonObj = obj.toObject();
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
QJsonArray arr = obj.toArray(); <void
foreach (const QJsonValue & jval, arr) { *>* output = new QList
<void
*>();
QJsonArray arr = obj.toArray();
foreach (const QJsonValue & jval, arr) {
if(complexType.startsWith("SWG")) { if(complexType.startsWith("SWG")) {
// it's an object // it's an object
SWGObject * val = (SWGObject*)create(complexType); SWGObject * val = (SWGObject*)create(complexType);
QJsonObject t = jval.toObject(); QJsonObject t = jval.toObject();
val->fromJsonObject(t); val->fromJsonObject(t);
output->append(val); output->append(val);
} }
else { else {
// primitives // primitives
if(QStringLiteral("qint32").compare(complexType) == 0) { if(QStringLiteral("qint32").compare(complexType) == 0) {
qint32 val; qint32 val;
setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral("")); setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral(""));
output->append((void*)&val); output->append((void*)&val);
} }
else if(QStringLiteral("qint64").compare(complexType) == 0) { else if(QStringLiteral("qint64").compare(complexType) == 0) {
qint64 val; qint64 val;
setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral("")); setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral(""));
output->append((void*)&val); output->append((void*)&val);
} }
else if(QStringLiteral("bool").compare(complexType) == 0) { else if(QStringLiteral("bool").compare(complexType) == 0) {
bool val; bool val;
setValue(&val, jval, QStringLiteral("bool"), QStringLiteral("")); setValue(&val, jval, QStringLiteral("bool"), QStringLiteral(""));
output->append((void*)&val); output->append((void*)&val);
} }
}
}
QList
<void
*> **val = static_cast
<QList
<void
*>**>(value);
delete *val;
*val = output;
}
} }
}
QList<void*> **val = static_cast<QList<void*>**>(value);
delete *val;
*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
if(swgObject != NULL) { <SWGObject *>(value);
QJsonObject* o = (*swgObject).asJsonObject(); if(swgObject != NULL) {
if(name != NULL) { QJsonObject* o = (*swgObject).asJsonObject();
if(name != NULL) {
output->insert(name, *o); output->insert(name, *o);
delete o; delete o;
} }
else { else {
output->empty(); output->empty();
foreach(QString key, o->keys()) { foreach(QString key, o->keys()) {
output->insert(key, o->value(key)); output->insert(key, o->value(key));
}
}
}
}
else if(QStringLiteral("QString").compare(type) == 0) {
QString* str = static_cast
<QString
*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("qint32").compare(type) == 0) {
qint32* str = static_cast
<qint32
*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("qint64").compare(type) == 0) {
qint64* str = static_cast
<qint64
*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("bool").compare(type) == 0) {
bool* str = static_cast
<bool
*>(value);
output->insert(name, QJsonValue(*str));
}
} }
}
}
}
else if(QStringLiteral("QString").compare(type) == 0) {
QString* str = static_cast<QString*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("qint32").compare(type) == 0) {
qint32* str = static_cast<qint32*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("qint64").compare(type) == 0) {
qint64* str = static_cast<qint64*>(value);
output->insert(name, QJsonValue(*str));
}
else if(QStringLiteral("bool").compare(type) == 0) {
bool* str = static_cast<bool*>(value);
output->insert(name, QJsonValue(*str));
}
}
void void
toJsonArray(QList<void*>* value, QJsonArray* output, QString innerName, QString innerType) { toJsonArray(QList
foreach(void* obj, *value) { <void
QJsonObject element; *>* value, QJsonArray* output, QString innerName, QString innerType) {
foreach(void* obj, *value) {
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
return QString(*str); <QString
} *>(value);
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;
}
inline void* create(QString json, QString type) { return NULL;
void* val = create(type); }
if(val != NULL) {
SWGObject* obj = static_cast<SWGObject*>(val); inline void* create(QString json, QString type) {
return obj->fromJson(json); void* val = create(type);
} if(val != NULL) {
if(type.startsWith("QString")) { SWGObject* obj = static_cast
return new QString(); <SWGObject*>(val);
} return obj->fromJson(json);
return NULL; }
} if(type.startsWith("QString")) {
return new QString();
}
return NULL;
}
} /* namespace Swagger */ } /* namespace Swagger */
#endif /* ModelFactory_H_ */ #endif /* ModelFactory_H_ */

View File

@@ -1,24 +1,25 @@
#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;
} }
virtual ~SWGObject() {} virtual ~SWGObject() {}
virtual SWGObject* fromJson(QString &jsonString) { virtual SWGObject* fromJson(QString &jsonString) {
Q_UNUSED(jsonString); Q_UNUSED(jsonString);
return NULL; return NULL;
} }
virtual void fromJsonObject(QJsonObject &json) { virtual void fromJsonObject(QJsonObject &json) {
Q_UNUSED(json); Q_UNUSED(json);
} }
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,34 +37,34 @@ SWGOrder::init() {
status = new QString(""); status = new QString("");
complete = false; complete = false;
} }
void void
SWGOrder::cleanup() { SWGOrder::cleanup() {
if(shipDate != NULL) { if(shipDate != NULL) {
delete shipDate; delete shipDate;
} }
if(status != NULL) { if(status != NULL) {
delete status; delete status;
} }
} }
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,97 +72,104 @@ 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);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject* QJsonDocument doc(*obj);
SWGOrder::asJsonObject() { QByteArray bytes = doc.toJson();
QJsonObject* obj = new QJsonObject(); return QString(bytes);
}
QJsonObject*
SWGOrder::asJsonObject() {
QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
obj->insert("petId", QJsonValue(petId)); obj->insert("petId", QJsonValue(petId));
obj->insert("quantity", QJsonValue(quantity)); obj->insert("quantity", QJsonValue(quantity));
toJsonValue(QString("shipDate"), shipDate, obj, QString("QDateTime")); toJsonValue(QString("shipDate"), shipDate, obj, QString("QDateTime"));
toJsonValue(QString("status"), status, obj, QString("QString"));
toJsonValue(QString("status"), status, obj, QString("QString"));
obj->insert("complete", QJsonValue(complete)); obj->insert("complete", QJsonValue(complete));
return obj; return obj;
} }
qint64
SWGOrder::getId() { qint64
return id; SWGOrder::getId() {
} return id;
void }
SWGOrder::setId(qint64 id) { void
this->id = id; SWGOrder::setId(qint64 id) {
} this->id = id;
}
qint64
SWGOrder::getPetId() { qint64
return petId; SWGOrder::getPetId() {
} return petId;
void }
SWGOrder::setPetId(qint64 petId) { void
this->petId = petId; SWGOrder::setPetId(qint64 petId) {
} this->petId = petId;
}
qint32
SWGOrder::getQuantity() { qint32
return quantity; SWGOrder::getQuantity() {
} return quantity;
void }
SWGOrder::setQuantity(qint32 quantity) { void
this->quantity = quantity; SWGOrder::setQuantity(qint32 quantity) {
} this->quantity = quantity;
}
QDateTime*
SWGOrder::getShipDate() { QDateTime*
return shipDate; SWGOrder::getShipDate() {
} return shipDate;
void }
SWGOrder::setShipDate(QDateTime* shipDate) { void
this->shipDate = shipDate; SWGOrder::setShipDate(QDateTime* shipDate) {
} this->shipDate = shipDate;
}
QString*
SWGOrder::getStatus() { QString*
return status; SWGOrder::getStatus() {
} return status;
void }
SWGOrder::setStatus(QString* status) { void
this->status = status; SWGOrder::setStatus(QString* status) {
} this->status = status;
}
bool
SWGOrder::getComplete() { bool
return complete; SWGOrder::getComplete() {
} return complete;
void }
SWGOrder::setComplete(bool complete) { void
this->complete = complete; SWGOrder::setComplete(bool complete) {
} this->complete = complete;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@@ -1,51 +1,52 @@
/* /*
* 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();
void init(); void init();
void cleanup(); void cleanup();
QString asJson (); QString asJson ();
QJsonObject* asJsonObject(); QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json); void fromJsonObject(QJsonObject &json);
SWGOrder* fromJson(QString &jsonString); SWGOrder* fromJson(QString &jsonString);
qint64 getId(); qint64 getId();
void setId(qint64 id); void setId(qint64 id);
qint64 getPetId(); qint64 getPetId();
void setPetId(qint64 petId); void setPetId(qint64 petId);
qint32 getQuantity(); qint32 getQuantity();
void setQuantity(qint32 quantity); void setQuantity(qint32 quantity);
QDateTime* getShipDate(); QDateTime* getShipDate();
void setShipDate(QDateTime* shipDate); void setShipDate(QDateTime* shipDate);
QString* getStatus(); QString* getStatus();
void setStatus(QString* status); void setStatus(QString* status);
bool getComplete(); bool getComplete();
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,48 +37,48 @@ 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;
} }
if(name != NULL) { if(name != NULL) {
delete name; delete name;
} }
if(photoUrls != NULL) { if(photoUrls != NULL) {
QList<QString*>* arr = photoUrls; QList<QString*>* arr = photoUrls;
foreach(QString* o, *arr) { foreach(QString* o, *arr) {
delete o; delete o;
}
delete photoUrls;
} }
delete photoUrls;
}
if(tags != NULL) { if(tags != NULL) {
QList<SWGTag*>* arr = tags; QList<SWGTag*>* arr = tags;
foreach(SWGTag* o, *arr) { foreach(SWGTag* o, *arr) {
delete o; delete o;
}
delete tags;
} }
delete tags;
}
if(status != NULL) { if(status != NULL) {
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,118 +86,127 @@ 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);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject* QJsonDocument doc(*obj);
SWGPet::asJsonObject() { QByteArray bytes = doc.toJson();
QJsonObject* obj = new QJsonObject(); return QString(bytes);
}
QJsonObject*
SWGPet::asJsonObject() {
QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
toJsonValue(QString("category"), category, obj, QString("SWGCategory")); toJsonValue(QString("category"), category, obj, QString("SWGCategory"));
toJsonValue(QString("name"), name, obj, QString("QString"));
toJsonValue(QString("name"), name, obj, QString("QString")); QList<QString*>* photoUrlsList = photoUrls;
QJsonArray photoUrlsJsonArray;
toJsonArray((QList
<void*>*)photoUrls, &photoUrlsJsonArray, "photoUrls", "QString");
QList<QString*>* photoUrlsList = photoUrls;
QJsonArray photoUrlsJsonArray;
toJsonArray((QList<void*>*)photoUrls, &photoUrlsJsonArray, "photoUrls", "QString");
obj->insert("photoUrls", photoUrlsJsonArray); obj->insert("photoUrls", photoUrlsJsonArray);
QList<SWGTag*>* tagsList = tags;
QList<SWGTag*>* tagsList = tags; QJsonArray tagsJsonArray;
QJsonArray tagsJsonArray; toJsonArray((QList
toJsonArray((QList<void*>*)tags, &tagsJsonArray, "tags", "SWGTag"); <void*>*)tags, &tagsJsonArray, "tags", "SWGTag");
obj->insert("tags", tagsJsonArray); obj->insert("tags", tagsJsonArray);
toJsonValue(QString("status"), status, obj, QString("QString"));
toJsonValue(QString("status"), status, obj, QString("QString"));
return obj; return obj;
} }
qint64
SWGPet::getId() { qint64
return id; SWGPet::getId() {
} return id;
void }
SWGPet::setId(qint64 id) { void
this->id = id; SWGPet::setId(qint64 id) {
} this->id = id;
}
SWGCategory*
SWGPet::getCategory() { SWGCategory*
return category; SWGPet::getCategory() {
} return category;
void }
SWGPet::setCategory(SWGCategory* category) { void
this->category = category; SWGPet::setCategory(SWGCategory* category) {
} this->category = category;
}
QString*
SWGPet::getName() { QString*
return name; SWGPet::getName() {
} return name;
void }
SWGPet::setName(QString* name) { void
this->name = name; SWGPet::setName(QString* name) {
} this->name = name;
}
QList<QString*>*
SWGPet::getPhotoUrls() { QList<QString*>*
return photoUrls; SWGPet::getPhotoUrls() {
} return photoUrls;
void }
SWGPet::setPhotoUrls(QList<QString*>* photoUrls) { void
this->photoUrls = photoUrls; SWGPet::setPhotoUrls(QList<QString*>* photoUrls) {
} this->photoUrls = photoUrls;
}
QList<SWGTag*>*
SWGPet::getTags() { QList<SWGTag*>*
return tags; SWGPet::getTags() {
} return tags;
void }
SWGPet::setTags(QList<SWGTag*>* tags) { void
this->tags = tags; SWGPet::setTags(QList<SWGTag*>* tags) {
} this->tags = tags;
}
QString*
SWGPet::getStatus() { QString*
return status; SWGPet::getStatus() {
} return status;
void }
SWGPet::setStatus(QString* status) { void
this->status = status; SWGPet::setStatus(QString* 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,39 +16,39 @@
#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();
void init(); void init();
void cleanup(); void cleanup();
QString asJson (); QString asJson ();
QJsonObject* asJsonObject(); QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json); void fromJsonObject(QJsonObject &json);
SWGPet* fromJson(QString &jsonString); SWGPet* fromJson(QString &jsonString);
qint64 getId(); qint64 getId();
void setId(qint64 id); void setId(qint64 id);
SWGCategory* getCategory(); SWGCategory* getCategory();
void setCategory(SWGCategory* category); void setCategory(SWGCategory* category);
QString* getName(); QString* getName();
void setName(QString* name); void setName(QString* name);
QList<QString*>* getPhotoUrls(); QList<QString*>* getPhotoUrls();
void setPhotoUrls(QList<QString*>* photoUrls); void setPhotoUrls(QList<QString*>* photoUrls);
QList<SWGTag*>* getTags(); QList<SWGTag*>* getTags();
void setTags(QList<SWGTag*>* tags); void setTags(QList<SWGTag*>* tags);
QString* getStatus(); QString* getStatus();
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_ */

File diff suppressed because it is too large Load Diff

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,238 +2,249 @@
#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() {
QString fullPath; void
fullPath.append(this->host).append(this->basePath).append("/store/inventory"); SWGStoreApi::getInventory() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/inventory");
HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET"); HttpRequestInput input(fullPath, "GET");
connect(worker, connect(worker,
&HttpRequestWorker::on_execution_finished, &HttpRequestWorker::on_execution_finished,
this, this,
&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());
} }
else { else {
msg = "Error: " + worker->error_str; msg = "Error: " + worker->error_str;
} }
QMap<QString, qint32>* output = new QMap<QString, qint32>(); QMap<QString, qint32>* output = new QMap<QString, qint32>();
QString json(worker->response); QString json(worker->response);
QByteArray array (json.toStdString().c_str()); QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array); QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject obj = doc.object(); QJsonObject obj = doc.object();
foreach(QString key, obj.keys()) { foreach(QString key, obj.keys()) {
qint32* val; qint32* val;
setValue(&val, obj[key], "QMap", ""); setValue(&val, obj[key], "QMap", "");
output->insert(key, *val); output->insert(key, *val);
} }
worker->deleteLater(); worker->deleteLater();
emit getInventorySignal(output); emit getInventorySignal(output);
} }
void
SWGStoreApi::placeOrder(SWGOrder body) { void
QString fullPath; SWGStoreApi::placeOrder(SWGOrder body) {
fullPath.append(this->host).append(this->basePath).append("/store/order"); QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order");
HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST"); HttpRequestInput input(fullPath, "POST");
QString output = body.asJson(); QString output = body.asJson();
input.request_body.append(output); input.request_body.append(output);
connect(worker, connect(worker,
&HttpRequestWorker::on_execution_finished, &HttpRequestWorker::on_execution_finished,
this, this,
&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());
} }
else { else {
msg = "Error: " + worker->error_str; msg = "Error: " + worker->error_str;
} }
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")));
worker->deleteLater(); worker->deleteLater();
emit placeOrderSignal(output); emit placeOrderSignal(output);
} }
void
SWGStoreApi::getOrderById(QString* orderId) { void
QString fullPath; SWGStoreApi::getOrderById(QString* orderId) {
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}"); QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}"); QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId)); fullPath.replace(orderIdPathParam, stringValue(orderId));
HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET"); HttpRequestInput input(fullPath, "GET");
connect(worker, connect(worker,
&HttpRequestWorker::on_execution_finished, &HttpRequestWorker::on_execution_finished,
this, this,
&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());
} }
else { else {
msg = "Error: " + worker->error_str; msg = "Error: " + worker->error_str;
} }
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")));
worker->deleteLater(); worker->deleteLater();
emit getOrderByIdSignal(output); emit getOrderByIdSignal(output);
} }
void
SWGStoreApi::deleteOrder(QString* orderId) { void
QString fullPath; SWGStoreApi::deleteOrder(QString* orderId) {
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}"); QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}"); QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId)); fullPath.replace(orderIdPathParam, stringValue(orderId));
HttpRequestWorker *worker = new HttpRequestWorker(); HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE"); HttpRequestInput input(fullPath, "DELETE");
connect(worker, connect(worker,
&HttpRequestWorker::on_execution_finished, &HttpRequestWorker::on_execution_finished,
this, this,
&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());
} }
else { else {
msg = "Error: " + worker->error_str; msg = "Error: " + worker->error_str;
} }
worker->deleteLater(); worker->deleteLater();
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,105 +1,112 @@
#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);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject* QJsonDocument doc(*obj);
SWGTag::asJsonObject() { QByteArray bytes = doc.toJson();
QJsonObject* obj = new QJsonObject(); return QString(bytes);
}
QJsonObject*
SWGTag::asJsonObject() {
QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
toJsonValue(QString("name"), name, obj, QString("QString")); toJsonValue(QString("name"), name, obj, QString("QString"));
return obj; return obj;
} }
qint64
SWGTag::getId() { qint64
return id; SWGTag::getId() {
} return id;
void }
SWGTag::setId(qint64 id) { void
this->id = id; SWGTag::setId(qint64 id) {
} this->id = id;
}
QString*
SWGTag::getName() { QString*
return name; SWGTag::getName() {
} return name;
void }
SWGTag::setName(QString* name) { void
this->name = name; SWGTag::setName(QString* name) {
} this->name = name;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@@ -1,47 +1,48 @@
/* /*
* 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();
void init(); void init();
void cleanup(); void cleanup();
QString asJson (); QString asJson ();
QJsonObject* asJsonObject(); QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json); void fromJsonObject(QJsonObject &json);
SWGTag* fromJson(QString &jsonString); SWGTag* fromJson(QString &jsonString);
qint64 getId(); qint64 getId();
void setId(qint64 id); void setId(qint64 id);
QString* getName(); QString* getName();
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,44 +39,44 @@ 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;
} }
if(firstName != NULL) { if(firstName != NULL) {
delete firstName; delete firstName;
} }
if(lastName != NULL) { if(lastName != NULL) {
delete lastName; delete lastName;
} }
if(email != NULL) { if(email != NULL) {
delete email; delete email;
} }
if(password != NULL) { if(password != NULL) {
delete password; delete password;
} }
if(phone != NULL) { if(phone != NULL) {
delete phone; delete phone;
} }
} }
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,137 +86,146 @@ 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);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject* QJsonDocument doc(*obj);
SWGUser::asJsonObject() { QByteArray bytes = doc.toJson();
QJsonObject* obj = new QJsonObject(); return QString(bytes);
}
QJsonObject*
SWGUser::asJsonObject() {
QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id)); obj->insert("id", QJsonValue(id));
toJsonValue(QString("username"), username, obj, QString("QString")); toJsonValue(QString("username"), username, obj, QString("QString"));
toJsonValue(QString("firstName"), firstName, obj, QString("QString"));
toJsonValue(QString("firstName"), firstName, obj, QString("QString")); toJsonValue(QString("lastName"), lastName, obj, QString("QString"));
toJsonValue(QString("email"), email, obj, QString("QString"));
toJsonValue(QString("lastName"), lastName, obj, QString("QString")); toJsonValue(QString("password"), password, obj, QString("QString"));
toJsonValue(QString("email"), email, obj, QString("QString"));
toJsonValue(QString("password"), password, obj, QString("QString"));
toJsonValue(QString("phone"), phone, obj, QString("QString"));
toJsonValue(QString("phone"), phone, obj, QString("QString"));
obj->insert("userStatus", QJsonValue(userStatus)); obj->insert("userStatus", QJsonValue(userStatus));
return obj; return obj;
} }
qint64
SWGUser::getId() { qint64
return id; SWGUser::getId() {
} return id;
void }
SWGUser::setId(qint64 id) { void
this->id = id; SWGUser::setId(qint64 id) {
} this->id = id;
}
QString*
SWGUser::getUsername() { QString*
return username; SWGUser::getUsername() {
} return username;
void }
SWGUser::setUsername(QString* username) { void
this->username = username; SWGUser::setUsername(QString* username) {
} this->username = username;
}
QString*
SWGUser::getFirstName() { QString*
return firstName; SWGUser::getFirstName() {
} return firstName;
void }
SWGUser::setFirstName(QString* firstName) { void
this->firstName = firstName; SWGUser::setFirstName(QString* firstName) {
} this->firstName = firstName;
}
QString*
SWGUser::getLastName() { QString*
return lastName; SWGUser::getLastName() {
} return lastName;
void }
SWGUser::setLastName(QString* lastName) { void
this->lastName = lastName; SWGUser::setLastName(QString* lastName) {
} this->lastName = lastName;
}
QString*
SWGUser::getEmail() { QString*
return email; SWGUser::getEmail() {
} return email;
void }
SWGUser::setEmail(QString* email) { void
this->email = email; SWGUser::setEmail(QString* email) {
} this->email = email;
}
QString*
SWGUser::getPassword() { QString*
return password; SWGUser::getPassword() {
} return password;
void }
SWGUser::setPassword(QString* password) { void
this->password = password; SWGUser::setPassword(QString* password) {
} this->password = password;
}
QString*
SWGUser::getPhone() { QString*
return phone; SWGUser::getPhone() {
} return phone;
void }
SWGUser::setPhone(QString* phone) { void
this->phone = phone; SWGUser::setPhone(QString* phone) {
} this->phone = phone;
}
qint32
SWGUser::getUserStatus() { qint32
return userStatus; SWGUser::getUserStatus() {
} return userStatus;
void }
SWGUser::setUserStatus(qint32 userStatus) { void
this->userStatus = userStatus; SWGUser::setUserStatus(qint32 userStatus) {
} this->userStatus = userStatus;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@@ -1,54 +1,55 @@
/* /*
* 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();
void init(); void init();
void cleanup(); void cleanup();
QString asJson (); QString asJson ();
QJsonObject* asJsonObject(); QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json); void fromJsonObject(QJsonObject &json);
SWGUser* fromJson(QString &jsonString); SWGUser* fromJson(QString &jsonString);
qint64 getId(); qint64 getId();
void setId(qint64 id); void setId(qint64 id);
QString* getUsername(); QString* getUsername();
void setUsername(QString* username); void setUsername(QString* username);
QString* getFirstName(); QString* getFirstName();
void setFirstName(QString* firstName); void setFirstName(QString* firstName);
QString* getLastName(); QString* getLastName();
void setLastName(QString* lastName); void setLastName(QString* lastName);
QString* getEmail(); QString* getEmail();
void setEmail(QString* email); void setEmail(QString* email);
QString* getPassword(); QString* getPassword();
void setPassword(QString* password); void setPassword(QString* password);
QString* getPhone(); QString* getPhone();
void setPhone(QString* phone); void setPhone(QString* phone);
qint32 getUserStatus(); qint32 getUserStatus();
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,442 +2,463 @@
#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) {
QString fullPath; void
fullPath.append(this->host).append(this->basePath).append("/user"); SWGUserApi::createUser(SWGUser body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
QString output = body.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
QString output = body.asJson(); &SWGUserApi::createUserCallback);
input.request_body.append(output);
worker->execute(&input);
}
connect(worker, void
&HttpRequestWorker::on_execution_finished, SWGUserApi::createUserCallback(HttpRequestWorker * worker) {
this, QString msg;
&SWGUserApi::createUserCallback); if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
worker->execute(&input);
}
void worker->deleteLater();
SWGUserApi::createUserCallback(HttpRequestWorker * worker) {
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
emit createUserSignal();
}
void
SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithArray");
worker->deleteLater();
emit createUserSignal();
}
void
SWGUserApi::createUsersWithArrayInput(QList<SWGUser*>* body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithArray");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList
<void
*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
HttpRequestWorker *worker = new HttpRequestWorker(); QJsonDocument doc(*bodyArray);
HttpRequestInput input(fullPath, "POST"); QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList<void*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
connect(worker,
QJsonDocument doc(*bodyArray); &HttpRequestWorker::on_execution_finished,
QByteArray bytes = doc.toJson(); this,
&SWGUserApi::createUsersWithArrayInputCallback);
input.request_body.append(bytes);
worker->execute(&input);
}
void
SWGUserApi::createUsersWithArrayInputCallback(HttpRequestWorker * worker) {
connect(worker, QString msg;
&HttpRequestWorker::on_execution_finished, if (worker->error_type == QNetworkReply::NoError) {
this, msg = QString("Success! %1 bytes").arg(worker->response.length());
&SWGUserApi::createUsersWithArrayInputCallback); }
else {
worker->execute(&input); msg = "Error: " + worker->error_str;
} }
void
SWGUserApi::createUsersWithArrayInputCallback(HttpRequestWorker * worker) {
QString msg; worker->deleteLater();
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
} emit createUsersWithArrayInputSignal();
else { }
msg = "Error: " + worker->error_str;
} void
SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithList");
worker->deleteLater();
emit createUsersWithArrayInputSignal();
}
void HttpRequestWorker *worker = new HttpRequestWorker();
SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) { HttpRequestInput input(fullPath, "POST");
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithList");
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList
HttpRequestWorker *worker = new HttpRequestWorker(); <void
HttpRequestInput input(fullPath, "POST"); *>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList<void*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson();
connect(worker,
input.request_body.append(bytes); &HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUsersWithListInputCallback);
worker->execute(&input);
}
connect(worker,
&HttpRequestWorker::on_execution_finished, void
this, SWGUserApi::createUsersWithListInputCallback(HttpRequestWorker * worker) {
&SWGUserApi::createUsersWithListInputCallback); QString msg;
if (worker->error_type == QNetworkReply::NoError) {
worker->execute(&input); msg = QString("Success! %1 bytes").arg(worker->response.length());
} }
else {
void msg = "Error: " + worker->error_str;
SWGUserApi::createUsersWithListInputCallback(HttpRequestWorker * worker) { }
QString msg;
if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
} worker->deleteLater();
else {
msg = "Error: " + worker->error_str;
} emit createUsersWithListInputSignal();
}
void
worker->deleteLater(); SWGUserApi::loginUser(QString* username
, QString* password) {
QString fullPath;
emit createUsersWithListInputSignal(); fullPath.append(this->host).append(this->basePath).append("/user/login");
}
void
SWGUserApi::loginUser(QString* username, QString* password) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/login");
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("username"))
if(fullPath.indexOf("?") > 0) .append("=")
fullPath.append("&"); .append(QUrl::toPercentEncoding(stringValue(username)));
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("username"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(username)));
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("password"))
if(fullPath.indexOf("?") > 0) .append("=")
fullPath.append("&"); .append(QUrl::toPercentEncoding(stringValue(password)));
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("password"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(password)));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::loginUserCallback);
connect(worker, worker->execute(&input);
&HttpRequestWorker::on_execution_finished, }
this,
&SWGUserApi::loginUserCallback); void
SWGUserApi::loginUserCallback(HttpRequestWorker * worker) {
worker->execute(&input); QString msg;
} if (worker->error_type == QNetworkReply::NoError) {
msg = QString("Success! %1 bytes").arg(worker->response.length());
void }
SWGUserApi::loginUserCallback(HttpRequestWorker * worker) { else {
QString msg; msg = "Error: " + worker->error_str;
if (worker->error_type == QNetworkReply::NoError) { }
msg = QString("Success! %1 bytes").arg(worker->response.length());
}
else {
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
QString* output = static_cast<QString*>(create(json,
QString("QString")));
QString json(worker->response);
QString* output = static_cast<QString*>(create(json, QString("QString")));
worker->deleteLater();
emit loginUserSignal(output);
worker->deleteLater(); }
emit loginUserSignal(output); void
SWGUserApi::logoutUser() {
} QString fullPath;
void fullPath.append(this->host).append(this->basePath).append("/user/logout");
SWGUserApi::logoutUser() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/logout");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
connect(worker, &SWGUserApi::logoutUserCallback);
&HttpRequestWorker::on_execution_finished,
this, worker->execute(&input);
&SWGUserApi::logoutUserCallback); }
worker->execute(&input); void
} SWGUserApi::logoutUserCallback(HttpRequestWorker * worker) {
QString msg;
void if (worker->error_type == QNetworkReply::NoError) {
SWGUserApi::logoutUserCallback(HttpRequestWorker * worker) { msg = QString("Success! %1 bytes").arg(worker->response.length());
QString msg; }
if (worker->error_type == QNetworkReply::NoError) { else {
msg = QString("Success! %1 bytes").arg(worker->response.length()); msg = "Error: " + worker->error_str;
} }
else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
worker->deleteLater(); emit logoutUserSignal();
}
emit logoutUserSignal(); void
} SWGUserApi::getUserByName(QString* username) {
void QString fullPath;
SWGUserApi::getUserByName(QString* username) { fullPath.append(this->host).append(this->basePath).append("/user/{username}");
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
connect(worker, this,
&HttpRequestWorker::on_execution_finished, &SWGUserApi::getUserByNameCallback);
this,
&SWGUserApi::getUserByNameCallback); worker->execute(&input);
}
worker->execute(&input);
} void
SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) {
void QString msg;
SWGUserApi::getUserByNameCallback(HttpRequestWorker * worker) { if (worker->error_type == QNetworkReply::NoError) {
QString msg; msg = QString("Success! %1 bytes").arg(worker->response.length());
if (worker->error_type == QNetworkReply::NoError) { }
msg = QString("Success! %1 bytes").arg(worker->response.length()); else {
} msg = "Error: " + worker->error_str;
else { }
msg = "Error: " + worker->error_str;
}
QString json(worker->response);
SWGUser* output = static_cast<SWGUser*>(create(json,
QString json(worker->response); QString("SWGUser")));
SWGUser* output = static_cast<SWGUser*>(create(json, QString("SWGUser")));
worker->deleteLater();
worker->deleteLater();
emit getUserByNameSignal(output);
emit getUserByNameSignal(output);
}
}
void void
SWGUserApi::updateUser(QString* username, SWGUser body) { SWGUserApi::updateUser(QString* username
QString fullPath; , SWGUser body) {
fullPath.append(this->host).append(this->basePath).append("/user/{username}"); QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username)); QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "PUT"); HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "PUT");
QString output = body.asJson();
input.request_body.append(output); QString output = body.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished, connect(worker,
this, &HttpRequestWorker::on_execution_finished,
&SWGUserApi::updateUserCallback); this,
&SWGUserApi::updateUserCallback);
worker->execute(&input);
} worker->execute(&input);
}
void
SWGUserApi::updateUserCallback(HttpRequestWorker * worker) { void
QString msg; SWGUserApi::updateUserCallback(HttpRequestWorker * worker) {
if (worker->error_type == QNetworkReply::NoError) { QString msg;
msg = QString("Success! %1 bytes").arg(worker->response.length()); if (worker->error_type == QNetworkReply::NoError) {
} msg = QString("Success! %1 bytes").arg(worker->response.length());
else { }
msg = "Error: " + worker->error_str; else {
} msg = "Error: " + worker->error_str;
}
worker->deleteLater();
worker->deleteLater();
emit updateUserSignal();
} emit updateUserSignal();
void }
SWGUserApi::deleteUser(QString* username) {
QString fullPath; void
fullPath.append(this->host).append(this->basePath).append("/user/{username}"); SWGUserApi::deleteUser(QString* username) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this, connect(worker,
&SWGUserApi::deleteUserCallback); &HttpRequestWorker::on_execution_finished,
this,
worker->execute(&input); &SWGUserApi::deleteUserCallback);
}
worker->execute(&input);
void }
SWGUserApi::deleteUserCallback(HttpRequestWorker * worker) {
QString msg; void
if (worker->error_type == QNetworkReply::NoError) { SWGUserApi::deleteUserCallback(HttpRequestWorker * worker) {
msg = QString("Success! %1 bytes").arg(worker->response.length()); QString msg;
} if (worker->error_type == QNetworkReply::NoError) {
else { msg = QString("Success! %1 bytes").arg(worker->response.length());
msg = "Error: " + worker->error_str; }
} else {
msg = "Error: " + worker->error_str;
}
worker->deleteLater();
worker->deleteLater();
emit deleteUserSignal();
}
} /* namespace Swagger */ emit deleteUserSignal();
}
} /* 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,19 +6,18 @@ 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();
RestAdapter adapter = new RestAdapter.Builder() RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint("http://petstore.swagger.io/v2") .setEndpoint("http://petstore.swagger.io/v2")
.setConverter(new GsonConverter(gson)) .setConverter(new GsonConverter(gson))
.build(); .build();
return adapter.create(serviceClass); return adapter.create(serviceClass);
}
} }
}

View File

@@ -1,117 +1,117 @@
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
* *
* @param body Pet object that needs to be added to the store * @param body Pet object that needs to be added to the store
* @return Void * @return Void
*/ */
@PUT("/pet") @PUT("/pet")
Void updatePet( Void updatePet(
@Body Pet body @Body Pet body
); );
/** /**
* 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
* @return Void * @return Void
*/ */
@POST("/pet") @POST("/pet")
Void addPet( Void addPet(
@Body Pet body @Body Pet body
); );
/** /**
* 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> */
*/
@GET("/pet/findByStatus")
@GET("/pet/findByStatus") List<Pet> findPetsByStatus(
List<Pet> findPetsByStatus( @Query("status") List<String> status
@Query("status") List<String> status );
);
/**
/** * 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
* * @return List<Pet>
* @param tags Tags to filter by */
* @return List<Pet>
*/ @GET("/pet/findByTags")
List<Pet> findPetsByTags(
@GET("/pet/findByTags") @Query("tags") List<String> tags
List<Pet> findPetsByTags( );
@Query("tags") List<String> tags
); /**
* 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 * @param petId ID of pet that needs to be fetched
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions * @return Pet
* */
* @param petId ID of pet that needs to be fetched
* @return Pet @GET("/pet/{petId}")
*/ Pet getPetById(
@Path("petId") Long petId
@GET("/pet/{petId}") );
Pet getPetById(
@Path("petId") Long petId /**
); * Updates a pet in the store with form data
*
/** * @param petId ID of pet that needs to be updated
* Updates a pet in the store with form data * @param name Updated name of the pet
* * @param status Updated status of the pet
* @param petId ID of pet that needs to be updated * @return Void
* @param name Updated name of the pet */
* @param status Updated status of the pet
* @return Void @FormUrlEncoded
*/ @POST("/pet/{petId}")
Void updatePetWithForm(
@FormUrlEncoded @Path("petId") String petId,@Field("name") String name,@Field("status") String status
@POST("/pet/{petId}") );
Void updatePetWithForm(
@Path("petId") String petId, @Field("name") String name, @Field("status") String status /**
); * Deletes a pet
*
/** * @param apiKey
* Deletes a pet * @param petId Pet id to delete
* * @return Void
* @param apiKey */
* @param petId Pet id to delete
* @return Void @DELETE("/pet/{petId}")
*/ Void deletePet(
@Header("api_key") String apiKey,@Path("petId") Long petId
@DELETE("/pet/{petId}") );
Void deletePet(
@Header("api_key") String apiKey, @Path("petId") Long petId /**
); * uploads an image
*
/** * @param petId ID of pet to update
* uploads an image * @param additionalMetadata Additional data to pass to server
* * @param file file to upload
* @param petId ID of pet to update * @return Void
* @param additionalMetadata Additional data to pass to server */
* @param file file to upload
* @return Void @Multipart
*/ @POST("/pet/{petId}/uploadImage")
Void uploadFile(
@Multipart @Path("petId") Long petId,@Part("additionalMetadata") String additionalMetadata,@Part("file") TypedFile file
@POST("/pet/{petId}/uploadImage") );
Void uploadFile(
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file }
);
}

View File

@@ -1,60 +1,60 @@
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> */
*/
@GET("/store/inventory")
@GET("/store/inventory") Map<String, Integer> getInventory();
Map<String, Integer> getInventory();
/**
/** * 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 * @return Order
* @return Order */
*/
@POST("/store/order")
@POST("/store/order") Order placeOrder(
Order placeOrder( @Body Order body
@Body Order body );
);
/**
/** * 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
* * @return Order
* @param orderId ID of pet that needs to be fetched */
* @return Order
*/ @GET("/store/order/{orderId}")
Order getOrderById(
@GET("/store/order/{orderId}") @Path("orderId") String orderId
Order getOrderById( );
@Path("orderId") String orderId
); /**
* 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 * @param orderId ID of the order that needs to be deleted
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors * @return Void
* */
* @param orderId ID of the order that needs to be deleted
* @return Void @DELETE("/store/order/{orderId}")
*/ Void deleteOrder(
@Path("orderId") String orderId
@DELETE("/store/order/{orderId}") );
Void deleteOrder(
@Path("orderId") String orderId }
);
}

View File

@@ -1,110 +1,110 @@
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 */
*/
@POST("/user")
@POST("/user") Void createUser(
Void createUser( @Body User body
@Body User body );
);
/**
/** * 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 * @return Void
* @return Void */
*/
@POST("/user/createWithArray")
@POST("/user/createWithArray") Void createUsersWithArrayInput(
Void createUsersWithArrayInput( @Body List<User> body
@Body List<User> body );
);
/**
/** * 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 * @return Void
* @return Void */
*/
@POST("/user/createWithList")
@POST("/user/createWithList") Void createUsersWithListInput(
Void createUsersWithListInput( @Body List<User> body
@Body List<User> body );
);
/**
/** * 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 * @return String
* @return String */
*/
@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 );
);
/**
/** * Logs out current logged in user session
* Logs out current logged in user session *
* * @return Void
* @return Void */
*/
@GET("/user/logout")
@GET("/user/logout") Void logoutUser();
Void logoutUser();
/**
/** * 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. * @return User
* @return User */
*/
@GET("/user/{username}")
@GET("/user/{username}") User getUserByName(
User getUserByName( @Path("username") String username
@Path("username") String username );
);
/**
/** * 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 body Updated user object
* @param username name that need to be deleted * @return Void
* @param body Updated user object */
* @return Void
*/ @PUT("/user/{username}")
Void updateUser(
@PUT("/user/{username}") @Path("username") String username,@Body User body
Void updateUser( );
@Path("username") String username, @Body User body
); /**
* Delete user
/** * This can only be done by the logged in user.
* Delete user * @param username The name that needs to be deleted
* This can only be done by the logged in user. * @return Void
* */
* @param username The name that needs to be deleted
* @return Void @DELETE("/user/{username}")
*/ Void deleteUser(
@Path("username") String username
@DELETE("/user/{username}") );
Void deleteUser(
@Path("username") String username }
);
}

View File

@@ -1,50 +1,50 @@
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 {
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("name") @SerializedName("name")
private String name = null; private String name = 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;
} }
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;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Category {\n"); sb.append("class Category {\n");
sb.append(" id: ").append(id).append("\n"); sb.append(" id: ").append(id).append("\n");
sb.append(" name: ").append(name).append("\n"); sb.append(" name: ").append(name).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -1,115 +1,111 @@
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 {
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("petId") @SerializedName("petId")
private Long petId = null; private Long petId = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("quantity") @SerializedName("quantity")
private Integer quantity = null; private Integer quantity = null;
/** /**
**/ **/
@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
**/ **/
@ApiModelProperty(value = "Order Status") @ApiModelProperty(value = "Order Status")
@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;
} }
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;
} }
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;
} }
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;
} }
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;
} }
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;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Order {\n"); sb.append("class Order {\n");
sb.append(" id: ").append(id).append("\n"); sb.append(" id: ").append(id).append("\n");
sb.append(" petId: ").append(petId).append("\n"); sb.append(" petId: ").append(petId).append("\n");
sb.append(" quantity: ").append(quantity).append("\n"); sb.append(" quantity: ").append(quantity).append("\n");
sb.append(" shipDate: ").append(shipDate).append("\n"); sb.append(" shipDate: ").append(shipDate).append("\n");
sb.append(" status: ").append(status).append("\n"); sb.append(" status: ").append(status).append("\n");
sb.append(" complete: ").append(complete).append("\n"); sb.append(" complete: ").append(complete).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
public enum StatusEnum {
placed, approved, delivered,
} }
}

View File

@@ -1,119 +1,113 @@
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 = "")
public class Pet {
@ApiModel(description = "")
public class Pet {
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("category") @SerializedName("category")
private Category category = null; private Category category = null;
/** /**
**/ **/
@ApiModelProperty(required = true, value = "") @ApiModelProperty(required = true, value = "")
@SerializedName("name") @SerializedName("name")
private String name = null; private String name = null;
/** /**
**/ **/
@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
**/ **/
@ApiModelProperty(value = "pet status in the store") @ApiModelProperty(value = "pet status in the store")
@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;
} }
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;
} }
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;
} }
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;
} }
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;
} }
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;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n"); sb.append("class Pet {\n");
sb.append(" id: ").append(id).append("\n"); sb.append(" id: ").append(id).append("\n");
sb.append(" category: ").append(category).append("\n"); sb.append(" category: ").append(category).append("\n");
sb.append(" name: ").append(name).append("\n"); sb.append(" name: ").append(name).append("\n");
sb.append(" photoUrls: ").append(photoUrls).append("\n"); sb.append(" photoUrls: ").append(photoUrls).append("\n");
sb.append(" tags: ").append(tags).append("\n"); sb.append(" tags: ").append(tags).append("\n");
sb.append(" status: ").append(status).append("\n"); sb.append(" status: ").append(status).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
public enum StatusEnum {
available, pending, sold,
} }
}

View File

@@ -1,50 +1,50 @@
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 {
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("name") @SerializedName("name")
private String name = null; private String name = 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;
} }
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;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n"); sb.append("class Tag {\n");
sb.append(" id: ").append(id).append("\n"); sb.append(" id: ").append(id).append("\n");
sb.append(" name: ").append(name).append("\n"); sb.append(" name: ").append(name).append("\n");
sb.append("}\n"); sb.append("}\n");
return sb.toString(); return sb.toString();
} }
} }

View File

@@ -1,141 +1,135 @@
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 {
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("id") @SerializedName("id")
private Long id = null; private Long id = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("username") @SerializedName("username")
private String username = null; private String username = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("firstName") @SerializedName("firstName")
private String firstName = null; private String firstName = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("lastName") @SerializedName("lastName")
private String lastName = null; private String lastName = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("email") @SerializedName("email")
private String email = null; private String email = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("password") @SerializedName("password")
private String password = null; private String password = null;
/** /**
**/ **/
@ApiModelProperty(value = "") @ApiModelProperty(value = "")
@SerializedName("phone") @SerializedName("phone")
private String phone = null; private String phone = null;
/** /**
* User Status * User Status
**/ **/
@ApiModelProperty(value = "User Status") @ApiModelProperty(value = "User Status")
@SerializedName("userStatus") @SerializedName("userStatus")
private Integer userStatus = null; private Integer userStatus = 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;
} }
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;
} }
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;
} }
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;
} }
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;
} }
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;
} }
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;
} }
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;
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class User {\n"); sb.append("class User {\n");
sb.append(" id: ").append(id).append("\n"); sb.append(" id: ").append(id).append("\n");
sb.append(" username: ").append(username).append("\n"); sb.append(" username: ").append(username).append("\n");
sb.append(" firstName: ").append(firstName).append("\n"); sb.append(" firstName: ").append(firstName).append("\n");
sb.append(" lastName: ").append(lastName).append("\n"); sb.append(" lastName: ").append(lastName).append("\n");
sb.append(" email: ").append(email).append("\n"); sb.append(" email: ").append(email).append("\n");
sb.append(" password: ").append(password).append("\n"); sb.append(" password: ").append(password).append("\n");
sb.append(" phone: ").append(phone).append("\n"); sb.append(" phone: ").append(phone).append("\n");
sb.append(" userStatus: ").append(userStatus).append("\n"); sb.append(" userStatus: ").append(userStatus).append("\n");
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

@@ -1,328 +1,337 @@
require "uri" require "uri"
module SwaggerClient module SwaggerClient
class PetApi class PetApi
basePath = "http://petstore.swagger.io/v2" basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker # apiInvoker = APIInvoker
# Update an existing pet
#
# @param [Hash] opts the optional parameters
# @option opts [Pet] :body Pet object that needs to be added to the store
# @return [nil]
def self.update_pet(opts = {})
# Update an existing pet # resource path
# path = "/pet".sub('{format}','json')
# @param [Hash] opts the optional parameters
# @option opts [Pet] :body Pet object that needs to be added to the store
# @return [nil]
def self.update_pet(opts = {})
# resource path # query parameters
path = "/pet".sub('{format}','json') query_params = {}
# query parameters # header parameters
query_params = {} header_params = {}
# header parameters # HTTP header 'Accept' (if needed)
header_params = {} _header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Accept' (if needed) # HTTP header 'Content-Type'
_header_accept = ['application/json', 'application/xml'] _header_content_type = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# HTTP header 'Content-Type' # form parameters
_header_content_type = ['application/json', 'application/xml'] form_params = {}
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters # http body (model)
form_params = {} post_body = Swagger::Request.object_to_http_body(opts[:'body'])
# http body (model) auth_names = ['petstore_auth']
post_body = Swagger::Request.object_to_http_body(opts[:'body']) Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Add a new pet to the store
#
# @param [Hash] opts the optional parameters
# @option opts [Pet] :body Pet object that needs to be added to the store
# @return [nil]
def self.add_pet(opts = {})
auth_names = ['petstore_auth'] # resource path
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make path = "/pet".sub('{format}','json')
nil
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = ['application/json', 'application/xml']
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Finds Pets by status
# Multiple status values can be provided with comma seperated strings
# @param [Hash] opts the optional parameters
# @option opts [array[string]] :status Status values that need to be considered for filter
# @return [array[Pet]]
def self.find_pets_by_status(opts = {})
# resource path
path = "/pet/findByStatus".sub('{format}','json')
# query parameters
query_params = {}
query_params[:'status'] = opts[:'status'] if opts[:'status']
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
response.map {|response| obj = Pet.new() and obj.build_from_hash(response) }
end
# Finds Pets by tags
# Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
# @param [Hash] opts the optional parameters
# @option opts [array[string]] :tags Tags to filter by
# @return [array[Pet]]
def self.find_pets_by_tags(opts = {})
# resource path
path = "/pet/findByTags".sub('{format}','json')
# query parameters
query_params = {}
query_params[:'tags'] = opts[:'tags'] if opts[:'tags']
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
response.map {|response| obj = Pet.new() and obj.build_from_hash(response) }
end
# Find pet by ID
# 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 [Hash] opts the optional parameters
# @return [Pet]
def self.get_pet_by_id(pet_id, opts = {})
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil?
# resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['api_key', 'petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = Pet.new() and obj.build_from_hash(response)
end
# Updates a pet in the store with form data
#
# @param pet_id ID of pet that needs to be updated
# @param [Hash] opts the optional parameters
# @option opts [string] :name Updated name of the pet
# @option opts [string] :status Updated status of the pet
# @return [nil]
def self.update_pet_with_form(pet_id, opts = {})
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil?
# resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = ['application/x-www-form-urlencoded']
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
form_params["name"] = opts[:'name'] if opts[:'name']
form_params["status"] = opts[:'status'] if opts[:'status']
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Deletes a pet
#
# @param pet_id Pet id to delete
# @param [Hash] opts the optional parameters
# @option opts [string] :api_key
# @return [nil]
def self.delete_pet(pet_id, opts = {})
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil?
# resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key']
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# uploads an image
#
# @param pet_id ID of pet to update
# @param [Hash] opts the optional parameters
# @option opts [string] :additional_metadata Additional data to pass to server
# @option opts [file] :file file to upload
# @return [nil]
def self.upload_file(pet_id, opts = {})
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil?
# resource path
path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = ['multipart/form-data']
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
form_params["additionalMetadata"] = opts[:'additional_metadata'] if opts[:'additional_metadata']
form_params["file"] = opts[:'file'] if opts[:'file']
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
end end
# Add a new pet to the store
#
# @param [Hash] opts the optional parameters
# @option opts [Pet] :body Pet object that needs to be added to the store
# @return [nil]
def self.add_pet(opts = {})
# resource path
path = "/pet".sub('{format}','json')
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = ['application/json', 'application/xml']
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Finds Pets by status
# Multiple status values can be provided with comma seperated strings
# @param [Hash] opts the optional parameters
# @option opts [array[string]] :status Status values that need to be considered for filter
# @return [array[Pet]]
def self.find_pets_by_status(opts = {})
# resource path
path = "/pet/findByStatus".sub('{format}','json')
# query parameters
query_params = {}
query_params[:'status'] = opts[:'status'] if opts[:'status']
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
response.map {|response| obj = Pet.new() and obj.build_from_hash(response) }
end
# Finds Pets by tags
# Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
# @param [Hash] opts the optional parameters
# @option opts [array[string]] :tags Tags to filter by
# @return [array[Pet]]
def self.find_pets_by_tags(opts = {})
# resource path
path = "/pet/findByTags".sub('{format}','json')
# query parameters
query_params = {}
query_params[:'tags'] = opts[:'tags'] if opts[:'tags']
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
response.map {|response| obj = Pet.new() and obj.build_from_hash(response) }
end
# Find pet by ID
# 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 [Hash] opts the optional parameters
# @return [Pet]
def self.get_pet_by_id(pet_id, opts = {})
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil?
# resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['api_key', 'petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = Pet.new() and obj.build_from_hash(response)
end
# Updates a pet in the store with form data
#
# @param pet_id ID of pet that needs to be updated
# @param [Hash] opts the optional parameters
# @option opts [string] :name Updated name of the pet
# @option opts [string] :status Updated status of the pet
# @return [nil]
def self.update_pet_with_form(pet_id, opts = {})
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil?
# resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = ['application/x-www-form-urlencoded']
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
form_params["name"] = opts[:'name'] if opts[:'name']
form_params["status"] = opts[:'status'] if opts[:'status']
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Deletes a pet
#
# @param pet_id Pet id to delete
# @param [Hash] opts the optional parameters
# @option opts [string] :api_key
# @return [nil]
def self.delete_pet(pet_id, opts = {})
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil?
# resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key']
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# uploads an image
#
# @param pet_id ID of pet to update
# @param [Hash] opts the optional parameters
# @option opts [string] :additional_metadata Additional data to pass to server
# @option opts [file] :file file to upload
# @return [nil]
def self.upload_file(pet_id, opts = {})
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil?
# resource path
path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = ['multipart/form-data']
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
form_params["additionalMetadata"] = opts[:'additional_metadata'] if opts[:'additional_metadata']
form_params["file"] = opts[:'file'] if opts[:'file']
# http body (model)
post_body = nil
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
end
end end

View File

@@ -1,161 +1,166 @@
require "uri" require "uri"
module SwaggerClient module SwaggerClient
class StoreApi class StoreApi
basePath = "http://petstore.swagger.io/v2" basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker # apiInvoker = APIInvoker
# Returns pet inventories by status
# Returns a map of status codes to quantities
# @param [Hash] opts the optional parameters
# @return [map[string,int]]
def self.get_inventory(opts = {})
# Returns pet inventories by status # resource path
# Returns a map of status codes to quantities path = "/store/inventory".sub('{format}','json')
# @param [Hash] opts the optional parameters
# @return [map[string,int]]
def self.get_inventory(opts = {})
# resource path # query parameters
path = "/store/inventory".sub('{format}','json') query_params = {}
# query parameters # header parameters
query_params = {} header_params = {}
# header parameters # HTTP header 'Accept' (if needed)
header_params = {} _header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Accept' (if needed) # HTTP header 'Content-Type'
_header_accept = ['application/json', 'application/xml'] _header_content_type = []
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# HTTP header 'Content-Type' # form parameters
_header_content_type = [] form_params = {}
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters # http body (model)
form_params = {} post_body = nil
# http body (model) auth_names = ['api_key']
post_body = nil response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
response.map {|response| obj = map.new() and obj.build_from_hash(response) }
end
# Place an order for a pet
#
# @param [Hash] opts the optional parameters
# @option opts [Order] :body order placed for purchasing the pet
# @return [Order]
def self.place_order(opts = {})
auth_names = ['api_key'] # resource path
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body path = "/store/order".sub('{format}','json')
response.map {|response| obj = map.new() and obj.build_from_hash(response) }
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = []
response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = Order.new() and obj.build_from_hash(response)
end
# Find purchase order by ID
# 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 [Hash] opts the optional parameters
# @return [Order]
def self.get_order_by_id(order_id, opts = {})
# verify the required parameter 'order_id' is set
raise "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil?
# resource path
path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = Order.new() and obj.build_from_hash(response)
end
# Delete purchase order by ID
# 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 [Hash] opts the optional parameters
# @return [nil]
def self.delete_order(order_id, opts = {})
# verify the required parameter 'order_id' is set
raise "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil?
# resource path
path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
end end
# Place an order for a pet
#
# @param [Hash] opts the optional parameters
# @option opts [Order] :body order placed for purchasing the pet
# @return [Order]
def self.place_order(opts = {})
# resource path
path = "/store/order".sub('{format}','json')
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = []
response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = Order.new() and obj.build_from_hash(response)
end
# Find purchase order by ID
# 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 [Hash] opts the optional parameters
# @return [Order]
def self.get_order_by_id(order_id, opts = {})
# verify the required parameter 'order_id' is set
raise "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil?
# resource path
path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = Order.new() and obj.build_from_hash(response)
end
# Delete purchase order by ID
# 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 [Hash] opts the optional parameters
# @return [nil]
def self.delete_order(order_id, opts = {})
# verify the required parameter 'order_id' is set
raise "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil?
# resource path
path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
end
end end

View File

@@ -1,316 +1,325 @@
require "uri" require "uri"
module SwaggerClient module SwaggerClient
class UserApi class UserApi
basePath = "http://petstore.swagger.io/v2" basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker # apiInvoker = APIInvoker
# Create user
# This can only be done by the logged in user.
# @param [Hash] opts the optional parameters
# @option opts [User] :body Created user object
# @return [nil]
def self.create_user(opts = {})
# Create user # resource path
# This can only be done by the logged in user. path = "/user".sub('{format}','json')
# @param [Hash] opts the optional parameters
# @option opts [User] :body Created user object
# @return [nil]
def self.create_user(opts = {})
# resource path # query parameters
path = "/user".sub('{format}','json') query_params = {}
# query parameters # header parameters
query_params = {} header_params = {}
# header parameters # HTTP header 'Accept' (if needed)
header_params = {} _header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Accept' (if needed) # HTTP header 'Content-Type'
_header_accept = ['application/json', 'application/xml'] _header_content_type = []
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# HTTP header 'Content-Type' # form parameters
_header_content_type = [] form_params = {}
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters # http body (model)
form_params = {} post_body = Swagger::Request.object_to_http_body(opts[:'body'])
# http body (model) auth_names = []
post_body = Swagger::Request.object_to_http_body(opts[:'body']) Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Creates list of users with given input array
#
# @param [Hash] opts the optional parameters
# @option opts [array[User]] :body List of user object
# @return [nil]
def self.create_users_with_array_input(opts = {})
auth_names = [] # resource path
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make path = "/user/createWithArray".sub('{format}','json')
nil
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = []
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Creates list of users with given input array
#
# @param [Hash] opts the optional parameters
# @option opts [array[User]] :body List of user object
# @return [nil]
def self.create_users_with_list_input(opts = {})
# resource path
path = "/user/createWithList".sub('{format}','json')
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = []
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Logs user into the system
#
# @param [Hash] opts the optional parameters
# @option opts [string] :username The user name for login
# @option opts [string] :password The password for login in clear text
# @return [string]
def self.login_user(opts = {})
# resource path
path = "/user/login".sub('{format}','json')
# query parameters
query_params = {}
query_params[:'username'] = opts[:'username'] if opts[:'username']
query_params[:'password'] = opts[:'password'] if opts[:'password']
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = string.new() and obj.build_from_hash(response)
end
# Logs out current logged in user session
#
# @param [Hash] opts the optional parameters
# @return [nil]
def self.logout_user(opts = {})
# resource path
path = "/user/logout".sub('{format}','json')
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Get user by user name
#
# @param username The name that needs to be fetched. Use user1 for testing.
# @param [Hash] opts the optional parameters
# @return [User]
def self.get_user_by_name(username, opts = {})
# verify the required parameter 'username' is set
raise "Missing the required parameter 'username' when calling get_user_by_name" if username.nil?
# resource path
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = User.new() and obj.build_from_hash(response)
end
# Updated user
# This can only be done by the logged in user.
# @param username name that need to be deleted
# @param [Hash] opts the optional parameters
# @option opts [User] :body Updated user object
# @return [nil]
def self.update_user(username, opts = {})
# verify the required parameter 'username' is set
raise "Missing the required parameter 'username' when calling update_user" if username.nil?
# resource path
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = []
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Delete user
# This can only be done by the logged in user.
# @param username The name that needs to be deleted
# @param [Hash] opts the optional parameters
# @return [nil]
def self.delete_user(username, opts = {})
# verify the required parameter 'username' is set
raise "Missing the required parameter 'username' when calling delete_user" if username.nil?
# resource path
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
end end
# Creates list of users with given input array
#
# @param [Hash] opts the optional parameters
# @option opts [array[User]] :body List of user object
# @return [nil]
def self.create_users_with_array_input(opts = {})
# resource path
path = "/user/createWithArray".sub('{format}','json')
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = []
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Creates list of users with given input array
#
# @param [Hash] opts the optional parameters
# @option opts [array[User]] :body List of user object
# @return [nil]
def self.create_users_with_list_input(opts = {})
# resource path
path = "/user/createWithList".sub('{format}','json')
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = []
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Logs user into the system
#
# @param [Hash] opts the optional parameters
# @option opts [string] :username The user name for login
# @option opts [string] :password The password for login in clear text
# @return [string]
def self.login_user(opts = {})
# resource path
path = "/user/login".sub('{format}','json')
# query parameters
query_params = {}
query_params[:'username'] = opts[:'username'] if opts[:'username']
query_params[:'password'] = opts[:'password'] if opts[:'password']
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = string.new() and obj.build_from_hash(response)
end
# Logs out current logged in user session
#
# @param [Hash] opts the optional parameters
# @return [nil]
def self.logout_user(opts = {})
# resource path
path = "/user/logout".sub('{format}','json')
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Get user by user name
#
# @param username The name that needs to be fetched. Use user1 for testing.
# @param [Hash] opts the optional parameters
# @return [User]
def self.get_user_by_name(username, opts = {})
# verify the required parameter 'username' is set
raise "Missing the required parameter 'username' when calling get_user_by_name" if username.nil?
# resource path
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
obj = User.new() and obj.build_from_hash(response)
end
# Updated user
# This can only be done by the logged in user.
# @param username name that need to be deleted
# @param [Hash] opts the optional parameters
# @option opts [User] :body Updated user object
# @return [nil]
def self.update_user(username, opts = {})
# verify the required parameter 'username' is set
raise "Missing the required parameter 'username' when calling update_user" if username.nil?
# resource path
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = []
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
end
# Delete user
# This can only be done by the logged in user.
# @param username The name that needs to be deleted
# @param [Hash] opts the optional parameters
# @return [nil]
def self.delete_user(username, opts = {})
# verify the required parameter 'username' is set
raise "Missing the required parameter 'username' when calling delete_user" if username.nil?
# resource path
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
_header_accept = ['application/json', 'application/xml']
_header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = []
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
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
{
# attribute type :'id' => :'int',
def self.swagger_types :'name' => :'string'
{ }
:'id' => :'int', end
:'name' => :'string'
def initialize(attributes = {})
} return if !attributes.is_a?(Hash) || attributes.empty?
end
# convert string to symbol for hash key
def initialize(attributes = {}) attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
return if !attributes.is_a?(Hash) || attributes.empty?
if attributes[:'id']
# convert string to symbol for hash key @id = attributes[:'id']
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} end
if attributes[:'name']
@name = attributes[:'name']
if attributes[:'id'] end
@id = attributes[:'id'] end
end end
if attributes[:'name']
@name = attributes[:'name']
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',
#
# :'ship_date' => :'shipDate',
:'quantity' => :'quantity', # Order Status
:'status' => :'status',
# #
:'ship_date' => :'shipDate', :'complete' => :'complete'
}
# Order Status end
:'status' => :'status',
# attribute type
# def self.swagger_types
:'complete' => :'complete' {
:'id' => :'int',
} :'pet_id' => :'int',
end :'quantity' => :'int',
:'ship_date' => :'DateTime',
# attribute type :'status' => :'string',
def self.swagger_types :'complete' => :'boolean'
{ }
:'id' => :'int', end
:'pet_id' => :'int',
:'quantity' => :'int', def initialize(attributes = {})
:'ship_date' => :'DateTime', return if !attributes.is_a?(Hash) || attributes.empty?
:'status' => :'string',
:'complete' => :'boolean' # convert string to symbol for hash key
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
}
end if attributes[:'id']
@id = attributes[:'id']
def initialize(attributes = {}) end
return if !attributes.is_a?(Hash) || attributes.empty? if attributes[:'petId']
@pet_id = attributes[:'petId']
# convert string to symbol for hash key end
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} if attributes[:'quantity']
@quantity = attributes[:'quantity']
end
if attributes[:'id'] if attributes[:'shipDate']
@id = attributes[:'id'] @ship_date = attributes[:'shipDate']
end end
if attributes[:'status']
if attributes[:'petId'] @status = attributes[:'status']
@pet_id = attributes[:'petId'] end
end if attributes[:'complete']
@complete = attributes[:'complete']
if attributes[:'quantity'] end
@quantity = attributes[:'quantity'] end
end end
if attributes[:'shipDate']
@ship_date = attributes[:'shipDate']
end
if attributes[:'status']
@status = attributes[:'status']
end
if attributes[:'complete']
@complete = attributes[:'complete']
end
end
end
end 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',
#
# :'photo_urls' => :'photoUrls',
:'name' => :'name', #
:'tags' => :'tags',
# # pet status in the store
:'photo_urls' => :'photoUrls', :'status' => :'status'
}
# end
:'tags' => :'tags',
# attribute type
# pet status in the store def self.swagger_types
:'status' => :'status' {
:'id' => :'int',
} :'category' => :'Category',
end :'name' => :'string',
:'photo_urls' => :'array[string]',
# attribute type :'tags' => :'array[Tag]',
def self.swagger_types :'status' => :'string'
{ }
:'id' => :'int', end
:'category' => :'Category',
:'name' => :'string', def initialize(attributes = {})
:'photo_urls' => :'array[string]', return if !attributes.is_a?(Hash) || attributes.empty?
:'tags' => :'array[Tag]',
:'status' => :'string' # convert string to symbol for hash key
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
}
end if attributes[:'id']
@id = attributes[:'id']
def initialize(attributes = {}) end
return if !attributes.is_a?(Hash) || attributes.empty? if attributes[:'category']
@category = attributes[:'category']
# convert string to symbol for hash key end
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} if attributes[:'name']
@name = attributes[:'name']
end
if attributes[:'id'] if attributes[:'photoUrls']
@id = attributes[:'id'] if (value = attributes[:'photoUrls']).is_a?(Array)
end @photo_urls = value
end
if attributes[:'category'] end
@category = attributes[:'category'] if attributes[:'tags']
end if (value = attributes[:'tags']).is_a?(Array)
@tags = value
if attributes[:'name'] end
@name = attributes[:'name'] end
end if attributes[:'status']
@status = attributes[:'status']
if attributes[:'photoUrls'] end
if (value = attributes[:'photoUrls']).is_a?(Array) end
@photo_urls = value end
end
end
if attributes[:'tags']
if (value = attributes[:'tags']).is_a?(Array)
@tags = value
end
end
if attributes[:'status']
@status = attributes[:'status']
end
end
end
end 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
{
# attribute type :'id' => :'int',
def self.swagger_types :'name' => :'string'
{ }
:'id' => :'int', end
:'name' => :'string'
def initialize(attributes = {})
} return if !attributes.is_a?(Hash) || attributes.empty?
end
# convert string to symbol for hash key
def initialize(attributes = {}) attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
return if !attributes.is_a?(Hash) || attributes.empty?
if attributes[:'id']
# convert string to symbol for hash key @id = attributes[:'id']
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} end
if attributes[:'name']
@name = attributes[:'name']
if attributes[:'id'] end
@id = attributes[:'id'] end
end end
if attributes[:'name']
@name = attributes[:'name']
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',
#
# :'last_name' => :'lastName',
:'first_name' => :'firstName', #
:'email' => :'email',
# #
:'last_name' => :'lastName', :'password' => :'password',
#
# :'phone' => :'phone',
:'email' => :'email', # User Status
:'user_status' => :'userStatus'
# }
:'password' => :'password', end
# # attribute type
:'phone' => :'phone', def self.swagger_types
{
# User Status :'id' => :'int',
:'user_status' => :'userStatus' :'username' => :'string',
:'first_name' => :'string',
} :'last_name' => :'string',
end :'email' => :'string',
:'password' => :'string',
# attribute type :'phone' => :'string',
def self.swagger_types :'user_status' => :'int'
{ }
:'id' => :'int', end
:'username' => :'string',
:'first_name' => :'string', def initialize(attributes = {})
:'last_name' => :'string', return if !attributes.is_a?(Hash) || attributes.empty?
:'email' => :'string',
:'password' => :'string', # convert string to symbol for hash key
:'phone' => :'string', attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
:'user_status' => :'int'
if attributes[:'id']
} @id = attributes[:'id']
end end
if attributes[:'username']
def initialize(attributes = {}) @username = attributes[:'username']
return if !attributes.is_a?(Hash) || attributes.empty? end
if attributes[:'firstName']
# convert string to symbol for hash key @first_name = attributes[:'firstName']
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} end
if attributes[:'lastName']
@last_name = attributes[:'lastName']
if attributes[:'id'] end
@id = attributes[:'id'] if attributes[:'email']
end @email = attributes[:'email']
end
if attributes[:'username'] if attributes[:'password']
@username = attributes[:'username'] @password = attributes[:'password']
end end
if attributes[:'phone']
if attributes[:'firstName'] @phone = attributes[:'phone']
@first_name = attributes[:'firstName'] end
end if attributes[:'userStatus']
@user_status = attributes[:'userStatus']
if attributes[:'lastName'] end
@last_name = attributes[:'lastName'] end
end end
if attributes[:'email']
@email = attributes[:'email']
end
if attributes[:'password']
@password = attributes[:'password']
end
if attributes[:'phone']
@phone = attributes[:'phone']
end
if attributes[:'userStatus']
@user_status = attributes[:'userStatus']
end
end
end
end end

View File

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