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;
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>
/// <returns>Dictionary<String, int?></returns>
Dictionary<String, int?> GetInventory ();
///
<summary>
/// Returns pet inventories by status Returns a map of status codes to quantities
///
</summary>
///
<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>
/// <param name="Body">order placed for purchasing the pet</param>
/// <returns>Order</returns>
Order PlaceOrder (Order Body);
///
<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>
Order GetOrderById (string OrderId);
/// <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>
/// 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>
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>
/// <param name="OrderId">ID of pet that needs to be fetched</param>
/// <returns>Order</returns>
Order GetOrderById (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>
/// 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>
Task<Order> GetOrderByIdAsync (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>
/// 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>
/// <returns></returns>
///
<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>
///
<returns></returns>
public StoreApi(String basePath)
{
this.apiClient = new ApiClient(basePath);
this.apiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
///
<summary>
/// Sets the base path of the API client.
///
</summary>
///
<value>The base path</value>
public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath;
this.apiClient.basePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
///
<summary>
/// Gets the base path of the API client.
///
</summary>
///
<value>The base path</value>
public String GetBasePath(String basePath) {
return this.apiClient.basePath;
return this.apiClient.basePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>The API client</value>
///
<summary>
/// Gets or sets the API client.
///
</summary>
///
<value>The API client</value>
public ApiClient apiClient {get; set;}
/// <summary>
/// Returns pet inventories by status Returns a map of status codes to quantities
/// </summary>
/// <returns>Dictionary<String, int?></returns>
public Dictionary<String, int?> GetInventory () {
///
<summary>
/// Returns pet inventories by status Returns a map of status codes to quantities
///
</summary>
///
<returns>Dictionary<String, int?></returns>
public Dictionary<String, int?> GetInventory () {
var path = "/store/inventory";
path = path.Replace("{format}", "json");
var path = "/store/inventory";
path = path.Replace("{format}", "json");
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;
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" };
// authentication setting, if any
String[] authSettings = new String[] { "api_key" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
// make the HTTP request
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);
}
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 () {
}
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 () {
var path = "/store/inventory";
path = path.Replace("{format}", "json");
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;
var path = "/store/inventory";
path = path.Replace("{format}", "json");
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
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
// authentication setting, if any
String[] authSettings = new String[] { "api_key" };
// 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);
}
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>
/// <param name="Body">order placed for purchasing the pet</param>
/// <returns>Order</returns>
public 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>
public Order PlaceOrder (Order Body) {
var path = "/store/order";
path = path.Replace("{format}", "json");
var path = "/store/order";
path = path.Replace("{format}", "json");
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;
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;
postBody = apiClient.Serialize(Body); // http body (model) parameter
postBody = apiClient.Serialize(Body); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
// make the HTTP request
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);
}
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) {
}
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) {
var path = "/store/order";
path = path.Replace("{format}", "json");
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;
var path = "/store/order";
path = path.Replace("{format}", "json");
postBody = apiClient.Serialize(Body); // http body (model) parameter
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[] { };
postBody = apiClient.Serialize(Body); // http body (model) parameter
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
// authentication setting, if any
String[] authSettings = new String[] { };
// 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);
}
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>
/// <param name="OrderId">ID of pet that needs to be fetched</param>
/// <returns>Order</returns>
public Order GetOrderById (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>
///
<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
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById");
// verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById");
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
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;
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[] { };
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
// make the HTTP request
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);
}
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) {
}
return (Order) apiClient.Deserialize(response.Content, typeof(Order));
}
// verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById");
///
<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) {
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
// verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById");
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;
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
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
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
// authentication setting, if any
String[] authSettings = new String[] { };
// 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);
}
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>
/// <param name="OrderId">ID of the order that needs to be deleted</param>
/// <returns></returns>
public 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>
public void DeleteOrder (string OrderId) {
// verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder");
// verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder");
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
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;
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[] { };
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
// make the HTTP request
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);
}
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) {
}
return;
}
// verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder");
///
<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) {
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
// verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder");
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;
var path = "/store/order/{orderId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "orderId" + "}", apiClient.ParameterToString(OrderId));
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
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
// authentication setting, if any
String[] authSettings = new String[] { };
// 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);
}
return;
}
}
return;
}
}
}
}

View File

@ -5,50 +5,58 @@ using System.Collections.Generic;
using System.Runtime.Serialization;
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 Newtonsoft.Json;
namespace IO.Swagger.Model {
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class Order {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
///
<summary>
///
///
</summary>
[DataContract]
public class Order {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="petId", EmitDefaultValue=false)]
public long? PetId { get; set; }
[DataMember(Name="petId", EmitDefaultValue=false)]
public long? PetId { get; set; }
[DataMember(Name="quantity", EmitDefaultValue=false)]
public int? Quantity { get; set; }
[DataMember(Name="quantity", EmitDefaultValue=false)]
public int? Quantity { get; set; }
[DataMember(Name="shipDate", EmitDefaultValue=false)]
public DateTime? ShipDate { get; set; }
[DataMember(Name="shipDate", EmitDefaultValue=false)]
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 Newtonsoft.Json;
namespace IO.Swagger.Model {
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class Pet {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
///
<summary>
///
///
</summary>
[DataContract]
public class Pet {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="category", EmitDefaultValue=false)]
public Category Category { get; set; }
[DataMember(Name="category", EmitDefaultValue=false)]
public Category Category { get; set; }
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
[DataMember(Name="photoUrls", EmitDefaultValue=false)]
public List<string> PhotoUrls { get; set; }
[DataMember(Name="photoUrls", EmitDefaultValue=false)]
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 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 Newtonsoft.Json;
namespace IO.Swagger.Model {
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class User {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
///
<summary>
///
///
</summary>
[DataContract]
public class User {
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
[DataMember(Name="username", EmitDefaultValue=false)]
public string Username { get; set; }
[DataMember(Name="username", EmitDefaultValue=false)]
public string Username { get; set; }
[DataMember(Name="firstName", EmitDefaultValue=false)]
public string FirstName { get; set; }
[DataMember(Name="firstName", EmitDefaultValue=false)]
public string FirstName { get; set; }
[DataMember(Name="lastName", EmitDefaultValue=false)]
public string LastName { get; set; }
[DataMember(Name="lastName", EmitDefaultValue=false)]
public string LastName { get; set; }
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
[DataMember(Name="password", EmitDefaultValue=false)]
public string Password { get; set; }
[DataMember(Name="password", EmitDefaultValue=false)]
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;
namespace IO.Swagger.Client {
/// <summary>
/// API client is mainly responible for making the HTTP call to the API backend
/// </summary>
public class ApiClient {
///
<summary>
/// API client is mainly responible for making the HTTP call to the API backend
///
</summary>
public class ApiClient {
/// <summary>
/// Initializes a new instance of the <see cref="ApiClient"/> class.
/// </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>
/// Initializes a new instance of the
<see cref="ApiClient"/>
class.
///
</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.
/// </summary>
/// <value>The base path.</value>
public string basePath { get; set; }
///
</summary>
///
<value>The base path.</value>
public string basePath { get; set; }
/// <summary>
///
<summary>
/// Gets or sets the RestClient
/// </summary>
/// <value>The RestClient.</value>
public RestClient restClient { get; set; }
///
</summary>
///
<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,
Dictionary<String, String> HeaderParams, Dictionary<String, String> FormParams, Dictionary<String, String> FileParams, String[] AuthSettings) {
var response = Task.Run(async () => {
var resp = await CallApiAsync(Path, Method, QueryParams, PostBody, HeaderParams, FormParams, FileParams, AuthSettings);
return resp;
});
return response.Result;
public Object CallApi(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 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,
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);
return (Object) await restClient.ExecuteTaskAsync(request);
}
/// <summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name
/// <param name="value"> Header field value
/// <returns></returns>
///
<summary>
/// Add default header
///
</summary>
///
<param name="key">
Header field name
///
<param name="value">
Header field value
///
<returns></returns>
public void AddDefaultHeader(string key, string value) {
defaultHeaderMap.Add(key, value);
defaultHeaderMap.Add(key, value);
}
/// <summary>
/// Get default header
/// </summary>
/// <returns>Dictionary of default header</returns>
public Dictionary<String, String> GetDefaultHeader() {
return defaultHeaderMap;
///
<summary>
/// Get default header
///
</summary>
///
<returns>Dictionary of default header</returns>
public Dictionary
<String
, String> GetDefaultHeader() {
return defaultHeaderMap;
}
/// <summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str"> String to be escaped
/// <returns>Escaped string</returns>
///
<summary>
/// escape string (url-encoded)
///
</summary>
///
<param name="str">
String to be escaped
///
<returns>Escaped string</returns>
public string EscapeString(string str) {
return str;
return str;
}
/// <summary>
/// if parameter is DateTime, output in ISO8601 format
/// if parameter is a list of string, join the list with ","
/// otherwise just return the string
/// </summary>
/// <param name="obj"> The parameter (header, path, query, form)
/// <returns>Formatted string</returns>
///
<summary>
/// if parameter is DateTime, output in ISO8601 format
/// if parameter is a list of string, join the list with ","
/// otherwise just return the string
///
</summary>
///
<param name="obj">
The parameter (header, path, query, form)
///
<returns>Formatted string</returns>
public string ParameterToString(object obj)
{
if (obj is DateTime) {
return ((DateTime)obj).ToString ("u");
} else if (obj is List<string>) {
return String.Join(",", obj as List<string>);
} else {
return Convert.ToString (obj);
}
}
if (obj is DateTime) {
return ((DateTime)obj).ToString ("u");
} else if (obj is List
<string>) {
return String.Join(",", obj as List
<string>);
} else {
return Convert.ToString (obj);
}
}
/// <summary>
/// Deserialize the JSON string into a proper object
/// </summary>
/// <param name="json"> JSON string
/// <param name="type"> Object type
/// <returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type) {
if (type.GetType() == typeof(Object))
return (Object)content;
///
<summary>
/// Deserialize the JSON string into a proper object
///
</summary>
///
<param name="json">
JSON string
///
<param name="type">
Object type
///
<returns>Object representation of the JSON string</returns>
public object Deserialize(string content, Type type) {
if (type.GetType() == typeof(Object))
return (Object)content;
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (IOException e) {
throw new ApiException(500, e.Message);
}
}
try
{
return JsonConvert.DeserializeObject(content, type);
}
catch (IOException e) {
throw new ApiException(500, e.Message);
}
}
/// <summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj"> Object
/// <returns>JSON string</returns>
public string Serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
///
<summary>
/// Serialize an object into JSON string
///
</summary>
///
<param name="obj">
Object
///
<returns>JSON string</returns>
public string Serialize(object obj) {
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>
/// <param name="obj"> Object
/// <returns>API key with prefix</returns>
public string GetApiKeyWithPrefix (string apiKey)
{
var apiKeyValue = "";
Configuration.apiKey.TryGetValue (apiKey, out apiKeyValue);
var apiKeyPrefix = "";
if (Configuration.apiKeyPrefix.TryGetValue (apiKey, out apiKeyPrefix)) {
return apiKeyPrefix + " " + apiKeyValue;
} else {
return apiKeyValue;
}
}
///
<summary>
/// Get the API key with prefix
///
</summary>
///
<param name="obj">
Object
///
<returns>API key with prefix</returns>
public string GetApiKeyWithPrefix (string apiKey)
{
var 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>
/// <param name="QueryParams">Query parameters</param>
/// <param name="HeaderParams">Header parameters</param>
/// <param name="AuthSettings">Authentication settings</param>
public void UpdateParamsForAuth(Dictionary<String, String> QueryParams, Dictionary<String, String> HeaderParams, string[] AuthSettings) {
if (AuthSettings == null || AuthSettings.Length == 0)
return;
foreach (string auth in AuthSettings) {
// determine which one to use
switch(auth) {
case "api_key":
HeaderParams["api_key"] = GetApiKeyWithPrefix("api_key");
///
<summary>
/// Update parameters based on authentication
///
</summary>
///
<param name="QueryParams">
Query parameters</param>
///
<param name="HeaderParams">
Header parameters</param>
///
<param name="AuthSettings">
Authentication settings</param>
public void UpdateParamsForAuth(Dictionary
<String
, String> QueryParams, Dictionary
<String
, String> HeaderParams, string[] AuthSettings) {
if (AuthSettings == null || AuthSettings.Length == 0)
return;
foreach (string auth in AuthSettings) {
// determine which one to use
switch(auth) {
break;
case "petstore_auth":
case "api_key":
HeaderParams["api_key"] = GetApiKeyWithPrefix("api_key
");
break;
//TODO support oauth
break;
default:
case "petstore_auth":
//TODO support oauth
break;
default:
//TODO show warning about security definition not found
break;
}
}
break;
}
}
}
}
/// <summary>
/// Encode string in base64 format
/// </summary>
/// <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);
}
///
<summary>
/// Encode string in base64 format
///
</summary>
///
<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;
namespace IO.Swagger.Client {
/// <summary>
/// API Exception
/// </summary>
public class ApiException : Exception {
/// <summary>
///
<summary>
/// API Exception
///
</summary>
public class ApiException : Exception {
///
<summary>
/// Gets or sets the error code (HTTP status code)
/// </summary>
/// <value>The error code (HTTP status code).</value>
public int ErrorCode { get; set; }
///
</summary>
///
<value>The error code (HTTP status code).</value>
public int ErrorCode { get; set; }
/// <summary>
///
<summary>
/// Gets or sets the error content (body json object)
/// </summary>
/// <value>The error content (Http response body).</value>
public dynamic ErrorContent { get; private set; }
///
</summary>
///
<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>
/// <param name="basePath">The base path.</param>
public ApiException() {}
///
<summary>
/// Initializes a new instance of the
<see cref="ApiException"/>
class.
///
</summary>
///
<param name="basePath">The base path.</param>
public ApiException() {}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </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;
}
///
<summary>
/// Initializes a new instance of the
<see cref="ApiException"/>
class.
///
</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) {
this.ErrorCode = errorCode;
this.ErrorContent = errorContent;
}
}
public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) {
this.ErrorCode = errorCode;
this.ErrorContent = errorContent;
}
}
}

View File

@ -7,41 +7,62 @@ using System.Text;
using IO.Swagger.Client;
namespace IO.Swagger.Client {
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration{
///
<summary>
/// Represents a set of configuration settings
///
</summary>
public class Configuration{
/// <summary>
///
<summary>
/// Gets or sets the API client. This is the default API client for making HTTP calls.
/// </summary>
/// <value>The API client.</value>
public static ApiClient apiClient = new ApiClient();
///
</summary>
///
<value>The API client.</value>
public static ApiClient apiClient = new ApiClient();
/// <summary>
///
<summary>
/// Gets or sets the username (HTTP basic authentication)
/// </summary>
/// <value>The username.</value>
public static String username { get; set; }
///
</summary>
///
<value>The username.</value>
public static String username { get; set; }
/// <summary>
///
<summary>
/// Gets or sets the password (HTTP basic authentication)
/// </summary>
/// <value>The password.</value>
public static String password { get; set; }
///
</summary>
///
<value>The password.</value>
public static String password { get; set; }
/// <summary>
/// Gets or sets the API key based on the authentication name
/// </summary>
/// <value>The API key.</value>
public static Dictionary<String, String> apiKey = new Dictionary<String, String>();
///
<summary>
/// Gets or sets the API key based on the authentication name
///
</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>
/// <value>The prefix of the API key.</value>
public static Dictionary<String, String> apiKeyPrefix = new Dictionary<String, String>();
///
<summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name
///
</summary>
///
<value>The prefix of the API key.</value>
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"
@protocol SWGCategory
@end
@interface SWGCategory : SWGObject
@protocol SWGCategory
@end
@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
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }];
}
@implementation SWGCategory
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
NSArray *optionalProperties = @[@"_id", @"name"];
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }];
}
if ([optionalProperties containsObject:propertyName]) {
return YES;
}
else {
return NO;
}
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
NSArray *optionalProperties = @[@"_id", @"name"];
@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
/**
* Api key values for Api Key type Authentication
*
* To add or remove api key, use `setValue:forApiKeyField:`.
*/
* Api key values for Api Key type Authentication
*
* To add or remove api key, use `setValue:forApiKeyField:`.
*/
@property (readonly, nonatomic, strong) NSDictionary *apiKey;
/**
* Api key prefix values to be prepend to the respective api key
*
* To add or remove prefix, use `setValue:forApiKeyPrefixField:`.
*/
* Api key prefix values to be prepend to the respective api key
*
* To add or remove prefix, use `setValue:forApiKeyPrefixField:`.
*/
@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 *password;
/**
* Get configuration singleton instance
*/
* Get configuration singleton instance
*/
+ (instancetype) sharedConfig;
/**
* Sets field in `apiKey`
*/
* Sets field in `apiKey`
*/
- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field;
/**
* Sets field in `apiKeyPrefix`
*/
* Sets field in `apiKeyPrefix`
*/
- (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;
/**
* Get Basic Auth token
*/
* Get Basic Auth token
*/
- (NSString *) getBasicAuthToken;
/**
* Get Authentication Setings
*/
* Get Authentication Setings
*/
- (NSDictionary *) authSettings;
@end

View File

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

View File

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

View File

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

View File

@ -1,22 +1,24 @@
#import "SWGPet.h"
#import "SWGPet.h"
@implementation SWGPet
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }];
}
@implementation SWGPet
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"];
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }];
}
if ([optionalProperties containsObject:propertyName]) {
return YES;
}
else {
return NO;
}
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
NSArray *optionalProperties = @[@"_id", @"category", @"tags", @"status"];
@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 "SWGFile.h"
#import "SWGObject.h"
#import "SWGApiClient.h"
@interface SWGPetApi: NSObject
@interface SWGPetApi: NSObject
@property(nonatomic, assign)SWGApiClient *apiClient;
@property(nonatomic, assign)SWGApiClient *apiClient;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize;
+(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath;
/**
Update an existing pet
@param body Pet object that needs to be added to the store
return type:
*/
-(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize;
+(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath;
/**
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
Multiple status values can be provided with comma seperated strings
return type: NSArray<SWGPet>*
*/
-(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
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
return type:
*/
-(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
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
return type:
*/
-(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

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 "SWGObject.h"
#import "SWGApiClient.h"
@interface SWGStoreApi: NSObject
@interface SWGStoreApi: NSObject
@property(nonatomic, assign)SWGApiClient *apiClient;
@property(nonatomic, assign)SWGApiClient *apiClient;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize;
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath;
+(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;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize;
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath;
/**
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
For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
return type: SWGOrder*
*/
-(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

View File

@ -1,478 +1,478 @@
#import "SWGStoreApi.h"
#import "SWGFile.h"
#import "SWGQueryParamCollection.h"
#import "SWGOrder.h"
#import "SWGStoreApi.h"
#import "SWGFile.h"
#import "SWGQueryParamCollection.h"
#import "SWGOrder.h"
@interface SWGStoreApi ()
@interface SWGStoreApi ()
@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];
if (self) {
self.apiClient = [SWGApiClient sharedClientFromPool:basePath];
self.defaultHeaders = [NSMutableDictionary dictionary];
self.apiClient = [SWGApiClient sharedClientFromPool:basePath];
self.defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
}
- (id) initWithApiClient:(SWGApiClient *)apiClient {
- (id) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init];
if (self) {
if (apiClient) {
self.apiClient = apiClient;
}
else {
self.apiClient = [SWGApiClient sharedClientFromPool:basePath];
}
self.defaultHeaders = [NSMutableDictionary dictionary];
if (apiClient) {
self.apiClient = apiClient;
}
else {
self.apiClient = [SWGApiClient sharedClientFromPool:basePath];
}
self.defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
}
#pragma mark -
#pragma mark -
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {
+(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key {
static SWGStoreApi* singletonAPI = nil;
if (singletonAPI == nil) {
singletonAPI = [[SWGStoreApi alloc] init];
[singletonAPI addHeader:headerValue forKey:key];
singletonAPI = [[SWGStoreApi alloc] init];
[singletonAPI addHeader:headerValue forKey:key];
}
return singletonAPI;
}
}
+(void) setBasePath:(NSString*)path {
+(void) setBasePath:(NSString*)path {
basePath = path;
}
}
+(NSString*) getBasePath {
+(NSString*) getBasePath {
return basePath;
}
}
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
}
}
-(void) setHeaderValue:(NSString*) value
forKey:(NSString*)key {
-(void) setHeaderValue:(NSString*) value
forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
}
}
-(unsigned long) requestQueueSize {
-(unsigned long) requestQueueSize {
return [SWGApiClient requestQueueSize];
}
}
/*!
* Returns pet inventories by status
* Returns a map of status codes to quantities
* \returns NSDictionary*
*/
-(NSNumber*) getInventoryWithCompletionBlock:
/*!
* Returns pet inventories by status
* Returns a map of status codes to quantities
* \returns NSDictionary*
*/
-(NSNumber*) getInventoryWithCompletionBlock:
(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
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
// remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
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) {
// 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"]) {
// response content type
NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
}
else {
}
else {
responseContentType = @"";
}
}
// request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting
NSArray *authSettings = @[@"api_key"];
id bodyDictionary = nil;
// Authentication setting
NSArray *authSettings = @[@"api_key"];
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
{
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath];
NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath];
// remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
// remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init];
NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders];
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) {
// 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"]) {
// response content type
NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
}
else {
}
else {
responseContentType = @"";
}
}
// request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting
NSArray *authSettings = @[];
id bodyDictionary = nil;
id __body = body;
// Authentication setting
NSArray *authSettings = @[];
if(__body != nil && [__body isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] init];
for (id dict in (NSArray*)__body) {
id bodyDictionary = nil;
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)]) {
[objs addObject:[(SWGObject*)dict toDictionary]];
[objs addObject:[(SWGObject*)dict toDictionary]];
}
else{
[objs addObject:dict];
[objs addObject:dict];
}
}
bodyDictionary = objs;
}
else if([__body respondsToSelector:@selector(toDictionary)]) {
bodyDictionary = [(SWGObject*)__body toDictionary];
}
else if([__body isKindOfClass:[NSString class]]) {
// convert it to a dictionary
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
}
bodyDictionary = objs;
}
else if([__body respondsToSelector:@selector(toDictionary)]) {
bodyDictionary = [(SWGObject*)__body toDictionary];
}
else if([__body isKindOfClass:[NSString class]]) {
// convert it to a dictionary
NSError * error;
NSString * str = (NSString*)__body;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
// non container response
// complex response
options: NSJSONReadingMutableContainers
error: &error];
bodyDictionary = JSON;
}
// comples response type
// non container response
// complex response
// comples response type
return [self.apiClient dictionary: requestUrl
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
SWGOrder* result = nil;
if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
method: @"POST"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
completionBlock(nil, error);
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*
*/
-(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId
/*!
* 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*
*/
-(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock
{
// verify the required parameter 'orderId' is set
NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling getOrderById");
// verify the required parameter 'orderId' is set
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
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
// remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"];
[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
[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]];
// 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
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;
}
SWGOrder* result = nil;
if (data) {
result = [[SWGOrder alloc] initWithDictionary:data error:nil];
}
completionBlock(result , nil);
}];
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;
}
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
*/
-(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId
/*!
* 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
*/
-(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId
completionHandler: (void (^)(NSError* error))completionBlock {
// verify the required parameter 'orderId' is set
NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling deleteOrder");
// verify the required parameter 'orderId' is set
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
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
// remove format in URL if needed
if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound)
[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];
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) {
// 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"]) {
// response content type
NSString *responseContentType;
if ([headerParams objectForKey:@"Accept"]) {
responseContentType = [headerParams[@"Accept"] componentsSeparatedByString:@", "][0];
}
else {
}
else {
responseContentType = @"";
}
}
// request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// request content type
NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]];
// Authentication setting
NSArray *authSettings = @[];
id bodyDictionary = nil;
// Authentication setting
NSArray *authSettings = @[];
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

View File

@ -1,15 +1,21 @@
#import <Foundation/Foundation.h>
#import
<Foundation/Foundation.h>
#import "SWGObject.h"
@protocol SWGTag
@end
@interface SWGTag : SWGObject
@protocol SWGTag
@end
@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
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }];
}
@implementation SWGTag
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
NSArray *optionalProperties = @[@"_id", @"name"];
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }];
}
if ([optionalProperties containsObject:propertyName]) {
return YES;
}
else {
return NO;
}
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
NSArray *optionalProperties = @[@"_id", @"name"];
@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"
@protocol SWGUser
@end
@interface SWGUser : SWGObject
@protocol SWGUser
@end
@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;
@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
@end

View File

@ -1,22 +1,24 @@
#import "SWGUser.h"
#import "SWGUser.h"
@implementation SWGUser
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }];
}
@implementation SWGUser
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"];
+ (JSONKeyMapper *)keyMapper
{
return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }];
}
if ([optionalProperties containsObject:propertyName]) {
return YES;
}
else {
return NO;
}
}
+ (BOOL)propertyIsOptional:(NSString *)propertyName
{
NSArray *optionalProperties = @[@"_id", @"username", @"firstName", @"lastName", @"email", @"password", @"phone", @"userStatus"];
@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 "SWGObject.h"
#import "SWGApiClient.h"
@interface SWGUserApi: NSObject
@interface SWGUserApi: NSObject
@property(nonatomic, assign)SWGApiClient *apiClient;
@property(nonatomic, assign)SWGApiClient *apiClient;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize;
+(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath;
+(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
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key;
-(unsigned long) requestQueueSize;
+(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key;
+(void) setBasePath:(NSString*)basePath;
+(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
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

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -43,412 +43,409 @@ class ApiClient {
function __construct($host = null) {
if ($host === null) {
$this->host = 'http://petstore.swagger.io/v2';
} else {
$this->host = $host;
}
}
} else {
$this->host = $host;
}
}
/**
* add default header
*
* @param string $header_name header name (e.g. Token)
* @param string $header_value header value (e.g. 1z8wp3)
*/
public function addDefaultHeader($header_name, $header_value) {
if (!is_string($header_name))
throw new \InvalidArgumentException('Header name must be a string.');
/**
* add default header
*
* @param string $header_name header name (e.g. Token)
* @param string $header_value header value (e.g. 1z8wp3)
*/
public function addDefaultHeader($header_name, $header_value) {
if (!is_string($header_name))
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
*
* @return array default header
*/
public function getDefaultHeader() {
return self::$default_header;
}
/**
* get the default header
*
* @return array default header
*/
public function getDefaultHeader() {
return self::$default_header;
}
/**
* delete the default header based on header name
*
* @param string $header_name header name (e.g. Token)
*/
public function deleteDefaultHeader($header_name) {
unset(self::$default_header[$header_name]);
}
/**
* delete the default header based on header name
*
* @param string $header_name header name (e.g. Token)
*/
public function deleteDefaultHeader($header_name) {
unset(self::$default_header[$header_name]);
}
/**
* set the user agent of the api client
*
* @param string $user_agent the user agent of the api client
*/
public function setUserAgent($user_agent) {
if (!is_string($user_agent))
throw new \InvalidArgumentException('User-agent must be a string.');
/**
* set the user agent of the api client
*
* @param string $user_agent the user agent of the api client
*/
public function setUserAgent($user_agent) {
if (!is_string($user_agent))
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
*
* @return string user agent
*/
public function getUserAgent($user_agent) {
return $this->user_agent;
}
/**
* get the user agent of the api client
*
* @return string user agent
*/
public function getUserAgent($user_agent) {
return $this->user_agent;
}
/**
* set the HTTP timeout value
*
* @param integer $seconds Number of seconds before timing out [set to 0 for no timeout]
*/
public function setTimeout($seconds) {
if (!is_numeric($seconds) || $seconds < 0)
throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.');
/**
* set the HTTP timeout value
*
* @param integer $seconds Number of seconds before timing out [set to 0 for no timeout]
*/
public function setTimeout($seconds) {
if (!is_numeric($seconds) || $seconds < 0)
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
*
* @return string HTTP timeout value
*/
public function getTimeout() {
return $this->curl_timeout;
}
/**
* get the HTTP timeout value
*
* @return string HTTP timeout value
*/
public function getTimeout() {
return $this->curl_timeout;
}
/**
* Get API key (with prefix if set)
* @param string key name
* @return string API key with the prefix
*/
public function getApiKeyWithPrefix($apiKey) {
if (isset(Configuration::$apiKeyPrefix[$apiKey])) {
return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey];
} else if (isset(Configuration::$apiKey[$apiKey])) {
return Configuration::$apiKey[$apiKey];
} else {
return;
}
}
/**
* Get API key (with prefix if set)
* @param string key name
* @return string API key with the prefix
*/
public function getApiKeyWithPrefix($apiKey) {
if (isset(Configuration::$apiKeyPrefix[$apiKey])) {
return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey];
} else if (isset(Configuration::$apiKey[$apiKey])) {
return Configuration::$apiKey[$apiKey];
} else {
return;
}
}
/**
* update hearder and query param based on authentication setting
*
* @param array $headerParams header parameters (by ref)
* @param array $queryParams query parameters (by ref)
* @param array $authSettings array of authentication scheme (e.g ['api_key'])
*/
public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings)
{
if (count($authSettings) == 0)
return;
/**
* update hearder and query param based on authentication setting
*
* @param array $headerParams header parameters (by ref)
* @param array $queryParams query parameters (by ref)
* @param array $authSettings array of authentication scheme (e.g ['api_key'])
*/
public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings)
{
if (count($authSettings) == 0)
return;
// one endpoint can have more than 1 auth settings
foreach($authSettings as $auth) {
// determine which one to use
switch($auth) {
case 'api_key':
$headerParams['api_key'] = $this->getApiKeyWithPrefix('api_key');
break;
case 'petstore_auth':
//TODO support oauth
break;
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) {
// one endpoint can have more than 1 auth settings
foreach($authSettings as $auth) {
// determine which one to use
switch($auth) {
case 'api_key':
$headerParams['api_key'] = $this->getApiKeyWithPrefix('api_key');
break;
case 'petstore_auth':
//TODO support oauth
break;
default:
//TODO show warning about security definition not found
}
}
}
$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
$this->updateParamsForAuth($headerParams, $queryParams, $authSettings);
$headers = array();
# construct the http header
$headerParams = array_merge((array)self::$default_header, (array)$headerParams);
# determine authentication setting
$this->updateParamsForAuth($headerParams, $queryParams, $authSettings);
foreach ($headerParams as $key => $val) {
$headers[] = "$key: $val";
}
# construct the http header
$headerParams = array_merge((array)self::$default_header, (array)$headerParams);
// 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));
}
foreach ($headerParams as $key => $val) {
$headers[] = "$key: $val";
}
$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();
// 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);
$url = $this->host . $resourcePath;
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)) {
$url = ($url . '?' . http_build_query($queryParams));
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
if ($method == self::$POST) {
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method == self::$PATCH) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method == self::$PUT) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method == self::$DELETE) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
} else if ($method != self::$GET) {
throw new ApiException('Method ' . $method . ' is not recognized.');
}
curl_setopt($curl, CURLOPT_URL, $url);
if (! empty($queryParams)) {
$url = ($url . '?' . http_build_query($queryParams));
}
// Set user agent
curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
if ($method == self::$POST) {
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
if (Configuration::$debug) {
error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file);
// Set user agent
curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a'));
} else {
curl_setopt($curl, CURLOPT_VERBOSE, 0);
}
// debugging for curl
if (Configuration::$debug) {
error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, Configuration::$debug_file);
// obtain the HTTP response headers
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_STDERR, fopen(Configuration::$debug_file, 'a'));
} else {
curl_setopt($curl, CURLOPT_VERBOSE, 0);
}
// Make the request
$response = curl_exec($curl);
$http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$http_header = substr($response, 0, $http_header_size);
$http_body = substr($response, $http_header_size);
$response_info = curl_getinfo($curl);
// obtain the HTTP response headers
curl_setopt($curl, CURLOPT_HEADER, 1);
// debug HTTP response body
if (Configuration::$debug) {
error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file);
}
// Make the request
$response = curl_exec($curl);
$http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$http_header = substr($response, 0, $http_header_size);
$http_body = substr($response, $http_header_size);
$response_info = curl_getinfo($curl);
// Handle the response
if ($response_info['http_code'] == 0) {
throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null);
} else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) {
$data = json_decode($http_body);
if (json_last_error() > 0) { // if response is a string
$data = $http_body;
}
} else {
throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)",
$response_info['http_code'], $http_header, $http_body);
}
return $data;
}
// debug HTTP response body
if (Configuration::$debug) {
error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, Configuration::$debug_file);
}
/**
* 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;
}
// Handle the response
if ($response_info['http_code'] == 0) {
throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null);
} else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) {
$data = json_decode($http_body);
if (json_last_error() > 0) { // if response is a string
$data = $http_body;
}
} else {
throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)",
$response_info['http_code'], $http_header, $http_body);
}
return $data;
}
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;
}
/**
* 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));
}
return $sanitized;
}
/**
* Take value and turn it into a string suitable for inclusion in
* the query, by imploding comma-separated if it's an object.
* If it's a string, pass through unchanged. It will be url-encoded
* later.
* @param object $object an object to be serialized to a string
* @return string the serialized object
*/
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
* 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
* the header. If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601
* @param string $value a string which will be part of the header
* @return string the header string
*/
public static function toHeaderValue($value) {
return self::toString($value);
}
/**
* Take value and turn it into a string suitable for inclusion in
* the query, by imploding comma-separated if it's an object.
* If it's a string, pass through unchanged. It will be url-encoded
* later.
* @param object $object an object to be serialized to a string
* @return string the serialized object
*/
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
* the http body (form parameter). If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601
* @param string $value the value of the form parameter
* @return string the form string
*/
public static function toFormValue($value) {
return self::toString($value);
}
/**
* Take value and turn it into a string suitable for inclusion in
* the header. If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601
* @param string $value a string which will be part of the header
* @return string the header string
*/
public static function toHeaderValue($value) {
return self::toString($value);
}
/**
* Take value and turn it into a string suitable for inclusion in
* the parameter. If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601
* @param string $value the value of the parameter
* @return string the header string
*/
public static function toString($value) {
if ($value instanceof \DateTime) { // datetime in ISO8601 format
return $value->format(\DateTime::ISO8601);
}
else {
return $value;
}
}
/**
* Take value and turn it into a string suitable for inclusion in
* the http body (form parameter). If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601
* @param string $value the value of the form parameter
* @return string the form string
*/
public static function toFormValue($value) {
return self::toString($value);
}
/**
* 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;
}
/**
* Take value and turn it into a string suitable for inclusion in
* the parameter. If it's a string, pass through unchanged
* If it's a datetime object, format it in ISO8601
* @param string $value the value of the parameter
* @return string the header string
*/
public static function toString($value) {
if ($value instanceof \DateTime) { // datetime in ISO8601 format
return $value->format(\DateTime::ISO8601);
}
else {
return $value;
}
}
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 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 $deserialized;
}
/*
* 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);
}
}
/*
* 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
*
* @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) {
parent::__construct($message, $code);
$this->response_headers = $responseHeaders;
$this->response_body = $responseBody;
}
$this->response_body = $responseBody;
}
/**
* Get the HTTP response header
*
* @return string HTTP response header
*/
public function getResponseHeaders() {
return $this->response_headers;
}
/**
* Get the HTTP response header
*
* @return string HTTP response header
*/
public function getResponseHeaders() {
return $this->response_headers;
}
/**
* Get the HTTP response body
*
* @return string HTTP response body
*/
public function getResponseBody() {
return $this->response_body;
}
/**
* Get the HTTP response body
*
* @return string HTTP response body
*/
public function getResponseBody() {
return $this->response_body;
}
}

View File

@ -29,515 +29,506 @@ class PetApi {
if (Configuration::$apiClient === null) {
Configuration::$apiClient = new ApiClient(); // create a new API client if not present
$this->apiClient = Configuration::$apiClient;
}
else
$this->apiClient = Configuration::$apiClient; // use the default one
} else {
$this->apiClient = $apiClient; // use the one provided by the user
}
else
$this->apiClient = Configuration::$apiClient; // use the default one
} else {
$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;
}
/**
* get the API client
*/
public function getApiClient() {
return $this->apiClient;
}
// 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;
}
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
// authentication setting, if any
$authSettings = array('petstore_auth');
/**
* 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) {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// 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'));
}
/**
* 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) {
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// parse inputs
$resourcePath = "/pet";
$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('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)
$httpBody = $formParams;
}
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// authentication setting, if any
$authSettings = array('petstore_auth');
// 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;
}
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// authentication setting, if any
$authSettings = array('petstore_auth');
}
/**
* 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) {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// parse inputs
$resourcePath = "/pet";
$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('application/json','application/xml'));
}
/**
* 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) {
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// parse inputs
$resourcePath = "/pet/findByStatus";
$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());
// 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;
}
// query params
if($status !== null) {
$queryParams['status'] = $this->apiClient->toQueryValue($status);
}
// authentication setting, if any
$authSettings = array('petstore_auth');
// 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;
}
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// authentication setting, if any
$authSettings = array('petstore_auth');
}
/**
* 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) {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// parse inputs
$resourcePath = "/pet/findByStatus";
$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());
if(! $response) {
return null;
}
// query params
if($status !== null) {
$queryParams['status'] = $this->apiClient->toQueryValue($status);
}
$responseObject = $this->apiClient->deserialize($response,'array[Pet]');
return $responseObject;
}
/**
* 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)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
// parse inputs
$resourcePath = "/pet/findByTags";
$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());
// authentication setting, if any
$authSettings = array('petstore_auth');
// query params
if($tags !== null) {
$queryParams['tags'] = $this->apiClient->toQueryValue($tags);
}
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// 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;
}
if(! $response) {
return null;
}
// authentication setting, if any
$authSettings = array('petstore_auth');
$responseObject = $this->apiClient->deserialize($response,'array[Pet]');
return $responseObject;
}
/**
* findPetsByTags
*
* Finds Pets by tags
*
* @param array[string] $tags Tags to filter by (required)
* @return array[Pet]
*/
public function findPetsByTags($tags) {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// parse inputs
$resourcePath = "/pet/findByTags";
$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());
if(! $response) {
return null;
}
// query params
if($tags !== null) {
$queryParams['tags'] = $this->apiClient->toQueryValue($tags);
}
// 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('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) {
$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');
}
}
// parse inputs
$resourcePath = "/pet/{petId}";
$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());
// parse inputs
$resourcePath = "/pet/{petId}";
$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());
// path params
if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath);
}
// path params
if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath);
}
// 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;
}
// 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('api_key', 'petstore_auth');
// authentication setting, if any
$authSettings = array('api_key', 'petstore_auth');
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
if(! $response) {
return null;
}
if(! $response) {
return null;
}
$responseObject = $this->apiClient->deserialize($response,'Pet');
return $responseObject;
}
/**
* updatePetWithForm
*
* Updates a pet in the store with form data
*
* @param string $pet_id ID of pet that needs to be updated (required)
* @param string $name Updated name of the pet (required)
* @param string $status Updated status of the pet (required)
* @return void
*/
public function updatePetWithForm($pet_id, $name, $status) {
// verify the required parameter 'pet_id' is set
if ($pet_id === null) {
$responseObject = $this->apiClient->deserialize($response,'Pet');
return $responseObject;
}
/**
* updatePetWithForm
*
* Updates a pet in the store with form data
*
* @param string $pet_id ID of pet that needs to be updated (required)
* @param string $name Updated name of the pet (required)
* @param string $status Updated status of the pet (required)
* @return void
*/
public function updatePetWithForm($pet_id, $name, $status) {
// verify the required parameter 'pet_id' is set
if ($pet_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm');
}
}
// parse inputs
$resourcePath = "/pet/{petId}";
$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('application/x-www-form-urlencoded'));
// parse inputs
$resourcePath = "/pet/{petId}";
$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('application/x-www-form-urlencoded'));
// path params
if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath);
}
// form params
if ($name !== null) {
$formParams['name'] = $this->apiClient->toFormValue($name);
}// form params
if ($status !== null) {
$formParams['status'] = $this->apiClient->toFormValue($status);
}
// path params
if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath);
}
// form params
if ($name !== null) {
$formParams['name'] = $this->apiClient->toFormValue($name);
}// form params
if ($status !== null) {
$formParams['status'] = $this->apiClient->toFormValue($status);
}
// 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;
}
// 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('petstore_auth');
// authentication setting, if any
$authSettings = array('petstore_auth');
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
}
/**
* deletePet
*
* Deletes a pet
*
* @param string $api_key (required)
* @param int $pet_id Pet id to delete (required)
* @return void
*/
public function deletePet($api_key, $pet_id) {
// verify the required parameter 'pet_id' is set
if ($pet_id === null) {
}
/**
* deletePet
*
* Deletes a pet
*
* @param string $api_key (required)
* @param int $pet_id Pet id to delete (required)
* @return void
*/
public function deletePet($api_key, $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 deletePet');
}
}
// parse inputs
$resourcePath = "/pet/{petId}";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "DELETE";
$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());
// parse inputs
$resourcePath = "/pet/{petId}";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "DELETE";
$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());
// header params
if($api_key !== null) {
$headerParams['api_key'] = $this->apiClient->toHeaderValue($api_key);
}
// path params
if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath);
}
// header params
if($api_key !== null) {
$headerParams['api_key'] = $this->apiClient->toHeaderValue($api_key);
}
// path params
if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath);
}
// 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;
}
// 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('petstore_auth');
// authentication setting, if any
$authSettings = array('petstore_auth');
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
}
/**
* uploadFile
*
* uploads an image
*
* @param int $pet_id ID of pet to update (required)
* @param string $additional_metadata Additional data to pass to server (required)
* @param string $file file to upload (required)
* @return void
*/
public function uploadFile($pet_id, $additional_metadata, $file) {
// verify the required parameter 'pet_id' is set
if ($pet_id === null) {
}
/**
* uploadFile
*
* uploads an image
*
* @param int $pet_id ID of pet to update (required)
* @param string $additional_metadata Additional data to pass to server (required)
* @param string $file file to upload (required)
* @return void
*/
public function uploadFile($pet_id, $additional_metadata, $file) {
// verify the required parameter 'pet_id' is set
if ($pet_id === null) {
throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile');
}
}
// parse inputs
$resourcePath = "/pet/{petId}/uploadImage";
$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('multipart/form-data'));
// parse inputs
$resourcePath = "/pet/{petId}/uploadImage";
$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('multipart/form-data'));
// path params
if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath);
}
// form params
if ($additional_metadata !== null) {
$formParams['additionalMetadata'] = $this->apiClient->toFormValue($additional_metadata);
}// form params
if ($file !== null) {
$formParams['file'] = '@' . $this->apiClient->toFormValue($file);
}
// path params
if($pet_id !== null) {
$resourcePath = str_replace("{" . "petId" . "}",
$this->apiClient->toPathValue($pet_id), $resourcePath);
}
// form params
if ($additional_metadata !== null) {
$formParams['additionalMetadata'] = $this->apiClient->toFormValue($additional_metadata);
}// form params
if ($file !== null) {
$formParams['file'] = '@' . $this->apiClient->toFormValue($file);
}
// 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;
}
// 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('petstore_auth');
// authentication setting, if any
$authSettings = array('petstore_auth');
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
}
}
}

View File

@ -29,266 +29,261 @@ class StoreApi {
if (Configuration::$apiClient === null) {
Configuration::$apiClient = new ApiClient(); // create a new API client if not present
$this->apiClient = Configuration::$apiClient;
}
else
$this->apiClient = Configuration::$apiClient; // use the default one
} else {
$this->apiClient = $apiClient; // use the one provided by the user
}
else
$this->apiClient = Configuration::$apiClient; // use the default one
} else {
$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
/**
* get the API client
*/
public function getApiClient() {
return $this->apiClient;
}
// 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;
}
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
// authentication setting, if any
$authSettings = array('api_key');
/**
* getInventory
*
* Returns pet inventories by status
*
* @return map[string,int]
*/
public function getInventory() {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// 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());
if(! $response) {
return null;
}
$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)
if (isset($_tempBody)) {
$httpBody = $_tempBody; // $_tempBody is the method argument, if present
} else if (count($formParams) > 0) {
// for HTTP post (form)
$httpBody = $formParams;
}
// parse inputs
$resourcePath = "/store/order";
$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());
// authentication setting, if any
$authSettings = array('api_key');
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// 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;
}
if(! $response) {
return null;
}
// authentication setting, if any
$authSettings = 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) {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// parse inputs
$resourcePath = "/store/order";
$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());
if(! $response) {
return null;
}
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// 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);
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) {
$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');
}
}
// parse inputs
$resourcePath = "/store/order/{orderId}";
$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());
// parse inputs
$resourcePath = "/store/order/{orderId}";
$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());
// path params
if($order_id !== null) {
$resourcePath = str_replace("{" . "orderId" . "}",
$this->apiClient->toPathValue($order_id), $resourcePath);
}
// path params
if($order_id !== null) {
$resourcePath = str_replace("{" . "orderId" . "}",
$this->apiClient->toPathValue($order_id), $resourcePath);
}
// 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;
}
// 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();
// authentication setting, if any
$authSettings = array();
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
if(! $response) {
return null;
}
if(! $response) {
return null;
}
$responseObject = $this->apiClient->deserialize($response,'Order');
return $responseObject;
}
/**
* deleteOrder
*
* Delete purchase order by ID
*
* @param string $order_id ID of the order that needs to be deleted (required)
* @return void
*/
public function deleteOrder($order_id) {
// verify the required parameter 'order_id' is set
if ($order_id === null) {
$responseObject = $this->apiClient->deserialize($response,'Order');
return $responseObject;
}
/**
* deleteOrder
*
* Delete purchase order by ID
*
* @param string $order_id ID of the order that needs to be deleted (required)
* @return void
*/
public function deleteOrder($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 deleteOrder');
}
}
// parse inputs
$resourcePath = "/store/order/{orderId}";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "DELETE";
$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());
// parse inputs
$resourcePath = "/store/order/{orderId}";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "DELETE";
$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());
// path params
if($order_id !== null) {
$resourcePath = str_replace("{" . "orderId" . "}",
$this->apiClient->toPathValue($order_id), $resourcePath);
}
// path params
if($order_id !== null) {
$resourcePath = str_replace("{" . "orderId" . "}",
$this->apiClient->toPathValue($order_id), $resourcePath);
}
// 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;
}
// 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();
// authentication setting, if any
$authSettings = array();
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
}
}
}

View File

@ -29,490 +29,481 @@ class UserApi {
if (Configuration::$apiClient === null) {
Configuration::$apiClient = new ApiClient(); // create a new API client if not present
$this->apiClient = Configuration::$apiClient;
}
else
$this->apiClient = Configuration::$apiClient; // use the default one
} else {
$this->apiClient = $apiClient; // use the one provided by the user
}
else
$this->apiClient = Configuration::$apiClient; // use the default one
} else {
$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;
}
/**
* get the API client
*/
public function getApiClient() {
return $this->apiClient;
}
// 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;
}
/**
* set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
}
// authentication setting, if any
$authSettings = array();
/**
* createUser
*
* Create user
*
* @param User $body Created user object (required)
* @return void
*/
public function createUser($body) {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// 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());
}
/**
* createUsersWithArrayInput
*
* Creates list of users with given input array
*
* @param array[User] $body List of user object (required)
* @return void
*/
public function createUsersWithArrayInput($body) {
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// parse inputs
$resourcePath = "/user/createWithArray";
$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());
// 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;
}
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// authentication setting, if any
$authSettings = 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)
$httpBody = $formParams;
}
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// authentication setting, if any
$authSettings = array();
}
/**
* createUsersWithArrayInput
*
* Creates list of users with given input array
*
* @param array[User] $body List of user object (required)
* @return void
*/
public function createUsersWithArrayInput($body) {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// parse inputs
$resourcePath = "/user/createWithArray";
$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());
}
/**
* createUsersWithListInput
*
* Creates list of users with given input array
*
* @param array[User] $body List of user object (required)
* @return void
*/
public function createUsersWithListInput($body) {
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// parse inputs
$resourcePath = "/user/createWithList";
$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());
// 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;
}
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// authentication setting, if any
$authSettings = 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)
$httpBody = $formParams;
}
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// authentication setting, if any
$authSettings = array();
}
/**
* createUsersWithListInput
*
* Creates list of users with given input array
*
* @param array[User] $body List of user object (required)
* @return void
*/
public function createUsersWithListInput($body) {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// parse inputs
$resourcePath = "/user/createWithList";
$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());
}
/**
* 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) {
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// parse inputs
$resourcePath = "/user/login";
$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());
// 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;
}
// query params
if($username !== null) {
$queryParams['username'] = $this->apiClient->toQueryValue($username);
}// query params
if($password !== null) {
$queryParams['password'] = $this->apiClient->toQueryValue($password);
}
// authentication setting, if any
$authSettings = 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)
$httpBody = $formParams;
}
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// authentication setting, if any
$authSettings = array();
}
/**
* 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) {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// parse inputs
$resourcePath = "/user/login";
$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());
if(! $response) {
return null;
}
// query params
if($username !== null) {
$queryParams['username'] = $this->apiClient->toQueryValue($username);
}// query params
if($password !== null) {
$queryParams['password'] = $this->apiClient->toQueryValue($password);
}
$responseObject = $this->apiClient->deserialize($response,'string');
return $responseObject;
}
/**
* logoutUser
*
* Logs out current logged in user session
*
* @return void
*/
public function logoutUser() {
// 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;
}
// parse inputs
$resourcePath = "/user/logout";
$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());
// authentication setting, if any
$authSettings = array();
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// 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;
}
if(! $response) {
return null;
}
// authentication setting, if any
$authSettings = array();
$responseObject = $this->apiClient->deserialize($response,'string');
return $responseObject;
}
/**
* logoutUser
*
* Logs out current logged in user session
*
* @return void
*/
public function logoutUser() {
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// parse inputs
$resourcePath = "/user/logout";
$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());
// 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) {
}
/**
* 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');
}
}
// parse inputs
$resourcePath = "/user/{username}";
$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());
// parse inputs
$resourcePath = "/user/{username}";
$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());
// path params
if($username !== null) {
$resourcePath = str_replace("{" . "username" . "}",
$this->apiClient->toPathValue($username), $resourcePath);
}
// path params
if($username !== null) {
$resourcePath = str_replace("{" . "username" . "}",
$this->apiClient->toPathValue($username), $resourcePath);
}
// 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;
}
// 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();
// authentication setting, if any
$authSettings = array();
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
if(! $response) {
return null;
}
if(! $response) {
return null;
}
$responseObject = $this->apiClient->deserialize($response,'User');
return $responseObject;
}
/**
* updateUser
*
* Updated user
*
* @param string $username name that need to be deleted (required)
* @param User $body Updated user object (required)
* @return void
*/
public function updateUser($username, $body) {
// verify the required parameter 'username' is set
if ($username === null) {
$responseObject = $this->apiClient->deserialize($response,'User');
return $responseObject;
}
/**
* updateUser
*
* Updated user
*
* @param string $username name that need to be deleted (required)
* @param User $body Updated user object (required)
* @return void
*/
public function updateUser($username, $body) {
// verify the required parameter 'username' is set
if ($username === null) {
throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser');
}
}
// parse inputs
$resourcePath = "/user/{username}";
$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());
// parse inputs
$resourcePath = "/user/{username}";
$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());
// path params
if($username !== null) {
$resourcePath = str_replace("{" . "username" . "}",
$this->apiClient->toPathValue($username), $resourcePath);
}
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// path params
if($username !== null) {
$resourcePath = str_replace("{" . "username" . "}",
$this->apiClient->toPathValue($username), $resourcePath);
}
// body params
$_tempBody = null;
if (isset($body)) {
$_tempBody = $body;
}
// 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;
}
// 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();
// authentication setting, if any
$authSettings = array();
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
}
/**
* deleteUser
*
* Delete user
*
* @param string $username The name that needs to be deleted (required)
* @return void
*/
public function deleteUser($username) {
// verify the required parameter 'username' is set
if ($username === null) {
}
/**
* deleteUser
*
* Delete user
*
* @param string $username The name that needs to be deleted (required)
* @return void
*/
public function deleteUser($username) {
// verify the required parameter 'username' is set
if ($username === null) {
throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser');
}
}
// parse inputs
$resourcePath = "/user/{username}";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "DELETE";
$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());
// parse inputs
$resourcePath = "/user/{username}";
$resourcePath = str_replace("{format}", "json", $resourcePath);
$method = "DELETE";
$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());
// path params
if($username !== null) {
$resourcePath = str_replace("{" . "username" . "}",
$this->apiClient->toPathValue($username), $resourcePath);
}
// path params
if($username !== null) {
$resourcePath = str_replace("{" . "username" . "}",
$this->apiClient->toPathValue($username), $resourcePath);
}
// 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;
}
// 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();
// authentication setting, if any
$authSettings = array();
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
// make the API Call
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
}
}
}

View File

@ -15,6 +15,7 @@
* limitations under the License.
*/
/**
*
*
@ -29,36 +30,37 @@ use \ArrayAccess;
class Category implements ArrayAccess {
static $swaggerTypes = array(
'id' => 'int',
'name' => 'string'
);
'name' => 'string'
);
static $attributeMap = array(
'id' => 'id',
'name' => 'name'
);
static $attributeMap = array(
'id' => 'id',
'name' => 'name'
);
public $id; /* int */
public $name; /* string */
public $id; /* int */
public $name; /* string */
public function __construct(array $data = null) {
public function __construct(array $data = null) {
$this->id = $data["id"];
$this->name = $data["name"];
}
}
public function offsetExists($offset) {
public function offsetExists($offset) {
return isset($this->$offset);
}
}
public function offsetGet($offset) {
public function offsetGet($offset) {
return $this->$offset;
}
}
public function offsetSet($offset, $value) {
public function offsetSet($offset, $value) {
$this->$offset = $value;
}
}
public function offsetUnset($offset) {
public function offsetUnset($offset) {
unset($this->$offset);
}
}
}
}

View File

@ -15,6 +15,7 @@
* limitations under the License.
*/
/**
*
*
@ -29,55 +30,56 @@ use \ArrayAccess;
class Order implements ArrayAccess {
static $swaggerTypes = array(
'id' => 'int',
'pet_id' => 'int',
'quantity' => 'int',
'ship_date' => 'DateTime',
'status' => 'string',
'complete' => 'boolean'
);
'pet_id' => 'int',
'quantity' => 'int',
'ship_date' => 'DateTime',
'status' => 'string',
'complete' => 'boolean'
);
static $attributeMap = array(
'id' => 'id',
'pet_id' => 'petId',
'quantity' => 'quantity',
'ship_date' => 'shipDate',
'status' => 'status',
'complete' => 'complete'
);
static $attributeMap = array(
'id' => 'id',
'pet_id' => 'petId',
'quantity' => 'quantity',
'ship_date' => 'shipDate',
'status' => 'status',
'complete' => 'complete'
);
public $id; /* int */
public $pet_id; /* int */
public $quantity; /* int */
public $ship_date; /* DateTime */
/**
* Order Status
*/
public $status; /* string */
public $complete; /* boolean */
public $id; /* int */
public $pet_id; /* int */
public $quantity; /* int */
public $ship_date; /* DateTime */
/**
* Order Status
*/
public $status; /* string */
public $complete; /* boolean */
public function __construct(array $data = null) {
public function __construct(array $data = null) {
$this->id = $data["id"];
$this->pet_id = $data["pet_id"];
$this->quantity = $data["quantity"];
$this->ship_date = $data["ship_date"];
$this->status = $data["status"];
$this->complete = $data["complete"];
}
}
public function offsetExists($offset) {
public function offsetExists($offset) {
return isset($this->$offset);
}
}
public function offsetGet($offset) {
public function offsetGet($offset) {
return $this->$offset;
}
}
public function offsetSet($offset, $value) {
public function offsetSet($offset, $value) {
$this->$offset = $value;
}
}
public function offsetUnset($offset) {
public function offsetUnset($offset) {
unset($this->$offset);
}
}
}
}

View File

@ -15,6 +15,7 @@
* limitations under the License.
*/
/**
*
*
@ -29,55 +30,56 @@ use \ArrayAccess;
class Pet implements ArrayAccess {
static $swaggerTypes = array(
'id' => 'int',
'category' => 'Category',
'name' => 'string',
'photo_urls' => 'array[string]',
'tags' => 'array[Tag]',
'status' => 'string'
);
'category' => 'Category',
'name' => 'string',
'photo_urls' => 'array[string]',
'tags' => 'array[Tag]',
'status' => 'string'
);
static $attributeMap = array(
'id' => 'id',
'category' => 'category',
'name' => 'name',
'photo_urls' => 'photoUrls',
'tags' => 'tags',
'status' => 'status'
);
static $attributeMap = array(
'id' => 'id',
'category' => 'category',
'name' => 'name',
'photo_urls' => 'photoUrls',
'tags' => 'tags',
'status' => 'status'
);
public $id; /* int */
public $category; /* Category */
public $name; /* string */
public $photo_urls; /* array[string] */
public $tags; /* array[Tag] */
/**
* pet status in the store
*/
public $status; /* string */
public $id; /* int */
public $category; /* Category */
public $name; /* string */
public $photo_urls; /* array[string] */
public $tags; /* array[Tag] */
/**
* pet status in the store
*/
public $status; /* string */
public function __construct(array $data = null) {
public function __construct(array $data = null) {
$this->id = $data["id"];
$this->category = $data["category"];
$this->name = $data["name"];
$this->photo_urls = $data["photo_urls"];
$this->tags = $data["tags"];
$this->status = $data["status"];
}
}
public function offsetExists($offset) {
public function offsetExists($offset) {
return isset($this->$offset);
}
}
public function offsetGet($offset) {
public function offsetGet($offset) {
return $this->$offset;
}
}
public function offsetSet($offset, $value) {
public function offsetSet($offset, $value) {
$this->$offset = $value;
}
}
public function offsetUnset($offset) {
public function offsetUnset($offset) {
unset($this->$offset);
}
}
}
}

View File

@ -15,6 +15,7 @@
* limitations under the License.
*/
/**
*
*
@ -29,36 +30,37 @@ use \ArrayAccess;
class Tag implements ArrayAccess {
static $swaggerTypes = array(
'id' => 'int',
'name' => 'string'
);
'name' => 'string'
);
static $attributeMap = array(
'id' => 'id',
'name' => 'name'
);
static $attributeMap = array(
'id' => 'id',
'name' => 'name'
);
public $id; /* int */
public $name; /* string */
public $id; /* int */
public $name; /* string */
public function __construct(array $data = null) {
public function __construct(array $data = null) {
$this->id = $data["id"];
$this->name = $data["name"];
}
}
public function offsetExists($offset) {
public function offsetExists($offset) {
return isset($this->$offset);
}
}
public function offsetGet($offset) {
public function offsetGet($offset) {
return $this->$offset;
}
}
public function offsetSet($offset, $value) {
public function offsetSet($offset, $value) {
$this->$offset = $value;
}
}
public function offsetUnset($offset) {
public function offsetUnset($offset) {
unset($this->$offset);
}
}
}
}

View File

@ -15,6 +15,7 @@
* limitations under the License.
*/
/**
*
*
@ -29,40 +30,40 @@ use \ArrayAccess;
class User implements ArrayAccess {
static $swaggerTypes = array(
'id' => 'int',
'username' => 'string',
'first_name' => 'string',
'last_name' => 'string',
'email' => 'string',
'password' => 'string',
'phone' => 'string',
'user_status' => 'int'
);
'username' => 'string',
'first_name' => 'string',
'last_name' => 'string',
'email' => 'string',
'password' => 'string',
'phone' => 'string',
'user_status' => 'int'
);
static $attributeMap = array(
'id' => 'id',
'username' => 'username',
'first_name' => 'firstName',
'last_name' => 'lastName',
'email' => 'email',
'password' => 'password',
'phone' => 'phone',
'user_status' => 'userStatus'
);
static $attributeMap = array(
'id' => 'id',
'username' => 'username',
'first_name' => 'firstName',
'last_name' => 'lastName',
'email' => 'email',
'password' => 'password',
'phone' => 'phone',
'user_status' => 'userStatus'
);
public $id; /* int */
public $username; /* string */
public $first_name; /* string */
public $last_name; /* string */
public $email; /* string */
public $password; /* string */
public $phone; /* string */
/**
* User Status
*/
public $user_status; /* int */
public $id; /* int */
public $username; /* string */
public $first_name; /* string */
public $last_name; /* string */
public $email; /* string */
public $password; /* string */
public $phone; /* string */
/**
* User Status
*/
public $user_status; /* int */
public function __construct(array $data = null) {
public function __construct(array $data = null) {
$this->id = $data["id"];
$this->username = $data["username"];
$this->first_name = $data["first_name"];
@ -71,21 +72,22 @@ class User implements ArrayAccess {
$this->password = $data["password"];
$this->phone = $data["phone"];
$this->user_status = $data["user_status"];
}
}
public function offsetExists($offset) {
public function offsetExists($offset) {
return isset($this->$offset);
}
}
public function offsetGet($offset) {
public function offsetGet($offset) {
return $this->$offset;
}
}
public function offsetSet($offset, $value) {
public function offsetSet($offset, $value) {
$this->$offset = $value;
}
}
public function offsetUnset($offset) {
public function offsetUnset($offset) {
unset($this->$offset);
}
}
}
}

View File

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

View File

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

View File

@ -5,17 +5,17 @@
PetApi.py
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
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 ..api_client import ApiClient
class PetApi(object):
class PetApi(object):
def __init__(self, api_client=None):
if api_client:
self.api_client = api_client
else:
if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client
if api_client:
self.api_client = api_client
else:
if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client
def update_pet(self, **kwargs):
def update_pet(self, **kwargs):
"""
Update an existing pet
@ -55,9 +55,9 @@ class PetApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method update_pet" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method update_pet" % key)
params[key] = val
del params['kwargs']
resource_path = '/pet'.replace('{format}', 'json')
@ -74,13 +74,13 @@ class PetApi(object):
body_params = None
if 'body' in params:
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
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']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
def add_pet(self, **kwargs):
def add_pet(self, **kwargs):
"""
Add a new pet to the store
@ -106,9 +106,9 @@ class PetApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method add_pet" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method add_pet" % key)
params[key] = val
del params['kwargs']
resource_path = '/pet'.replace('{format}', 'json')
@ -125,13 +125,13 @@ class PetApi(object):
body_params = None
if 'body' in params:
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
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']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
def find_pets_by_status(self, **kwargs):
def find_pets_by_status(self, **kwargs):
"""
Finds Pets by status
Multiple status values can be provided with comma seperated strings
@ -157,9 +157,9 @@ class PetApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_status" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_status" % key)
params[key] = val
del params['kwargs']
resource_path = '/pet/findByStatus'.replace('{format}', 'json')
@ -169,7 +169,7 @@ class PetApi(object):
query_params = {}
if 'status' in params:
if 'status' in params:
query_params['status'] = params['status']
header_params = {}
@ -182,7 +182,7 @@ class PetApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP 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']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response='list[Pet]', auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
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
Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
@ -210,9 +210,9 @@ class PetApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_tags" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_tags" % key)
params[key] = val
del params['kwargs']
resource_path = '/pet/findByTags'.replace('{format}', 'json')
@ -222,7 +222,7 @@ class PetApi(object):
query_params = {}
if 'tags' in params:
if 'tags' in params:
query_params['tags'] = params['tags']
header_params = {}
@ -235,7 +235,7 @@ class PetApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP 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']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response='list[Pet]', auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
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
Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
@ -259,17 +259,17 @@ class PetApi(object):
:return: Pet
"""
# verify the required parameter 'pet_id' is set
if pet_id is None:
# verify the required parameter 'pet_id' is set
if pet_id is None:
raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`")
all_params = ['pet_id']
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_pet_by_id" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_pet_by_id" % key)
params[key] = val
del params['kwargs']
resource_path = '/pet/{petId}'.replace('{format}', 'json')
@ -277,8 +277,8 @@ class PetApi(object):
path_params = {}
if 'pet_id' in params:
path_params['petId'] = params['pet_id']
if 'pet_id' in params:
path_params['petId'] = params['pet_id']
query_params = {}
@ -292,7 +292,7 @@ class PetApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP 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']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response='Pet', auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
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
@ -318,17 +318,17 @@ class PetApi(object):
:return: None
"""
# verify the required parameter 'pet_id' is set
if pet_id is None:
# verify the required parameter 'pet_id' is set
if pet_id is None:
raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`")
all_params = ['pet_id', 'name', 'status']
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method update_pet_with_form" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method update_pet_with_form" % key)
params[key] = val
del params['kwargs']
resource_path = '/pet/{petId}'.replace('{format}', 'json')
@ -336,8 +336,8 @@ class PetApi(object):
path_params = {}
if 'pet_id' in params:
path_params['petId'] = params['pet_id']
if 'pet_id' in params:
path_params['petId'] = params['pet_id']
query_params = {}
@ -346,10 +346,10 @@ class PetApi(object):
form_params = {}
files = {}
if 'name' in params:
if 'name' in params:
form_params['name'] = params['name']
if 'status' in params:
if 'status' in params:
form_params['status'] = params['status']
body_params = None
@ -357,7 +357,7 @@ class PetApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
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']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
def delete_pet(self, pet_id, **kwargs):
def delete_pet(self, pet_id, **kwargs):
"""
Deletes a pet
@ -380,17 +380,17 @@ class PetApi(object):
:return: None
"""
# verify the required parameter 'pet_id' is set
if pet_id is None:
# verify the required parameter 'pet_id' is set
if pet_id is None:
raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`")
all_params = ['api_key', 'pet_id']
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method delete_pet" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method delete_pet" % key)
params[key] = val
del params['kwargs']
resource_path = '/pet/{petId}'.replace('{format}', 'json')
@ -398,14 +398,14 @@ class PetApi(object):
path_params = {}
if 'pet_id' in params:
path_params['petId'] = params['pet_id']
if 'pet_id' in params:
path_params['petId'] = params['pet_id']
query_params = {}
header_params = {}
if 'api_key' in params:
if 'api_key' in params:
header_params['api_key'] = params['api_key']
form_params = {}
@ -416,7 +416,7 @@ class PetApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP 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']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
def upload_file(self, pet_id, **kwargs):
def upload_file(self, pet_id, **kwargs):
"""
uploads an image
@ -440,17 +440,17 @@ class PetApi(object):
:return: None
"""
# verify the required parameter 'pet_id' is set
if pet_id is None:
# verify the required parameter 'pet_id' is set
if pet_id is None:
raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`")
all_params = ['pet_id', 'additional_metadata', 'file']
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method upload_file" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method upload_file" % key)
params[key] = val
del params['kwargs']
resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json')
@ -458,8 +458,8 @@ class PetApi(object):
path_params = {}
if 'pet_id' in params:
path_params['petId'] = params['pet_id']
if 'pet_id' in params:
path_params['petId'] = params['pet_id']
query_params = {}
@ -468,10 +468,10 @@ class PetApi(object):
form_params = {}
files = {}
if 'additional_metadata' in params:
if 'additional_metadata' in params:
form_params['additionalMetadata'] = params['additional_metadata']
if 'file' in params:
if 'file' in params:
files['file'] = params['file']
body_params = None
@ -479,7 +479,7 @@ class PetApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
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']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)

View File

@ -5,17 +5,17 @@
StoreApi.py
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
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 ..api_client import ApiClient
class StoreApi(object):
class StoreApi(object):
def __init__(self, api_client=None):
if api_client:
self.api_client = api_client
else:
if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client
if api_client:
self.api_client = api_client
else:
if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client
def get_inventory(self, **kwargs):
def get_inventory(self, **kwargs):
"""
Returns pet inventories by status
Returns a map of status codes to quantities
@ -54,9 +54,9 @@ class StoreApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_inventory" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_inventory" % key)
params[key] = val
del params['kwargs']
resource_path = '/store/inventory'.replace('{format}', 'json')
@ -76,7 +76,7 @@ class StoreApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP 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']
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response='map(String, int)', auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
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
@ -104,9 +104,9 @@ class StoreApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method place_order" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method place_order" % key)
params[key] = val
del params['kwargs']
resource_path = '/store/order'.replace('{format}', 'json')
@ -123,13 +123,13 @@ class StoreApi(object):
body_params = None
if 'body' in params:
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -138,12 +138,12 @@ class StoreApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response='Order', auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
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
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
"""
# verify the required parameter 'order_id' is set
if order_id is None:
# verify the required parameter 'order_id' is set
if order_id is None:
raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`")
all_params = ['order_id']
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_order_by_id" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_order_by_id" % key)
params[key] = val
del params['kwargs']
resource_path = '/store/order/{orderId}'.replace('{format}', 'json')
@ -171,8 +171,8 @@ class StoreApi(object):
path_params = {}
if 'order_id' in params:
path_params['orderId'] = params['order_id']
if 'order_id' in params:
path_params['orderId'] = params['order_id']
query_params = {}
@ -186,7 +186,7 @@ class StoreApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -195,12 +195,12 @@ class StoreApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response='Order', auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
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
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
"""
# verify the required parameter 'order_id' is set
if order_id is None:
# verify the required parameter 'order_id' is set
if order_id is None:
raise ValueError("Missing the required parameter `order_id` when calling `delete_order`")
all_params = ['order_id']
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method delete_order" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method delete_order" % key)
params[key] = val
del params['kwargs']
resource_path = '/store/order/{orderId}'.replace('{format}', 'json')
@ -228,8 +228,8 @@ class StoreApi(object):
path_params = {}
if 'order_id' in params:
path_params['orderId'] = params['order_id']
if 'order_id' in params:
path_params['orderId'] = params['order_id']
query_params = {}
@ -243,7 +243,7 @@ class StoreApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -252,8 +252,8 @@ class StoreApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)

View File

@ -5,17 +5,17 @@
UserApi.py
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
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 ..api_client import ApiClient
class UserApi(object):
class UserApi(object):
def __init__(self, api_client=None):
if api_client:
self.api_client = api_client
else:
if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client
if api_client:
self.api_client = api_client
else:
if not configuration.api_client:
configuration.api_client = ApiClient('http://petstore.swagger.io/v2')
self.api_client = configuration.api_client
def create_user(self, **kwargs):
def create_user(self, **kwargs):
"""
Create user
This can only be done by the logged in user.
@ -55,9 +55,9 @@ class UserApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method create_user" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method create_user" % key)
params[key] = val
del params['kwargs']
resource_path = '/user'.replace('{format}', 'json')
@ -74,13 +74,13 @@ class UserApi(object):
body_params = None
if 'body' in params:
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -89,10 +89,10 @@ class UserApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
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
@ -106,9 +106,9 @@ class UserApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_array_input" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_array_input" % key)
params[key] = val
del params['kwargs']
resource_path = '/user/createWithArray'.replace('{format}', 'json')
@ -125,13 +125,13 @@ class UserApi(object):
body_params = None
if 'body' in params:
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -140,10 +140,10 @@ class UserApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
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
@ -157,9 +157,9 @@ class UserApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_list_input" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_list_input" % key)
params[key] = val
del params['kwargs']
resource_path = '/user/createWithList'.replace('{format}', 'json')
@ -176,13 +176,13 @@ class UserApi(object):
body_params = None
if 'body' in params:
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -191,10 +191,10 @@ class UserApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
def login_user(self, **kwargs):
def login_user(self, **kwargs):
"""
Logs user into the system
@ -209,9 +209,9 @@ class UserApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method login_user" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method login_user" % key)
params[key] = val
del params['kwargs']
resource_path = '/user/login'.replace('{format}', 'json')
@ -221,10 +221,10 @@ class UserApi(object):
query_params = {}
if 'username' in params:
if 'username' in params:
query_params['username'] = params['username']
if 'password' in params:
if 'password' in params:
query_params['password'] = params['password']
header_params = {}
@ -237,7 +237,7 @@ class UserApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -246,12 +246,12 @@ class UserApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response='str', auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
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
@ -264,9 +264,9 @@ class UserApi(object):
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method logout_user" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method logout_user" % key)
params[key] = val
del params['kwargs']
resource_path = '/user/logout'.replace('{format}', 'json')
@ -286,7 +286,7 @@ class UserApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -295,10 +295,10 @@ class UserApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
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
@ -308,17 +308,17 @@ class UserApi(object):
:return: User
"""
# verify the required parameter 'username' is set
if username is None:
# verify the required parameter 'username' is set
if username is None:
raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`")
all_params = ['username']
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_user_by_name" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method get_user_by_name" % key)
params[key] = val
del params['kwargs']
resource_path = '/user/{username}'.replace('{format}', 'json')
@ -326,8 +326,8 @@ class UserApi(object):
path_params = {}
if 'username' in params:
path_params['username'] = params['username']
if 'username' in params:
path_params['username'] = params['username']
query_params = {}
@ -341,7 +341,7 @@ class UserApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -350,12 +350,12 @@ class UserApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response='User', auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
response='User', auth_settings=auth_settings)
return response
return response
def update_user(self, username, **kwargs):
def update_user(self, username, **kwargs):
"""
Updated user
This can only be done by the logged in user.
@ -366,17 +366,17 @@ class UserApi(object):
:return: None
"""
# verify the required parameter 'username' is set
if username is None:
# verify the required parameter 'username' is set
if username is None:
raise ValueError("Missing the required parameter `username` when calling `update_user`")
all_params = ['username', 'body']
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method update_user" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method update_user" % key)
params[key] = val
del params['kwargs']
resource_path = '/user/{username}'.replace('{format}', 'json')
@ -384,8 +384,8 @@ class UserApi(object):
path_params = {}
if 'username' in params:
path_params['username'] = params['username']
if 'username' in params:
path_params['username'] = params['username']
query_params = {}
@ -396,13 +396,13 @@ class UserApi(object):
body_params = None
if 'body' in params:
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -411,10 +411,10 @@ class UserApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
def delete_user(self, username, **kwargs):
def delete_user(self, username, **kwargs):
"""
Delete user
This can only be done by the logged in user.
@ -424,17 +424,17 @@ class UserApi(object):
:return: None
"""
# verify the required parameter 'username' is set
if username is None:
# verify the required parameter 'username' is set
if username is None:
raise ValueError("Missing the required parameter `username` when calling `delete_user`")
all_params = ['username']
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method delete_user" % key)
params[key] = val
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s' to method delete_user" % key)
params[key] = val
del params['kwargs']
resource_path = '/user/{username}'.replace('{format}', 'json')
@ -442,8 +442,8 @@ class UserApi(object):
path_params = {}
if 'username' in params:
path_params['username'] = params['username']
if 'username' in params:
path_params['username'] = params['username']
query_params = {}
@ -457,7 +457,7 @@ class UserApi(object):
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml'])
if not header_params['Accept']:
del header_params['Accept']
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type([])
@ -466,8 +466,8 @@ class UserApi(object):
auth_settings = []
response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)
body=body_params, post_params=form_params, files=files,
response=None, auth_settings=auth_settings)

View File

@ -3,37 +3,37 @@ import base64
import urllib3
def get_api_key_with_prefix(key):
global api_key
global api_key_prefix
global api_key
global api_key_prefix
if api_key.get(key) and api_key_prefix.get(key):
return api_key_prefix[key] + ' ' + api_key[key]
elif api_key.get(key):
return api_key[key]
if api_key.get(key) and api_key_prefix.get(key):
return api_key_prefix[key] + ' ' + api_key[key]
elif api_key.get(key):
return api_key[key]
def get_basic_auth_token():
global username
global password
global username
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():
return {
'api_key': {
'type': 'api_key',
'in': 'header',
'key': 'api_key',
'value': get_api_key_with_prefix('api_key')
},
}
return {
'api_key': {
'type': 'api_key',
'in': 'header',
'key': 'api_key',
'value': get_api_key_with_prefix('api_key')
},
}
# Default Base url
host = "http://petstore.swagger.io/v2"
# Default api client
api_client = None
# Authentication settings
api_key = {}

View File

@ -4,26 +4,27 @@
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class Category(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
class Category(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
def __init__(self):
"""
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.
"""
self.swagger_types = {
'id': 'int',
'name': 'str'
'id': 'int',
'name': 'str'
}
self.attribute_map = {
'id': 'id',
'name': 'name'
'id': 'id',
'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 = []
for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@ -4,26 +4,27 @@
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class Order(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
class Order(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
def __init__(self):
"""
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.
"""
self.swagger_types = {
'id': 'int',
'pet_id': 'int',
'quantity': 'int',
'ship_date': 'DateTime',
'status': 'str',
'complete': 'bool'
'id': 'int',
'pet_id': 'int',
'quantity': 'int',
'ship_date': 'DateTime',
'status': 'str',
'complete': 'bool'
}
self.attribute_map = {
'id': 'id',
'pet_id': 'petId',
'quantity': 'quantity',
'ship_date': 'shipDate',
'status': 'status',
'complete': 'complete'
'id': 'id',
'pet_id': 'petId',
'quantity': 'quantity',
'ship_date': 'shipDate',
'status': 'status',
'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.ship_date = None # DateTime
# Order Status
self.status = None # str
self.complete = None # bool
self.complete = None # bool
def __repr__(self):
def __repr__(self):
properties = []
for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@ -4,26 +4,27 @@
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class Pet(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
class Pet(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
def __init__(self):
"""
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.
"""
self.swagger_types = {
'id': 'int',
'category': 'Category',
'name': 'str',
'photo_urls': 'list[str]',
'tags': 'list[Tag]',
'status': 'str'
'id': 'int',
'category': 'Category',
'name': 'str',
'photo_urls': 'list[str]',
'tags': 'list[Tag]',
'status': 'str'
}
self.attribute_map = {
'id': 'id',
'category': 'category',
'name': 'name',
'photo_urls': 'photoUrls',
'tags': 'tags',
'status': 'status'
'id': 'id',
'category': 'category',
'name': 'name',
'photo_urls': 'photoUrls',
'tags': 'tags',
'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
self.photo_urls = None # list[str]
self.tags = None # list[Tag]
# pet status in the store
self.status = None # str
# pet status in the store
self.status = None # str
def __repr__(self):
def __repr__(self):
properties = []
for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@ -4,26 +4,27 @@
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class Tag(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
class Tag(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
def __init__(self):
"""
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.
"""
self.swagger_types = {
'id': 'int',
'name': 'str'
'id': 'int',
'name': 'str'
}
self.attribute_map = {
'id': 'id',
'name': 'name'
'id': 'id',
'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 = []
for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

@ -4,26 +4,27 @@
"""
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class User(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
class User(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self):
def __init__(self):
"""
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.
"""
self.swagger_types = {
'id': 'int',
'username': 'str',
'first_name': 'str',
'last_name': 'str',
'email': 'str',
'password': 'str',
'phone': 'str',
'user_status': 'int'
'id': 'int',
'username': 'str',
'first_name': 'str',
'last_name': 'str',
'email': 'str',
'password': 'str',
'phone': 'str',
'user_status': 'int'
}
self.attribute_map = {
'id': 'id',
'username': 'username',
'first_name': 'firstName',
'last_name': 'lastName',
'email': 'email',
'password': 'password',
'phone': 'phone',
'user_status': 'userStatus'
'id': 'id',
'username': 'username',
'first_name': 'firstName',
'last_name': 'lastName',
'email': 'email',
'password': 'password',
'phone': 'phone',
'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
self.email = None # str
self.password = None # str
self.phone = None # str
# User Status
self.user_status = None # int
# User Status
self.user_status = None # int
def __repr__(self):
def __repr__(self):
properties = []
for p in self.__dict__:
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
if p != 'swaggerTypes' and p != 'attributeMap':
properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p]))
return '<{name} {props}>'.format(name=__name__, props=' '.join(properties))

View File

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

View File

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

View File

@ -1,47 +1,48 @@
/*
* SWGCategory.h
*
*
*/
* SWGCategory.h
*
*
*/
#ifndef SWGCategory_H_
#define SWGCategory_H_
#include <QJsonObject>
#include
<QJsonObject>
#include <QString>
#include "SWGObject.h"
#include "SWGObject.h"
namespace Swagger {
namespace Swagger {
class SWGCategory: public SWGObject {
public:
class SWGCategory: public SWGObject {
public:
SWGCategory();
SWGCategory(QString* json);
virtual ~SWGCategory();
void init();
void cleanup();
virtual ~SWGCategory();
void init();
void cleanup();
QString asJson ();
QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json);
QString asJson ();
QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json);
SWGCategory* fromJson(QString &jsonString);
qint64 getId();
void setId(qint64 id);
void setId(qint64 id);
QString* getName();
void setName(QString* name);
void setName(QString* name);
private:
private:
qint64 id;
QString* name;
};
};
} /* namespace Swagger */
} /* namespace Swagger */
#endif /* SWGCategory_H_ */
#endif /* SWGCategory_H_ */

View File

@ -1,166 +1,201 @@
#include "SWGHelpers.h"
#include "SWGModelFactory.h"
#include "SWGObject.h"
#import <QDebug>
#import <QJsonArray>
#import <QJsonValue>
#import
<QDebug>
#import
<QJsonArray>
#import
<QJsonValue>
namespace Swagger {
namespace Swagger {
void
setValue(void* value, QJsonValue obj, QString type, QString complexType) {
if(value == NULL) {
// can't set value with a null pointer
return;
}
if(QStringLiteral("bool").compare(type) == 0) {
bool * val = static_cast<bool*>(value);
*val = obj.toBool();
}
else if(QStringLiteral("qint32").compare(type) == 0) {
qint32 *val = static_cast<qint32*>(value);
*val = obj.toInt();
}
else if(QStringLiteral("qint64").compare(type) == 0) {
qint64 *val = static_cast<qint64*>(value);
*val = obj.toVariant().toLongLong();
}
else if (QStringLiteral("QString").compare(type) == 0) {
QString **val = static_cast<QString**>(value);
void
setValue(void* value, QJsonValue obj, QString type, QString complexType) {
if(value == NULL) {
// can't set value with a null pointer
return;
}
if(QStringLiteral("bool").compare(type) == 0) {
bool * val = static_cast
<bool
*>(value);
*val = obj.toBool();
}
else if(QStringLiteral("qint32").compare(type) == 0) {
qint32 *val = static_cast
<qint32
*>(value);
*val = obj.toInt();
}
else if(QStringLiteral("qint64").compare(type) == 0) {
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()) {
// create a new value and return
delete *val;
*val = new QString(obj.toString());
return;
// create a new value and return
delete *val;
*val = new QString(obj.toString());
return;
}
else {
// set target to NULL
delete *val;
*val = NULL;
// set target to NULL
delete *val;
*val = NULL;
}
}
else {
}
else {
qDebug() << "Can't set value because the target pointer is NULL";
}
}
else if(type.startsWith("SWG") && obj.isObject()) {
// complex type
QJsonObject jsonObj = obj.toObject();
SWGObject * so = (SWGObject*)Swagger::create(type);
if(so != NULL) {
}
}
else if(type.startsWith("SWG") && obj.isObject()) {
// complex type
QJsonObject jsonObj = obj.toObject();
SWGObject * so = (SWGObject*)Swagger::create(type);
if(so != NULL) {
so->fromJsonObject(jsonObj);
SWGObject **val = static_cast<SWGObject**>(value);
SWGObject **val = static_cast
<SWGObject
**>(value);
delete *val;
*val = so;
}
}
else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) {
// list of values
QList<void*>* output = new QList<void*>();
QJsonArray arr = obj.toArray();
foreach (const QJsonValue & jval, arr) {
}
}
else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) {
// list of values
QList
<void
*>* output = new QList
<void
*>();
QJsonArray arr = obj.toArray();
foreach (const QJsonValue & jval, arr) {
if(complexType.startsWith("SWG")) {
// it's an object
SWGObject * val = (SWGObject*)create(complexType);
QJsonObject t = jval.toObject();
// it's an object
SWGObject * val = (SWGObject*)create(complexType);
QJsonObject t = jval.toObject();
val->fromJsonObject(t);
output->append(val);
val->fromJsonObject(t);
output->append(val);
}
else {
// primitives
if(QStringLiteral("qint32").compare(complexType) == 0) {
qint32 val;
setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral(""));
output->append((void*)&val);
}
else if(QStringLiteral("qint64").compare(complexType) == 0) {
qint64 val;
setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral(""));
output->append((void*)&val);
}
else if(QStringLiteral("bool").compare(complexType) == 0) {
bool val;
setValue(&val, jval, QStringLiteral("bool"), QStringLiteral(""));
output->append((void*)&val);
}
// primitives
if(QStringLiteral("qint32").compare(complexType) == 0) {
qint32 val;
setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral(""));
output->append((void*)&val);
}
else if(QStringLiteral("qint64").compare(complexType) == 0) {
qint64 val;
setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral(""));
output->append((void*)&val);
}
else if(QStringLiteral("bool").compare(complexType) == 0) {
bool val;
setValue(&val, jval, QStringLiteral("bool"), QStringLiteral(""));
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
toJsonValue(QString name, void* value, QJsonObject* output, QString type) {
if(value == NULL) {
return;
}
if(type.startsWith("SWG")) {
SWGObject *swgObject = reinterpret_cast<SWGObject *>(value);
if(swgObject != NULL) {
QJsonObject* o = (*swgObject).asJsonObject();
if(name != NULL) {
void
toJsonValue(QString name, void* value, QJsonObject* output, QString type) {
if(value == NULL) {
return;
}
if(type.startsWith("SWG")) {
SWGObject *swgObject = reinterpret_cast
<SWGObject *>(value);
if(swgObject != NULL) {
QJsonObject* o = (*swgObject).asJsonObject();
if(name != NULL) {
output->insert(name, *o);
delete o;
}
else {
}
else {
output->empty();
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
toJsonArray(QList<void*>* value, QJsonArray* output, QString innerName, QString innerType) {
foreach(void* obj, *value) {
QJsonObject element;
void
toJsonArray(QList
<void
*>* value, QJsonArray* output, QString innerName, QString innerType) {
foreach(void* obj, *value) {
QJsonObject element;
toJsonValue(NULL, obj, &element, innerType);
output->append(element);
}
}
toJsonValue(NULL, obj, &element, innerType);
output->append(element);
}
}
QString
stringValue(QString* value) {
QString* str = static_cast<QString*>(value);
return QString(*str);
}
QString
stringValue(QString* value) {
QString* str = static_cast
<QString
*>(value);
return QString(*str);
}
QString
stringValue(qint32 value) {
return QString::number(value);
}
QString
stringValue(qint32 value) {
return QString::number(value);
}
QString
stringValue(qint64 value) {
return QString::number(value);
}
QString
stringValue(qint64 value) {
return QString::number(value);
}
QString
stringValue(bool value) {
return QString(value ? "true" : "false");
}
} /* namespace Swagger */
QString
stringValue(bool value) {
return QString(value ? "true" : "false");
}
} /* namespace Swagger */

View File

@ -1,17 +1,20 @@
#ifndef SWGHELPERS_H
#define SWGHELPERS_H
#include <QJsonValue>
#include
<QJsonValue>
namespace Swagger {
namespace Swagger {
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);
bool isCompatibleJsonValue(QString type);
QString stringValue(QString* value);
QString stringValue(qint32 value);
QString stringValue(qint64 value);
QString stringValue(bool value);
}
}
#endif // SWGHELPERS_H
#endif // SWGHELPERS_H

View File

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

View File

@ -1,24 +1,25 @@
#ifndef _SWG_OBJECT_H_
#define _SWG_OBJECT_H_
#include <QJsonValue>
#include
<QJsonValue>
class SWGObject {
public:
class SWGObject {
public:
virtual QJsonObject* asJsonObject() {
return NULL;
return NULL;
}
virtual ~SWGObject() {}
virtual SWGObject* fromJson(QString &jsonString) {
Q_UNUSED(jsonString);
return NULL;
Q_UNUSED(jsonString);
return NULL;
}
virtual void fromJsonObject(QJsonObject &json) {
Q_UNUSED(json);
Q_UNUSED(json);
}
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 <QJsonArray>
#include <QObject>
#include <QDebug>
#include
<QJsonDocument>
#include
<QJsonArray>
#include
<QObject>
#include
<QDebug>
namespace Swagger {
namespace Swagger {
SWGOrder::SWGOrder(QString* json) {
init();
this->fromJson(*json);
}
SWGOrder::SWGOrder(QString* json) {
init();
this->fromJson(*json);
}
SWGOrder::SWGOrder() {
init();
}
SWGOrder::SWGOrder() {
init();
}
SWGOrder::~SWGOrder() {
this->cleanup();
}
SWGOrder::~SWGOrder() {
this->cleanup();
}
void
SWGOrder::init() {
void
SWGOrder::init() {
id = 0L;
petId = 0L;
quantity = 0;
@ -33,34 +37,34 @@ SWGOrder::init() {
status = new QString("");
complete = false;
}
}
void
SWGOrder::cleanup() {
void
SWGOrder::cleanup() {
if(shipDate != NULL) {
delete shipDate;
}
delete shipDate;
}
if(status != NULL) {
delete status;
}
delete status;
}
}
}
SWGOrder*
SWGOrder::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
SWGOrder*
SWGOrder::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
SWGOrder::fromJsonObject(QJsonObject &pJson) {
void
SWGOrder::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", "");
setValue(&petId, pJson["petId"], "qint64", "");
setValue(&quantity, pJson["quantity"], "qint32", "");
@ -68,97 +72,104 @@ SWGOrder::fromJsonObject(QJsonObject &pJson) {
setValue(&status, pJson["status"], "QString", "QString");
setValue(&complete, pJson["complete"], "bool", "");
}
}
QString
SWGOrder::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QString
SWGOrder::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonObject*
SWGOrder::asJsonObject() {
QJsonObject* obj = new QJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject*
SWGOrder::asJsonObject() {
QJsonObject* obj = new QJsonObject();
obj->insert("id", QJsonValue(id));
obj->insert("petId", QJsonValue(petId));
obj->insert("quantity", QJsonValue(quantity));
toJsonValue(QString("shipDate"), shipDate, obj, QString("QDateTime"));
toJsonValue(QString("status"), status, obj, QString("QString"));
toJsonValue(QString("shipDate"), shipDate, obj, QString("QDateTime"));
toJsonValue(QString("status"), status, obj, QString("QString"));
obj->insert("complete", QJsonValue(complete));
return obj;
}
return obj;
}
qint64
SWGOrder::getId() {
return id;
}
void
SWGOrder::setId(qint64 id) {
this->id = id;
}
qint64
SWGOrder::getId() {
return id;
}
void
SWGOrder::setId(qint64 id) {
this->id = id;
}
qint64
SWGOrder::getPetId() {
return petId;
}
void
SWGOrder::setPetId(qint64 petId) {
this->petId = petId;
}
qint64
SWGOrder::getPetId() {
return petId;
}
void
SWGOrder::setPetId(qint64 petId) {
this->petId = petId;
}
qint32
SWGOrder::getQuantity() {
return quantity;
}
void
SWGOrder::setQuantity(qint32 quantity) {
this->quantity = quantity;
}
qint32
SWGOrder::getQuantity() {
return quantity;
}
void
SWGOrder::setQuantity(qint32 quantity) {
this->quantity = quantity;
}
QDateTime*
SWGOrder::getShipDate() {
return shipDate;
}
void
SWGOrder::setShipDate(QDateTime* shipDate) {
this->shipDate = shipDate;
}
QDateTime*
SWGOrder::getShipDate() {
return shipDate;
}
void
SWGOrder::setShipDate(QDateTime* shipDate) {
this->shipDate = shipDate;
}
QString*
SWGOrder::getStatus() {
return status;
}
void
SWGOrder::setStatus(QString* status) {
this->status = status;
}
QString*
SWGOrder::getStatus() {
return status;
}
void
SWGOrder::setStatus(QString* status) {
this->status = status;
}
bool
SWGOrder::getComplete() {
return complete;
}
void
SWGOrder::setComplete(bool complete) {
this->complete = complete;
}
bool
SWGOrder::getComplete() {
return complete;
}
void
SWGOrder::setComplete(bool complete) {
this->complete = complete;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -1,51 +1,52 @@
/*
* SWGOrder.h
*
*
*/
* SWGOrder.h
*
*
*/
#ifndef SWGOrder_H_
#define SWGOrder_H_
#include <QJsonObject>
#include
<QJsonObject>
#include "QDateTime.h"
#include <QString>
#include "SWGObject.h"
#include "SWGObject.h"
namespace Swagger {
namespace Swagger {
class SWGOrder: public SWGObject {
public:
class SWGOrder: public SWGObject {
public:
SWGOrder();
SWGOrder(QString* json);
virtual ~SWGOrder();
void init();
void cleanup();
virtual ~SWGOrder();
void init();
void cleanup();
QString asJson ();
QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json);
QString asJson ();
QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json);
SWGOrder* fromJson(QString &jsonString);
qint64 getId();
void setId(qint64 id);
void setId(qint64 id);
qint64 getPetId();
void setPetId(qint64 petId);
void setPetId(qint64 petId);
qint32 getQuantity();
void setQuantity(qint32 quantity);
void setQuantity(qint32 quantity);
QDateTime* getShipDate();
void setShipDate(QDateTime* shipDate);
void setShipDate(QDateTime* shipDate);
QString* getStatus();
void setStatus(QString* status);
void setStatus(QString* status);
bool getComplete();
void setComplete(bool complete);
void setComplete(bool complete);
private:
private:
qint64 id;
qint64 petId;
qint32 quantity;
@ -53,8 +54,8 @@ private:
QString* status;
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 <QJsonArray>
#include <QObject>
#include <QDebug>
#include
<QJsonDocument>
#include
<QJsonArray>
#include
<QObject>
#include
<QDebug>
namespace Swagger {
namespace Swagger {
SWGPet::SWGPet(QString* json) {
init();
this->fromJson(*json);
}
SWGPet::SWGPet(QString* json) {
init();
this->fromJson(*json);
}
SWGPet::SWGPet() {
init();
}
SWGPet::SWGPet() {
init();
}
SWGPet::~SWGPet() {
this->cleanup();
}
SWGPet::~SWGPet() {
this->cleanup();
}
void
SWGPet::init() {
void
SWGPet::init() {
id = 0L;
category = new SWGCategory();
name = new QString("");
@ -33,48 +37,48 @@ SWGPet::init() {
tags = new QList<SWGTag*>();
status = new QString("");
}
}
void
SWGPet::cleanup() {
void
SWGPet::cleanup() {
if(category != NULL) {
delete category;
}
delete category;
}
if(name != NULL) {
delete name;
}
delete name;
}
if(photoUrls != NULL) {
QList<QString*>* arr = photoUrls;
QList<QString*>* arr = photoUrls;
foreach(QString* o, *arr) {
delete o;
delete o;
}
delete photoUrls;
}
delete photoUrls;
}
if(tags != NULL) {
QList<SWGTag*>* arr = tags;
QList<SWGTag*>* arr = tags;
foreach(SWGTag* o, *arr) {
delete o;
delete o;
}
delete tags;
}
delete tags;
}
if(status != NULL) {
delete status;
}
delete status;
}
}
}
SWGPet*
SWGPet::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
SWGPet*
SWGPet::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
SWGPet::fromJsonObject(QJsonObject &pJson) {
void
SWGPet::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", "");
setValue(&category, pJson["category"], "SWGCategory", "SWGCategory");
setValue(&name, pJson["name"], "QString", "QString");
@ -82,118 +86,127 @@ SWGPet::fromJsonObject(QJsonObject &pJson) {
setValue(&tags, pJson["tags"], "QList", "SWGTag");
setValue(&status, pJson["status"], "QString", "QString");
}
}
QString
SWGPet::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QString
SWGPet::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonObject*
SWGPet::asJsonObject() {
QJsonObject* obj = new QJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject*
SWGPet::asJsonObject() {
QJsonObject* obj = new QJsonObject();
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;
QJsonArray tagsJsonArray;
toJsonArray((QList<void*>*)tags, &tagsJsonArray, "tags", "SWGTag");
QList<SWGTag*>* tagsList = tags;
QJsonArray tagsJsonArray;
toJsonArray((QList
<void*>*)tags, &tagsJsonArray, "tags", "SWGTag");
obj->insert("tags", tagsJsonArray);
toJsonValue(QString("status"), status, obj, QString("QString"));
obj->insert("tags", tagsJsonArray);
toJsonValue(QString("status"), status, obj, QString("QString"));
return obj;
}
return obj;
}
qint64
SWGPet::getId() {
return id;
}
void
SWGPet::setId(qint64 id) {
this->id = id;
}
qint64
SWGPet::getId() {
return id;
}
void
SWGPet::setId(qint64 id) {
this->id = id;
}
SWGCategory*
SWGPet::getCategory() {
return category;
}
void
SWGPet::setCategory(SWGCategory* category) {
this->category = category;
}
SWGCategory*
SWGPet::getCategory() {
return category;
}
void
SWGPet::setCategory(SWGCategory* category) {
this->category = category;
}
QString*
SWGPet::getName() {
return name;
}
void
SWGPet::setName(QString* name) {
this->name = name;
}
QString*
SWGPet::getName() {
return name;
}
void
SWGPet::setName(QString* name) {
this->name = name;
}
QList<QString*>*
SWGPet::getPhotoUrls() {
return photoUrls;
}
void
SWGPet::setPhotoUrls(QList<QString*>* photoUrls) {
this->photoUrls = photoUrls;
}
QList<QString*>*
SWGPet::getPhotoUrls() {
return photoUrls;
}
void
SWGPet::setPhotoUrls(QList<QString*>* photoUrls) {
this->photoUrls = photoUrls;
}
QList<SWGTag*>*
SWGPet::getTags() {
return tags;
}
void
SWGPet::setTags(QList<SWGTag*>* tags) {
this->tags = tags;
}
QList<SWGTag*>*
SWGPet::getTags() {
return tags;
}
void
SWGPet::setTags(QList<SWGTag*>* tags) {
this->tags = tags;
}
QString*
SWGPet::getStatus() {
return status;
}
void
SWGPet::setStatus(QString* status) {
this->status = status;
}
QString*
SWGPet::getStatus() {
return status;
}
void
SWGPet::setStatus(QString* status) {
this->status = status;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -1,13 +1,14 @@
/*
* SWGPet.h
*
*
*/
* SWGPet.h
*
*
*/
#ifndef SWGPet_H_
#define SWGPet_H_
#include <QJsonObject>
#include
<QJsonObject>
#include "SWGTag.h"
@ -15,39 +16,39 @@
#include "SWGCategory.h"
#include <QString>
#include "SWGObject.h"
#include "SWGObject.h"
namespace Swagger {
namespace Swagger {
class SWGPet: public SWGObject {
public:
class SWGPet: public SWGObject {
public:
SWGPet();
SWGPet(QString* json);
virtual ~SWGPet();
void init();
void cleanup();
virtual ~SWGPet();
void init();
void cleanup();
QString asJson ();
QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json);
QString asJson ();
QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json);
SWGPet* fromJson(QString &jsonString);
qint64 getId();
void setId(qint64 id);
void setId(qint64 id);
SWGCategory* getCategory();
void setCategory(SWGCategory* category);
void setCategory(SWGCategory* category);
QString* getName();
void setName(QString* name);
void setName(QString* name);
QList<QString*>* getPhotoUrls();
void setPhotoUrls(QList<QString*>* photoUrls);
void setPhotoUrls(QList<QString*>* photoUrls);
QList<SWGTag*>* getTags();
void setTags(QList<SWGTag*>* tags);
void setTags(QList<SWGTag*>* tags);
QString* getStatus();
void setStatus(QString* status);
void setStatus(QString* status);
private:
private:
qint64 id;
SWGCategory* category;
QString* name;
@ -55,8 +56,8 @@ private:
QList<SWGTag*>* tags;
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 "SWGHttpRequest.h"
#include <QObject>
#include
<QObject>
namespace Swagger {
namespace Swagger {
class SWGPetApi: public QObject {
class SWGPetApi: public QObject {
Q_OBJECT
public:
public:
SWGPetApi();
SWGPetApi(QString host, QString basePath);
~SWGPetApi();
@ -27,11 +28,16 @@ public:
void findPetsByStatus(QList<QString*>* status);
void findPetsByTags(QList<QString*>* tags);
void getPetById(qint64 petId);
void updatePetWithForm(QString* petId, QString* name, QString* status);
void deletePet(QString* apiKey, qint64 petId);
void uploadFile(qint64 petId, QString* additionalMetadata, SWGHttpRequestInputFileElement* file);
void updatePetWithForm(QString* petId
, QString* name
, QString* status);
void deletePet(QString* apiKey
, qint64 petId);
void uploadFile(qint64 petId
, QString* additionalMetadata
, SWGHttpRequestInputFileElement* file);
private:
private:
void updatePetCallback (HttpRequestWorker * worker);
void addPetCallback (HttpRequestWorker * worker);
void findPetsByStatusCallback (HttpRequestWorker * worker);
@ -41,7 +47,7 @@ private:
void deletePetCallback (HttpRequestWorker * worker);
void uploadFileCallback (HttpRequestWorker * worker);
signals:
signals:
void updatePetSignal();
void addPetSignal();
void findPetsByStatusSignal(QList<SWGPet*>* summary);
@ -51,6 +57,6 @@ signals:
void deletePetSignal();
void uploadFileSignal();
};
}
#endif
};
}
#endif

View File

@ -2,238 +2,249 @@
#include "SWGHelpers.h"
#include "SWGModelFactory.h"
#include <QJsonArray>
#include <QJsonDocument>
#include
<QJsonArray>
#include
<QJsonDocument>
namespace Swagger {
SWGStoreApi::SWGStoreApi() {}
namespace Swagger {
SWGStoreApi::SWGStoreApi() {}
SWGStoreApi::~SWGStoreApi() {}
SWGStoreApi::~SWGStoreApi() {}
SWGStoreApi::SWGStoreApi(QString host, QString basePath) {
this->host = host;
this->basePath = basePath;
}
SWGStoreApi::SWGStoreApi(QString host, QString basePath) {
this->host = host;
this->basePath = basePath;
}
void
SWGStoreApi::getInventory() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/inventory");
void
SWGStoreApi::getInventory() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/inventory");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::getInventoryCallback);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::getInventoryCallback);
worker->execute(&input);
}
worker->execute(&input);
}
void
SWGStoreApi::getInventoryCallback(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;
}
void
SWGStoreApi::getInventoryCallback(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;
}
QMap<QString, qint32>* output = new QMap<QString, qint32>();
QMap<QString, qint32>* output = new QMap<QString, qint32>();
QString json(worker->response);
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject obj = doc.object();
QString json(worker->response);
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject obj = doc.object();
foreach(QString key, obj.keys()) {
qint32* val;
setValue(&val, obj[key], "QMap", "");
output->insert(key, *val);
}
foreach(QString key, obj.keys()) {
qint32* val;
setValue(&val, obj[key], "QMap", "");
output->insert(key, *val);
}
worker->deleteLater();
worker->deleteLater();
emit getInventorySignal(output);
}
void
SWGStoreApi::placeOrder(SWGOrder body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order");
emit getInventorySignal(output);
}
void
SWGStoreApi::placeOrder(SWGOrder body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order");
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);
QString output = body.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::placeOrderCallback);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::placeOrderCallback);
worker->execute(&input);
}
worker->execute(&input);
}
void
SWGStoreApi::placeOrderCallback(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;
}
void
SWGStoreApi::placeOrderCallback(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;
}
QString json(worker->response);
SWGOrder* output = static_cast<SWGOrder*>(create(json, QString("SWGOrder")));
QString json(worker->response);
SWGOrder* output = static_cast<SWGOrder*>(create(json,
QString("SWGOrder")));
worker->deleteLater();
worker->deleteLater();
emit placeOrderSignal(output);
}
void
SWGStoreApi::getOrderById(QString* orderId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
emit placeOrderSignal(output);
}
void
SWGStoreApi::getOrderById(QString* orderId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId));
QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::getOrderByIdCallback);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::getOrderByIdCallback);
worker->execute(&input);
}
worker->execute(&input);
}
void
SWGStoreApi::getOrderByIdCallback(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;
}
void
SWGStoreApi::getOrderByIdCallback(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;
}
QString json(worker->response);
SWGOrder* output = static_cast<SWGOrder*>(create(json, QString("SWGOrder")));
QString json(worker->response);
SWGOrder* output = static_cast<SWGOrder*>(create(json,
QString("SWGOrder")));
worker->deleteLater();
worker->deleteLater();
emit getOrderByIdSignal(output);
}
void
SWGStoreApi::deleteOrder(QString* orderId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
emit getOrderByIdSignal(output);
}
void
SWGStoreApi::deleteOrder(QString* orderId) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/store/order/{orderId}");
QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId));
QString orderIdPathParam("{"); orderIdPathParam.append("orderId").append("}");
fullPath.replace(orderIdPathParam, stringValue(orderId));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::deleteOrderCallback);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGStoreApi::deleteOrderCallback);
worker->execute(&input);
}
worker->execute(&input);
}
void
SWGStoreApi::deleteOrderCallback(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;
}
void
SWGStoreApi::deleteOrderCallback(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;
}
worker->deleteLater();
worker->deleteLater();
emit deleteOrderSignal();
}
} /* namespace Swagger */
emit deleteOrderSignal();
}
} /* namespace Swagger */

View File

@ -7,14 +7,15 @@
#include "SWGOrder.h"
#include <QString>
#include <QObject>
#include
<QObject>
namespace Swagger {
namespace Swagger {
class SWGStoreApi: public QObject {
class SWGStoreApi: public QObject {
Q_OBJECT
public:
public:
SWGStoreApi();
SWGStoreApi(QString host, QString basePath);
~SWGStoreApi();
@ -27,18 +28,18 @@ public:
void getOrderById(QString* orderId);
void deleteOrder(QString* orderId);
private:
private:
void getInventoryCallback (HttpRequestWorker * worker);
void placeOrderCallback (HttpRequestWorker * worker);
void getOrderByIdCallback (HttpRequestWorker * worker);
void deleteOrderCallback (HttpRequestWorker * worker);
signals:
signals:
void getInventorySignal(QMap<QString, qint32>* summary);
void placeOrderSignal(SWGOrder* summary);
void getOrderByIdSignal(SWGOrder* summary);
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 <QJsonArray>
#include <QObject>
#include <QDebug>
#include
<QJsonDocument>
#include
<QJsonArray>
#include
<QObject>
#include
<QDebug>
namespace Swagger {
namespace Swagger {
SWGTag::SWGTag(QString* json) {
init();
this->fromJson(*json);
}
SWGTag::SWGTag(QString* json) {
init();
this->fromJson(*json);
}
SWGTag::SWGTag() {
init();
}
SWGTag::SWGTag() {
init();
}
SWGTag::~SWGTag() {
this->cleanup();
}
SWGTag::~SWGTag() {
this->cleanup();
}
void
SWGTag::init() {
void
SWGTag::init() {
id = 0L;
name = new QString("");
}
}
void
SWGTag::cleanup() {
void
SWGTag::cleanup() {
if(name != NULL) {
delete name;
}
delete name;
}
}
}
SWGTag*
SWGTag::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
SWGTag*
SWGTag::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
SWGTag::fromJsonObject(QJsonObject &pJson) {
void
SWGTag::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", "");
setValue(&name, pJson["name"], "QString", "QString");
}
}
QString
SWGTag::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QString
SWGTag::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonObject*
SWGTag::asJsonObject() {
QJsonObject* obj = new QJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject*
SWGTag::asJsonObject() {
QJsonObject* obj = new QJsonObject();
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() {
return id;
}
void
SWGTag::setId(qint64 id) {
this->id = id;
}
qint64
SWGTag::getId() {
return id;
}
void
SWGTag::setId(qint64 id) {
this->id = id;
}
QString*
SWGTag::getName() {
return name;
}
void
SWGTag::setName(QString* name) {
this->name = name;
}
QString*
SWGTag::getName() {
return name;
}
void
SWGTag::setName(QString* name) {
this->name = name;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -1,47 +1,48 @@
/*
* SWGTag.h
*
*
*/
* SWGTag.h
*
*
*/
#ifndef SWGTag_H_
#define SWGTag_H_
#include <QJsonObject>
#include
<QJsonObject>
#include <QString>
#include "SWGObject.h"
#include "SWGObject.h"
namespace Swagger {
namespace Swagger {
class SWGTag: public SWGObject {
public:
class SWGTag: public SWGObject {
public:
SWGTag();
SWGTag(QString* json);
virtual ~SWGTag();
void init();
void cleanup();
virtual ~SWGTag();
void init();
void cleanup();
QString asJson ();
QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json);
QString asJson ();
QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json);
SWGTag* fromJson(QString &jsonString);
qint64 getId();
void setId(qint64 id);
void setId(qint64 id);
QString* getName();
void setName(QString* name);
void setName(QString* name);
private:
private:
qint64 id;
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 <QJsonArray>
#include <QObject>
#include <QDebug>
#include
<QJsonDocument>
#include
<QJsonArray>
#include
<QObject>
#include
<QDebug>
namespace Swagger {
namespace Swagger {
SWGUser::SWGUser(QString* json) {
init();
this->fromJson(*json);
}
SWGUser::SWGUser(QString* json) {
init();
this->fromJson(*json);
}
SWGUser::SWGUser() {
init();
}
SWGUser::SWGUser() {
init();
}
SWGUser::~SWGUser() {
this->cleanup();
}
SWGUser::~SWGUser() {
this->cleanup();
}
void
SWGUser::init() {
void
SWGUser::init() {
id = 0L;
username = new QString("");
firstName = new QString("");
@ -35,44 +39,44 @@ SWGUser::init() {
phone = new QString("");
userStatus = 0;
}
}
void
SWGUser::cleanup() {
void
SWGUser::cleanup() {
if(username != NULL) {
delete username;
}
delete username;
}
if(firstName != NULL) {
delete firstName;
}
delete firstName;
}
if(lastName != NULL) {
delete lastName;
}
delete lastName;
}
if(email != NULL) {
delete email;
}
delete email;
}
if(password != NULL) {
delete password;
}
delete password;
}
if(phone != NULL) {
delete phone;
}
delete phone;
}
}
}
SWGUser*
SWGUser::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
SWGUser*
SWGUser::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
SWGUser::fromJsonObject(QJsonObject &pJson) {
void
SWGUser::fromJsonObject(QJsonObject &pJson) {
setValue(&id, pJson["id"], "qint64", "");
setValue(&username, pJson["username"], "QString", "QString");
setValue(&firstName, pJson["firstName"], "QString", "QString");
@ -82,137 +86,146 @@ SWGUser::fromJsonObject(QJsonObject &pJson) {
setValue(&phone, pJson["phone"], "QString", "QString");
setValue(&userStatus, pJson["userStatus"], "qint32", "");
}
}
QString
SWGUser::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QString
SWGUser::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonObject*
SWGUser::asJsonObject() {
QJsonObject* obj = new QJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject*
SWGUser::asJsonObject() {
QJsonObject* obj = new QJsonObject();
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("email"), email, obj, QString("QString"));
toJsonValue(QString("password"), password, obj, QString("QString"));
toJsonValue(QString("phone"), phone, obj, QString("QString"));
toJsonValue(QString("password"), password, obj, QString("QString"));
toJsonValue(QString("phone"), phone, obj, QString("QString"));
obj->insert("userStatus", QJsonValue(userStatus));
return obj;
}
return obj;
}
qint64
SWGUser::getId() {
return id;
}
void
SWGUser::setId(qint64 id) {
this->id = id;
}
qint64
SWGUser::getId() {
return id;
}
void
SWGUser::setId(qint64 id) {
this->id = id;
}
QString*
SWGUser::getUsername() {
return username;
}
void
SWGUser::setUsername(QString* username) {
this->username = username;
}
QString*
SWGUser::getUsername() {
return username;
}
void
SWGUser::setUsername(QString* username) {
this->username = username;
}
QString*
SWGUser::getFirstName() {
return firstName;
}
void
SWGUser::setFirstName(QString* firstName) {
this->firstName = firstName;
}
QString*
SWGUser::getFirstName() {
return firstName;
}
void
SWGUser::setFirstName(QString* firstName) {
this->firstName = firstName;
}
QString*
SWGUser::getLastName() {
return lastName;
}
void
SWGUser::setLastName(QString* lastName) {
this->lastName = lastName;
}
QString*
SWGUser::getLastName() {
return lastName;
}
void
SWGUser::setLastName(QString* lastName) {
this->lastName = lastName;
}
QString*
SWGUser::getEmail() {
return email;
}
void
SWGUser::setEmail(QString* email) {
this->email = email;
}
QString*
SWGUser::getEmail() {
return email;
}
void
SWGUser::setEmail(QString* email) {
this->email = email;
}
QString*
SWGUser::getPassword() {
return password;
}
void
SWGUser::setPassword(QString* password) {
this->password = password;
}
QString*
SWGUser::getPassword() {
return password;
}
void
SWGUser::setPassword(QString* password) {
this->password = password;
}
QString*
SWGUser::getPhone() {
return phone;
}
void
SWGUser::setPhone(QString* phone) {
this->phone = phone;
}
QString*
SWGUser::getPhone() {
return phone;
}
void
SWGUser::setPhone(QString* phone) {
this->phone = phone;
}
qint32
SWGUser::getUserStatus() {
return userStatus;
}
void
SWGUser::setUserStatus(qint32 userStatus) {
this->userStatus = userStatus;
}
qint32
SWGUser::getUserStatus() {
return userStatus;
}
void
SWGUser::setUserStatus(qint32 userStatus) {
this->userStatus = userStatus;
}
} /* namespace Swagger */
} /* namespace Swagger */

View File

@ -1,54 +1,55 @@
/*
* SWGUser.h
*
*
*/
* SWGUser.h
*
*
*/
#ifndef SWGUser_H_
#define SWGUser_H_
#include <QJsonObject>
#include
<QJsonObject>
#include <QString>
#include "SWGObject.h"
#include "SWGObject.h"
namespace Swagger {
namespace Swagger {
class SWGUser: public SWGObject {
public:
class SWGUser: public SWGObject {
public:
SWGUser();
SWGUser(QString* json);
virtual ~SWGUser();
void init();
void cleanup();
virtual ~SWGUser();
void init();
void cleanup();
QString asJson ();
QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json);
QString asJson ();
QJsonObject* asJsonObject();
void fromJsonObject(QJsonObject &json);
SWGUser* fromJson(QString &jsonString);
qint64 getId();
void setId(qint64 id);
void setId(qint64 id);
QString* getUsername();
void setUsername(QString* username);
void setUsername(QString* username);
QString* getFirstName();
void setFirstName(QString* firstName);
void setFirstName(QString* firstName);
QString* getLastName();
void setLastName(QString* lastName);
void setLastName(QString* lastName);
QString* getEmail();
void setEmail(QString* email);
void setEmail(QString* email);
QString* getPassword();
void setPassword(QString* password);
void setPassword(QString* password);
QString* getPhone();
void setPhone(QString* phone);
void setPhone(QString* phone);
qint32 getUserStatus();
void setUserStatus(qint32 userStatus);
void setUserStatus(qint32 userStatus);
private:
private:
qint64 id;
QString* username;
QString* firstName;
@ -58,8 +59,8 @@ private:
QString* phone;
qint32 userStatus;
};
};
} /* namespace Swagger */
} /* namespace Swagger */
#endif /* SWGUser_H_ */
#endif /* SWGUser_H_ */

View File

@ -2,442 +2,463 @@
#include "SWGHelpers.h"
#include "SWGModelFactory.h"
#include <QJsonArray>
#include <QJsonDocument>
#include
<QJsonArray>
#include
<QJsonDocument>
namespace Swagger {
SWGUserApi::SWGUserApi() {}
namespace Swagger {
SWGUserApi::SWGUserApi() {}
SWGUserApi::~SWGUserApi() {}
SWGUserApi::~SWGUserApi() {}
SWGUserApi::SWGUserApi(QString host, QString basePath) {
this->host = host;
this->basePath = basePath;
}
SWGUserApi::SWGUserApi(QString host, QString basePath) {
this->host = host;
this->basePath = basePath;
}
void
SWGUserApi::createUser(SWGUser body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user");
void
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);
QString output = body.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUserCallback);
worker->execute(&input);
}
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUserCallback);
void
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;
}
worker->execute(&input);
}
void
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;
}
worker->deleteLater();
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();
HttpRequestInput input(fullPath, "POST");
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList<void*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUsersWithArrayInputCallback);
worker->execute(&input);
}
void
SWGUserApi::createUsersWithArrayInputCallback(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;
}
worker->deleteLater();
emit createUsersWithArrayInputSignal();
}
void
SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithList");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList<void*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUsersWithListInputCallback);
worker->execute(&input);
}
void
SWGUserApi::createUsersWithListInputCallback(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;
}
worker->deleteLater();
emit createUsersWithListInputSignal();
}
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"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(username)));
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("password"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(password)));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::loginUserCallback);
worker->execute(&input);
}
void
SWGUserApi::loginUserCallback(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;
}
QString json(worker->response);
QString* output = static_cast<QString*>(create(json, QString("QString")));
worker->deleteLater();
emit loginUserSignal(output);
}
void
SWGUserApi::logoutUser() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/logout");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::logoutUserCallback);
worker->execute(&input);
}
void
SWGUserApi::logoutUserCallback(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;
}
worker->deleteLater();
emit logoutUserSignal();
}
void
SWGUserApi::getUserByName(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));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::getUserByNameCallback);
worker->execute(&input);
}
void
SWGUserApi::getUserByNameCallback(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;
}
QString json(worker->response);
SWGUser* output = static_cast<SWGUser*>(create(json, QString("SWGUser")));
worker->deleteLater();
emit getUserByNameSignal(output);
}
void
SWGUserApi::updateUser(QString* username, SWGUser body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "PUT");
QString output = body.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::updateUserCallback);
worker->execute(&input);
}
void
SWGUserApi::updateUserCallback(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;
}
worker->deleteLater();
emit updateUserSignal();
}
void
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));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::deleteUserCallback);
worker->execute(&input);
}
void
SWGUserApi::deleteUserCallback(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;
}
worker->deleteLater();
emit deleteUserSignal();
}
} /* namespace Swagger */
QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUsersWithArrayInputCallback);
worker->execute(&input);
}
void
SWGUserApi::createUsersWithArrayInputCallback(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;
}
worker->deleteLater();
emit createUsersWithArrayInputSignal();
}
void
SWGUserApi::createUsersWithListInput(QList<SWGUser*>* body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/createWithList");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "POST");
QJsonArray* bodyArray = new QJsonArray();
toJsonArray((QList
<void
*>*)body, bodyArray, QString("body"), QString("SWGUser*"));
QJsonDocument doc(*bodyArray);
QByteArray bytes = doc.toJson();
input.request_body.append(bytes);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::createUsersWithListInputCallback);
worker->execute(&input);
}
void
SWGUserApi::createUsersWithListInputCallback(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;
}
worker->deleteLater();
emit createUsersWithListInputSignal();
}
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"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(username)));
if(fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append(QUrl::toPercentEncoding("password"))
.append("=")
.append(QUrl::toPercentEncoding(stringValue(password)));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::loginUserCallback);
worker->execute(&input);
}
void
SWGUserApi::loginUserCallback(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;
}
QString json(worker->response);
QString* output = static_cast<QString*>(create(json,
QString("QString")));
worker->deleteLater();
emit loginUserSignal(output);
}
void
SWGUserApi::logoutUser() {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/logout");
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::logoutUserCallback);
worker->execute(&input);
}
void
SWGUserApi::logoutUserCallback(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;
}
worker->deleteLater();
emit logoutUserSignal();
}
void
SWGUserApi::getUserByName(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));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "GET");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::getUserByNameCallback);
worker->execute(&input);
}
void
SWGUserApi::getUserByNameCallback(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;
}
QString json(worker->response);
SWGUser* output = static_cast<SWGUser*>(create(json,
QString("SWGUser")));
worker->deleteLater();
emit getUserByNameSignal(output);
}
void
SWGUserApi::updateUser(QString* username
, SWGUser body) {
QString fullPath;
fullPath.append(this->host).append(this->basePath).append("/user/{username}");
QString usernamePathParam("{"); usernamePathParam.append("username").append("}");
fullPath.replace(usernamePathParam, stringValue(username));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "PUT");
QString output = body.asJson();
input.request_body.append(output);
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::updateUserCallback);
worker->execute(&input);
}
void
SWGUserApi::updateUserCallback(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;
}
worker->deleteLater();
emit updateUserSignal();
}
void
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));
HttpRequestWorker *worker = new HttpRequestWorker();
HttpRequestInput input(fullPath, "DELETE");
connect(worker,
&HttpRequestWorker::on_execution_finished,
this,
&SWGUserApi::deleteUserCallback);
worker->execute(&input);
}
void
SWGUserApi::deleteUserCallback(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;
}
worker->deleteLater();
emit deleteUserSignal();
}
} /* namespace Swagger */

View File

@ -7,14 +7,15 @@
#include <QList>
#include <QString>
#include <QObject>
#include
<QObject>
namespace Swagger {
namespace Swagger {
class SWGUserApi: public QObject {
class SWGUserApi: public QObject {
Q_OBJECT
public:
public:
SWGUserApi();
SWGUserApi(QString host, QString basePath);
~SWGUserApi();
@ -25,13 +26,15 @@ public:
void createUser(SWGUser body);
void createUsersWithArrayInput(QList<SWGUser*>* body);
void createUsersWithListInput(QList<SWGUser*>* body);
void loginUser(QString* username, QString* password);
void loginUser(QString* username
, QString* password);
void logoutUser();
void getUserByName(QString* username);
void updateUser(QString* username, SWGUser body);
void updateUser(QString* username
, SWGUser body);
void deleteUser(QString* username);
private:
private:
void createUserCallback (HttpRequestWorker * worker);
void createUsersWithArrayInputCallback (HttpRequestWorker * worker);
void createUsersWithListInputCallback (HttpRequestWorker * worker);
@ -41,7 +44,7 @@ private:
void updateUserCallback (HttpRequestWorker * worker);
void deleteUserCallback (HttpRequestWorker * worker);
signals:
signals:
void createUserSignal();
void createUsersWithArrayInputSignal();
void createUsersWithListInputSignal();
@ -51,6 +54,6 @@ signals:
void updateUserSignal();
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">
<modelVersion>4.0.0</modelVersion>
<groupId>io.swagger</groupId>
@ -77,7 +77,8 @@
</goals>
<configuration>
<sources>
<source>src/main/java</source>
<source>
src/main/java</source>
</sources>
</configuration>
</execution>
@ -89,7 +90,8 @@
</goals>
<configuration>
<sources>
<source>src/test/java</source>
<source>
src/test/java</source>
</sources>
</configuration>
</execution>
@ -100,7 +102,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<source>
1.6</source>
<target>1.6</target>
</configuration>
</plugin>

View File

@ -6,19 +6,18 @@ import retrofit.RestAdapter;
import retrofit.converter.GsonConverter;
public class ServiceGenerator {
// No need to instantiate this class.
private ServiceGenerator() {
}
// No need to instantiate this class.
private ServiceGenerator() { }
public static <S> S createService(Class<S> serviceClass) {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.create();
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint("http://petstore.swagger.io/v2")
.setConverter(new GsonConverter(gson))
.build();
public static <S> S createService(Class<S> serviceClass) {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.create();
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint("http://petstore.swagger.io/v2")
.setConverter(new GsonConverter(gson))
.build();
return adapter.create(serviceClass);
return adapter.create(serviceClass);
}
}
}

View File

@ -1,117 +1,117 @@
package io.swagger.client.api;
import io.swagger.client.model.Pet;
import io.swagger.client.model.*;
import retrofit.http.*;
import retrofit.mime.*;
import java.util.*;
import java.util.List;
import io.swagger.client.model.Pet;
import java.io.File;
public interface PetApi {
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
* @return Void
*/
@PUT("/pet")
Void updatePet(
@Body Pet body
);
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
* @return Void
*/
@POST("/pet")
Void addPet(
@Body Pet 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 List<Pet>
*/
@GET("/pet/findByStatus")
List<Pet> findPetsByStatus(
@Query("status") List<String> status
);
/**
* 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
* @return List<Pet>
*/
@GET("/pet/findByTags")
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
*
* @param petId ID of pet that needs to be fetched
* @return Pet
*/
@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
* @param name Updated name of the pet
* @param status Updated status of the pet
* @return Void
*/
@FormUrlEncoded
@POST("/pet/{petId}")
Void updatePetWithForm(
@Path("petId") String petId, @Field("name") String name, @Field("status") String status
);
/**
* Deletes a pet
*
* @param apiKey
* @param petId Pet id to delete
* @return Void
*/
@DELETE("/pet/{petId}")
Void deletePet(
@Header("api_key") String apiKey, @Path("petId") Long petId
);
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
* @return Void
*/
@Multipart
@POST("/pet/{petId}/uploadImage")
Void uploadFile(
@Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file
);
}
public interface PetApi {
/**
* Update an existing pet
*
* @param body Pet object that needs to be added to the store
* @return Void
*/
@PUT("/pet")
Void updatePet(
@Body Pet body
);
/**
* Add a new pet to the store
*
* @param body Pet object that needs to be added to the store
* @return Void
*/
@POST("/pet")
Void addPet(
@Body Pet 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 List<Pet>
*/
@GET("/pet/findByStatus")
List<Pet> findPetsByStatus(
@Query("status") List<String> status
);
/**
* 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
* @return List<Pet>
*/
@GET("/pet/findByTags")
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
* @param petId ID of pet that needs to be fetched
* @return Pet
*/
@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
* @param name Updated name of the pet
* @param status Updated status of the pet
* @return Void
*/
@FormUrlEncoded
@POST("/pet/{petId}")
Void updatePetWithForm(
@Path("petId") String petId,@Field("name") String name,@Field("status") String status
);
/**
* Deletes a pet
*
* @param apiKey
* @param petId Pet id to delete
* @return Void
*/
@DELETE("/pet/{petId}")
Void deletePet(
@Header("api_key") String apiKey,@Path("petId") Long petId
);
/**
* uploads an image
*
* @param petId ID of pet to update
* @param additionalMetadata Additional data to pass to server
* @param file file to upload
* @return Void
*/
@Multipart
@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;
import io.swagger.client.model.Order;
import io.swagger.client.model.*;
import retrofit.http.*;
import retrofit.mime.*;
import java.util.*;
import java.util.Map;
import io.swagger.client.model.Order;
public interface StoreApi {
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
*
* @return Map<String, Integer>
*/
@GET("/store/inventory")
Map<String, Integer> getInventory();
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Order
*/
@POST("/store/order")
Order placeOrder(
@Body Order body
);
/**
* Find purchase order by ID
* 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
*/
@GET("/store/order/{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
*
* @param orderId ID of the order that needs to be deleted
* @return Void
*/
@DELETE("/store/order/{orderId}")
Void deleteOrder(
@Path("orderId") String orderId
);
}
public interface StoreApi {
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* @return Map<String, Integer>
*/
@GET("/store/inventory")
Map<String, Integer> getInventory();
/**
* Place an order for a pet
*
* @param body order placed for purchasing the pet
* @return Order
*/
@POST("/store/order")
Order placeOrder(
@Body Order body
);
/**
* Find purchase order by ID
* 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
*/
@GET("/store/order/{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
* @param orderId ID of the order that needs to be deleted
* @return Void
*/
@DELETE("/store/order/{orderId}")
Void deleteOrder(
@Path("orderId") String orderId
);
}

View File

@ -1,110 +1,110 @@
package io.swagger.client.api;
import io.swagger.client.model.User;
import io.swagger.client.model.*;
import retrofit.http.*;
import retrofit.mime.*;
import java.util.*;
import java.util.List;
import io.swagger.client.model.User;
import java.util.*;
public interface UserApi {
/**
* Create user
* This can only be done by the logged in user.
*
* @param body Created user object
* @return Void
*/
@POST("/user")
Void createUser(
@Body User body
);
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return Void
*/
@POST("/user/createWithArray")
Void createUsersWithArrayInput(
@Body List<User> body
);
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return Void
*/
@POST("/user/createWithList")
Void createUsersWithListInput(
@Body List<User> body
);
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return String
*/
@GET("/user/login")
String loginUser(
@Query("username") String username, @Query("password") String password
);
/**
* Logs out current logged in user session
*
* @return Void
*/
@GET("/user/logout")
Void logoutUser();
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
@GET("/user/{username}")
User getUserByName(
@Path("username") String username
);
/**
* 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 Void
*/
@PUT("/user/{username}")
Void updateUser(
@Path("username") String username, @Body User body
);
/**
* Delete user
* This can only be done by the logged in user.
*
* @param username The name that needs to be deleted
* @return Void
*/
@DELETE("/user/{username}")
Void deleteUser(
@Path("username") String username
);
}
public interface UserApi {
/**
* Create user
* This can only be done by the logged in user.
* @param body Created user object
* @return Void
*/
@POST("/user")
Void createUser(
@Body User body
);
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return Void
*/
@POST("/user/createWithArray")
Void createUsersWithArrayInput(
@Body List<User> body
);
/**
* Creates list of users with given input array
*
* @param body List of user object
* @return Void
*/
@POST("/user/createWithList")
Void createUsersWithListInput(
@Body List<User> body
);
/**
* Logs user into the system
*
* @param username The user name for login
* @param password The password for login in clear text
* @return String
*/
@GET("/user/login")
String loginUser(
@Query("username") String username,@Query("password") String password
);
/**
* Logs out current logged in user session
*
* @return Void
*/
@GET("/user/logout")
Void logoutUser();
/**
* Get user by user name
*
* @param username The name that needs to be fetched. Use user1 for testing.
* @return User
*/
@GET("/user/{username}")
User getUserByName(
@Path("username") String username
);
/**
* 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 Void
*/
@PUT("/user/{username}")
Void updateUser(
@Path("username") String username,@Body User body
);
/**
* Delete user
* This can only be done by the logged in user.
* @param username The name that needs to be deleted
* @return Void
*/
@DELETE("/user/{username}")
Void deleteUser(
@Path("username") String username
);
}

View File

@ -1,50 +1,50 @@
package io.swagger.client.model;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class Category {
@ApiModel(description = "")
public class Category {
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("id")
private Long id = null;
private Long id = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("name")
private String name = null;
private String name = null;
public Long getId() {
public Long getId() {
return id;
}
public void setId(Long id) {
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
}
public String getName() {
return name;
}
public void setName(String name) {
}
public void setName(String name) {
this.name = name;
}
}
@Override
public String toString() {
StringBuilder 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();
public String toString() {
StringBuilder 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();
}
}
}

View File

@ -1,115 +1,111 @@
package io.swagger.client.model;
import com.google.gson.annotations.SerializedName;
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 = "")
@SerializedName("id")
private Long id = null;
private Long id = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("petId")
private Long petId = null;
private Long petId = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("quantity")
private Integer quantity = null;
private Integer quantity = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("shipDate")
private Date shipDate = null;
private Date shipDate = null;
public enum StatusEnum {
placed, approved, delivered,
};
/**
* Order Status
**/
* Order Status
**/
@ApiModelProperty(value = "Order Status")
@SerializedName("status")
private StatusEnum status = null;
private StatusEnum status = null;
;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("complete")
private Boolean complete = null;
private Boolean complete = null;
public Long getId() {
public Long getId() {
return id;
}
public void setId(Long id) {
}
public void setId(Long id) {
this.id = id;
}
public Long getPetId() {
}
public Long getPetId() {
return petId;
}
public void setPetId(Long petId) {
}
public void setPetId(Long petId) {
this.petId = petId;
}
public Integer getQuantity() {
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Date getShipDate() {
}
public Date getShipDate() {
return shipDate;
}
public void setShipDate(Date shipDate) {
}
public void setShipDate(Date shipDate) {
this.shipDate = shipDate;
}
public StatusEnum getStatus() {
}
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
}
public void setStatus(StatusEnum status) {
this.status = status;
}
public Boolean getComplete() {
}
public Boolean getComplete() {
return complete;
}
public void setComplete(Boolean complete) {
}
public void setComplete(Boolean complete) {
this.complete = complete;
}
}
@Override
public String toString() {
StringBuilder 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();
public String toString() {
StringBuilder 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();
}
public enum StatusEnum {
placed, approved, delivered,
}
}

View File

@ -1,119 +1,113 @@
package io.swagger.client.model;
import com.google.gson.annotations.SerializedName;
import io.swagger.client.model.Category;
import io.swagger.client.model.Tag;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
@ApiModel(description = "")
public class Pet {
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class Pet {
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("id")
private Long id = null;
private Long id = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("category")
private Category category = null;
private Category category = null;
/**
**/
**/
@ApiModelProperty(required = true, value = "")
@SerializedName("name")
private String name = null;
private String name = null;
/**
**/
**/
@ApiModelProperty(required = true, value = "")
@SerializedName("photoUrls")
private List<String> photoUrls = new ArrayList<String>();
private List<String> photoUrls = new ArrayList<String>() ;
/**
**/
**/
@ApiModelProperty(value = "")
@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")
@SerializedName("status")
private StatusEnum status = null;
private StatusEnum status = null;
;
public Long getId() {
public Long getId() {
return id;
}
public void setId(Long id) {
}
public void setId(Long id) {
this.id = id;
}
public Category getCategory() {
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
}
public void setCategory(Category category) {
this.category = category;
}
public String getName() {
}
public String getName() {
return name;
}
public void setName(String name) {
}
public void setName(String name) {
this.name = name;
}
public List<String> getPhotoUrls() {
}
public List<String> getPhotoUrls() {
return photoUrls;
}
public void setPhotoUrls(List<String> photoUrls) {
}
public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
}
public List<Tag> getTags() {
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public StatusEnum getStatus() {
}
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
}
public void setStatus(StatusEnum status) {
this.status = status;
}
}
@Override
public String toString() {
StringBuilder 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();
public String toString() {
StringBuilder 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();
}
public enum StatusEnum {
available, pending, sold,
}
}

View File

@ -1,50 +1,50 @@
package io.swagger.client.model;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class Tag {
@ApiModel(description = "")
public class Tag {
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("id")
private Long id = null;
private Long id = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("name")
private String name = null;
private String name = null;
public Long getId() {
public Long getId() {
return id;
}
public void setId(Long id) {
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
}
public String getName() {
return name;
}
public void setName(String name) {
}
public void setName(String name) {
this.name = name;
}
}
@Override
public String toString() {
StringBuilder 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();
public String toString() {
StringBuilder 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();
}
}
}

View File

@ -1,141 +1,135 @@
package io.swagger.client.model;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
@ApiModel(description = "")
public class User {
@ApiModel(description = "")
public class User {
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("id")
private Long id = null;
private Long id = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("username")
private String username = null;
private String username = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("firstName")
private String firstName = null;
private String firstName = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("lastName")
private String lastName = null;
private String lastName = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("email")
private String email = null;
private String email = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("password")
private String password = null;
private String password = null;
/**
**/
**/
@ApiModelProperty(value = "")
@SerializedName("phone")
private String phone = null;
private String phone = null;
/**
* User Status
**/
* User Status
**/
@ApiModelProperty(value = "User Status")
@SerializedName("userStatus")
private Integer userStatus = null;
private Integer userStatus = null;
public Long getId() {
public Long getId() {
return id;
}
public void setId(Long id) {
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getUserStatus() {
}
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
}
@Override
public String toString() {
StringBuilder 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();
public String toString() {
StringBuilder 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();
}
}
}

View File

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

View File

@ -1,328 +1,337 @@
require "uri"
module SwaggerClient
class PetApi
class PetApi
basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker
# Update an existing pet
#
# @param [Hash] opts the optional parameters
# @option opts [Pet] :body Pet object that needs to be added to the store
# @return [nil]
def self.update_pet(opts = {})
# 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 = {})
# resource path
path = "/pet".sub('{format}','json')
# resource path
path = "/pet".sub('{format}','json')
# query parameters
query_params = {}
# query parameters
query_params = {}
# header parameters
header_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 '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)
# 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 = {}
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
auth_names = ['petstore_auth']
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
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']
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil
# 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
# 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

View File

@ -1,161 +1,166 @@
require "uri"
module SwaggerClient
class StoreApi
class StoreApi
basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker
# Returns pet inventories by status
# Returns a map of status codes to quantities
# @param [Hash] opts the optional parameters
# @return [map[string,int]]
def self.get_inventory(opts = {})
# Returns pet inventories by status
# Returns a map of status codes to quantities
# @param [Hash] opts the optional parameters
# @return [map[string,int]]
def self.get_inventory(opts = {})
# resource path
path = "/store/inventory".sub('{format}','json')
# resource path
path = "/store/inventory".sub('{format}','json')
# query parameters
query_params = {}
# query parameters
query_params = {}
# header parameters
header_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 '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)
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# form parameters
form_params = {}
# http body (model)
post_body = nil
# http body (model)
post_body = nil
auth_names = ['api_key']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.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']
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) }
# 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
# 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

View File

@ -1,316 +1,325 @@
require "uri"
module SwaggerClient
class UserApi
class UserApi
basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker
# Create user
# This can only be done by the logged in user.
# @param [Hash] opts the optional parameters
# @option opts [User] :body Created user object
# @return [nil]
def self.create_user(opts = {})
# 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 = {})
# resource path
path = "/user".sub('{format}','json')
# resource path
path = "/user".sub('{format}','json')
# query parameters
query_params = {}
# query parameters
query_params = {}
# header parameters
header_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 '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)
# HTTP header 'Content-Type'
_header_content_type = []
header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type)
# form parameters
form_params = {}
# form parameters
form_params = {}
# http body (model)
post_body = Swagger::Request.object_to_http_body(opts[:'body'])
# 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_array_input(opts = {})
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
# 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
# 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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,90 +1,90 @@
# module Swagger
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
class Object
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
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
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
def stringify_keys
inject({}) do |options, (key, value)|
options[key.to_s] = value
options
end
end
end
unless Hash.method_defined? :stringify_keys!
def stringify_keys!
self.replace(self.stringify_keys)
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
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
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
class Hash
unless Hash.method_defined? :symbolize_and_underscore_keys!
def symbolize_and_underscore_keys!
self.replace(self.symbolize_and_underscore_keys)
end
end
end
unless Hash.method_defined? :stringify_keys
def stringify_keys
inject({}) do |options, (key, value)|
options[key.to_s] = value
options
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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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