Merge pull request #808 from wing328/csharp_api_instance

[C#] Added ApiClient (Pluggable) and authentication (API key and HTTP basic auth)
This commit is contained in:
Tony Tam
2015-06-05 00:42:44 -07:00
19 changed files with 1159 additions and 519 deletions

View File

@@ -41,9 +41,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig
additionalProperties.put("invokerPackage", invokerPackage);
supportingFiles.add(new SupportingFile("apiInvoker.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.cs"));
supportingFiles.add(new SupportingFile("apiException.mustache",
supportingFiles.add(new SupportingFile("Configuration.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Configuration.cs"));
supportingFiles.add(new SupportingFile("ApiClient.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiClient.cs"));
supportingFiles.add(new SupportingFile("ApiException.mustache",
(sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.cs"));
supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll"));
supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll"));

View File

@@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using RestSharp;
namespace {{invokerPackage}} {
/// <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="{{basePath}}") {
this.basePath = basePath;
this.restClient = new RestClient(this.basePath);
}
/// <summary>
/// Gets or sets the base path.
/// </summary>
/// <value>The base path.</value>
public string basePath { get; set; }
/// <summary>
/// Gets or sets the RestClient
/// </summary>
/// <value>The RestClient.</value>
public RestClient restClient { get; set; }
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 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)restClient.Execute(request);
}
/// <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);
}
/// <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>
public string EscapeString(string 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>
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);
}
}
/// <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);
}
}
/// <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>
/// 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) {
{{#authMethods}}
case "{{name}}":
{{#isApiKey}}{{#isKeyInHeader}}HeaderParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInHeader}}{{#isKeyInQuery}}QueryParams["{{keyParamName}}"] = GetApiKeyWithPrefix("{{keyParamName}}");{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}HeaderParams["Authorization"] = "Basic " + Base64Encode(Configuration.username + ":" + Configuration.password);{{/isBasic}}
{{#isOAuth}}//TODO support oauth{{/isOAuth}}
break;
{{/authMethods}}
default:
//TODO show warning about security definition not found
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);
}
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using {{invokerPackage}};
namespace {{invokerPackage}} {
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration{
/// <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>
/// Gets or sets the username (HTTP basic authentication)
/// </summary>
/// <value>The username.</value>
public static String username { get; set; }
/// <summary>
/// Gets or sets the password (HTTP basic authentication)
/// </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 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

@@ -8,35 +8,56 @@ using {{modelPackage}};
namespace {{package}} {
{{#operations}}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class {{classname}} {
string basePath;
protected RestClient restClient;
public {{classname}}(String basePath = "{{basePath}}")
{
this.basePath = basePath;
this.restClient = new RestClient(basePath);
}
/// <summary>
/// Sets the endpoint base url for the services being accessed
/// Initializes a new instance of the <see cref="{{classname}}"/> class.
/// </summary>
/// <param name="basePath"> Base URL
/// <param name="apiClient"> an instance of ApiClient (optional)
/// <returns></returns>
public void SetBasePath(string basePath) {
this.basePath = basePath;
public {{classname}}(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient;
} else {
this.apiClient = apiClient;
}
}
/// <summary>
/// Gets the endpoint base url for the services being accessed
/// <returns>Base URL</returns>
/// Initializes a new instance of the <see cref="{{classname}}"/> class.
/// </summary>
public String GetBasePath() {
return this.basePath;
/// <returns></returns>
public {{classname}}(String basePath)
{
this.apiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath(String basePath) {
return this.apiClient.basePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>The API client</value>
public ApiClient apiClient {get; set;}
{{#operation}}
/// <summary>
/// {{summary}} {{notes}}
/// </summary>
@@ -45,37 +66,41 @@ namespace {{package}} {
/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
var _request = new RestRequest("{{path}}", Method.{{httpMethod}});
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}");
{{/required}}{{/allParams}}
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
_request.AddUrlSegment("format", "json"); // set format to json by default
{{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter
var path = "{{path}}";
path = path.Replace("{format}", "json");
{{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}}));
{{/pathParams}}
{{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // query 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;
{{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter
{{/queryParams}}
{{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter
{{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // header parameter
{{/headerParams}}
{{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // form parameter{{/isFile}}
{{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}}
{{/formParams}}
{{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter
{{#bodyParam}}postBody = apiClient.Serialize({{paramName}}); // http body (model) parameter
{{/bodyParam}}
// authentication setting, if any
String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content);
}
{{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}}
{{#returnType}}return ({{{returnType}}}) apiClient.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}}
return;{{/returnType}}
}
{{/operation}}

View File

@@ -1,13 +1,27 @@
using System;
namespace {{invokerPackage}} {
/// <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>
/// 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;
}

View File

@@ -1,84 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
namespace {{invokerPackage}} {
public class ApiInvoker {
private static Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
/// <summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name
/// <param name="value"> Header field value
/// <returns></returns>
public static void AddDefaultHeader(string key, string value) {
defaultHeaderMap.Add(key, value);
}
/// <summary>
/// Get default header
/// </summary>
/// <returns>Dictionary of default header</returns>
public static Dictionary<String, String> GetDefaultHeader() {
return defaultHeaderMap;
}
/// <summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str"> String to be escaped
/// <returns>Escaped string</returns>
public static string EscapeString(string str) {
return str;
}
/// <summary>
/// if parameter is DateTime, output in ISO8601 format, otherwise just return the string
/// </summary>
/// <param name="obj"> The parameter (header, path, query, form)
/// <returns>Formatted string</returns>
public static string ParameterToString(object obj)
{
return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : 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 static 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);
}
}
/// <summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj"> Object
/// <returns>JSON string</returns>
public static string Serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
}
}

View File

@@ -3,10 +3,15 @@ using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
{{#models}}
{{#model}}
namespace {{package}} {
/// <summary>
/// {{description}}
/// </summary>
[DataContract]
public class {{classname}} {
{{#vars}}
@@ -15,6 +20,11 @@ namespace {{package}} {
public {{{datatype}}} {{name}} { get; set; }
{{/vars}}
/// <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 {{classname}} {\n");
@@ -24,7 +34,16 @@ namespace {{package}} {
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);
}
}
{{/model}}
{{/models}}
}

View File

@@ -6,34 +6,55 @@ using IO.Swagger.Model;
namespace IO.Swagger.Api {
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class PetApi {
string basePath;
protected RestClient restClient;
public PetApi(String basePath = "http://petstore.swagger.io/v2")
{
this.basePath = basePath;
this.restClient = new RestClient(basePath);
}
/// <summary>
/// Sets the endpoint base url for the services being accessed
/// Initializes a new instance of the <see cref="PetApi"/> class.
/// </summary>
/// <param name="basePath"> Base URL
/// <param name="apiClient"> an instance of ApiClient (optional)
/// <returns></returns>
public void SetBasePath(string basePath) {
this.basePath = basePath;
public PetApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient;
} else {
this.apiClient = apiClient;
}
}
/// <summary>
/// Gets the endpoint base url for the services being accessed
/// <returns>Base URL</returns>
/// Initializes a new instance of the <see cref="PetApi"/> class.
/// </summary>
public String GetBasePath() {
return this.basePath;
/// <returns></returns>
public PetApi(String basePath)
{
this.apiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath(String basePath) {
return this.apiClient.basePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>The API client</value>
public ApiClient apiClient {get; set;}
/// <summary>
/// Update an existing pet
@@ -42,26 +63,30 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void UpdatePet (Pet Body) {
var _request = new RestRequest("/pet", Method.PUT);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/pet";
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
postBody = apiClient.Serialize(Body); // http body (model) parameter
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { "petstore_auth" };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content);
}
@@ -69,7 +94,6 @@ namespace IO.Swagger.Api {
return;
}
/// <summary>
/// Add a new pet to the store
/// </summary>
@@ -77,26 +101,30 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void AddPet (Pet Body) {
var _request = new RestRequest("/pet", Method.POST);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/pet";
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
postBody = apiClient.Serialize(Body); // http body (model) parameter
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { "petstore_auth" };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content);
}
@@ -104,7 +132,6 @@ namespace IO.Swagger.Api {
return;
}
/// <summary>
/// Finds Pets by status Multiple status values can be provided with comma seperated strings
/// </summary>
@@ -112,33 +139,36 @@ namespace IO.Swagger.Api {
/// <returns>List<Pet></returns>
public List<Pet> FindPetsByStatus (List<string> Status) {
var _request = new RestRequest("/pet/findByStatus", Method.GET);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/pet/findByStatus";
path = path.Replace("{format}", "json");
_request.AddUrlSegment("format", "json"); // set format to json by default
if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // query 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;
if (Status != null) queryParams.Add("status", apiClient.ParameterToString(Status)); // query parameter
// authentication setting, if any
String[] authSettings = new String[] { "petstore_auth" };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content);
}
return (List<Pet>) ApiInvoker.Deserialize(response.Content, typeof(List<Pet>));
return (List<Pet>) apiClient.Deserialize(response.Content, typeof(List<Pet>));
}
/// <summary>
/// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
/// </summary>
@@ -146,33 +176,36 @@ namespace IO.Swagger.Api {
/// <returns>List<Pet></returns>
public List<Pet> FindPetsByTags (List<string> Tags) {
var _request = new RestRequest("/pet/findByTags", Method.GET);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/pet/findByTags";
path = path.Replace("{format}", "json");
_request.AddUrlSegment("format", "json"); // set format to json by default
if (Tags != null) _request.AddParameter("tags", ApiInvoker.ParameterToString(Tags)); // query 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;
if (Tags != null) queryParams.Add("tags", apiClient.ParameterToString(Tags)); // query parameter
// authentication setting, if any
String[] authSettings = new String[] { "petstore_auth" };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content);
}
return (List<Pet>) ApiInvoker.Deserialize(response.Content, typeof(List<Pet>));
return (List<Pet>) apiClient.Deserialize(response.Content, typeof(List<Pet>));
}
/// <summary>
/// Find pet by ID Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
/// </summary>
@@ -180,36 +213,39 @@ namespace IO.Swagger.Api {
/// <returns>Pet</returns>
public Pet GetPetById (long? PetId) {
var _request = new RestRequest("/pet/{petId}", Method.GET);
// verify the required parameter 'PetId' is set
if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling GetPetById");
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/pet/{petId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
_request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter
// authentication setting, if any
String[] authSettings = new String[] { "api_key", "petstore_auth" };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content);
}
return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet));
return (Pet) apiClient.Deserialize(response.Content, typeof(Pet));
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
@@ -219,31 +255,35 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void UpdatePetWithForm (string PetId, string Name, string Status) {
var _request = new RestRequest("/pet/{petId}", Method.POST);
// verify the required parameter 'PetId' is set
if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UpdatePetWithForm");
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/pet/{petId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
_request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter
if (Name != null) _request.AddParameter("name", ApiInvoker.ParameterToString(Name)); // form parameter
if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // form parameter
if (Name != null) formParams.Add("name", apiClient.ParameterToString(Name)); // form parameter
if (Status != null) formParams.Add("status", apiClient.ParameterToString(Status)); // form parameter
// authentication setting, if any
String[] authSettings = new String[] { "petstore_auth" };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content);
}
@@ -251,7 +291,6 @@ namespace IO.Swagger.Api {
return;
}
/// <summary>
/// Deletes a pet
/// </summary>
@@ -260,30 +299,34 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void DeletePet (string ApiKey, long? PetId) {
var _request = new RestRequest("/pet/{petId}", Method.DELETE);
// verify the required parameter 'PetId' is set
if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling DeletePet");
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/pet/{petId}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
_request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter
if (ApiKey != null) _request.AddHeader("api_key", ApiInvoker.ParameterToString(ApiKey)); // header parameter
if (ApiKey != null) headerParams.Add("api_key", apiClient.ParameterToString(ApiKey)); // header parameter
// authentication setting, if any
String[] authSettings = new String[] { "petstore_auth" };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content);
}
@@ -291,7 +334,6 @@ namespace IO.Swagger.Api {
return;
}
/// <summary>
/// uploads an image
/// </summary>
@@ -301,31 +343,35 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void UploadFile (long? PetId, string AdditionalMetadata, string File) {
var _request = new RestRequest("/pet/{petId}/uploadImage", Method.POST);
// verify the required parameter 'PetId' is set
if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UploadFile");
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/pet/{petId}/uploadImage";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "petId" + "}", apiClient.ParameterToString(PetId));
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
_request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter
if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", ApiInvoker.ParameterToString(AdditionalMetadata)); // form parameter
if (File != null) _request.AddFile("file", File);
if (AdditionalMetadata != null) formParams.Add("additionalMetadata", apiClient.ParameterToString(AdditionalMetadata)); // form parameter
if (File != null) fileParams.Add("file", File);
// authentication setting, if any
String[] authSettings = new String[] { "petstore_auth" };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content);
}

View File

@@ -6,34 +6,55 @@ using IO.Swagger.Model;
namespace IO.Swagger.Api {
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class StoreApi {
string basePath;
protected RestClient restClient;
public StoreApi(String basePath = "http://petstore.swagger.io/v2")
{
this.basePath = basePath;
this.restClient = new RestClient(basePath);
}
/// <summary>
/// Sets the endpoint base url for the services being accessed
/// Initializes a new instance of the <see cref="StoreApi"/> class.
/// </summary>
/// <param name="basePath"> Base URL
/// <param name="apiClient"> an instance of ApiClient (optional)
/// <returns></returns>
public void SetBasePath(string basePath) {
this.basePath = basePath;
public StoreApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient;
} else {
this.apiClient = apiClient;
}
}
/// <summary>
/// Gets the endpoint base url for the services being accessed
/// <returns>Base URL</returns>
/// Initializes a new instance of the <see cref="StoreApi"/> class.
/// </summary>
public String GetBasePath() {
return this.basePath;
/// <returns></returns>
public StoreApi(String basePath)
{
this.apiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath(String basePath) {
return this.apiClient.basePath;
}
/// <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
@@ -41,32 +62,35 @@ namespace IO.Swagger.Api {
/// <returns>Dictionary<String, int?></returns>
public Dictionary<String, int?> GetInventory () {
var _request = new RestRequest("/store/inventory", Method.GET);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
// authentication setting, if any
String[] authSettings = new String[] { "api_key" };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(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);
}
return (Dictionary<String, int?>) ApiInvoker.Deserialize(response.Content, typeof(Dictionary<String, int?>));
return (Dictionary<String, int?>) apiClient.Deserialize(response.Content, typeof(Dictionary<String, int?>));
}
/// <summary>
/// Place an order for a pet
/// </summary>
@@ -74,33 +98,36 @@ namespace IO.Swagger.Api {
/// <returns>Order</returns>
public Order PlaceOrder (Order Body) {
var _request = new RestRequest("/store/order", Method.POST);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
postBody = apiClient.Serialize(Body); // http body (model) parameter
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(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);
}
return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order));
return (Order) apiClient.Deserialize(response.Content, typeof(Order));
}
/// <summary>
/// Find purchase order by ID For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
/// </summary>
@@ -108,36 +135,39 @@ namespace IO.Swagger.Api {
/// <returns>Order</returns>
public Order GetOrderById (string OrderId) {
var _request = new RestRequest("/store/order/{orderId}", Method.GET);
// verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById");
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
_request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(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);
}
return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order));
return (Order) apiClient.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>
@@ -145,29 +175,33 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void DeleteOrder (string OrderId) {
var _request = new RestRequest("/store/order/{orderId}", Method.DELETE);
// verify the required parameter 'OrderId' is set
if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder");
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
_request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(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);
}

View File

@@ -6,34 +6,55 @@ using IO.Swagger.Model;
namespace IO.Swagger.Api {
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class UserApi {
string basePath;
protected RestClient restClient;
public UserApi(String basePath = "http://petstore.swagger.io/v2")
{
this.basePath = basePath;
this.restClient = new RestClient(basePath);
}
/// <summary>
/// Sets the endpoint base url for the services being accessed
/// Initializes a new instance of the <see cref="UserApi"/> class.
/// </summary>
/// <param name="basePath"> Base URL
/// <param name="apiClient"> an instance of ApiClient (optional)
/// <returns></returns>
public void SetBasePath(string basePath) {
this.basePath = basePath;
public UserApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient;
} else {
this.apiClient = apiClient;
}
}
/// <summary>
/// Gets the endpoint base url for the services being accessed
/// <returns>Base URL</returns>
/// Initializes a new instance of the <see cref="UserApi"/> class.
/// </summary>
public String GetBasePath() {
return this.basePath;
/// <returns></returns>
public UserApi(String basePath)
{
this.apiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath(String basePath) {
return this.apiClient.basePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>The API client</value>
public ApiClient apiClient {get; set;}
/// <summary>
/// Create user This can only be done by the logged in user.
@@ -42,26 +63,30 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void CreateUser (User Body) {
var _request = new RestRequest("/user", Method.POST);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/user";
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
postBody = apiClient.Serialize(Body); // http body (model) parameter
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content);
}
@@ -69,7 +94,6 @@ namespace IO.Swagger.Api {
return;
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
@@ -77,26 +101,30 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void CreateUsersWithArrayInput (List<User> Body) {
var _request = new RestRequest("/user/createWithArray", Method.POST);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/user/createWithArray";
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
postBody = apiClient.Serialize(Body); // http body (model) parameter
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content);
}
@@ -104,7 +132,6 @@ namespace IO.Swagger.Api {
return;
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
@@ -112,26 +139,30 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void CreateUsersWithListInput (List<User> Body) {
var _request = new RestRequest("/user/createWithList", Method.POST);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/user/createWithList";
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
postBody = apiClient.Serialize(Body); // http body (model) parameter
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content);
}
@@ -139,7 +170,6 @@ namespace IO.Swagger.Api {
return;
}
/// <summary>
/// Logs user into the system
/// </summary>
@@ -148,59 +178,66 @@ namespace IO.Swagger.Api {
/// <returns>string</returns>
public string LoginUser (string Username, string Password) {
var _request = new RestRequest("/user/login", Method.GET);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/user/login";
path = path.Replace("{format}", "json");
_request.AddUrlSegment("format", "json"); // set format to json by default
if (Username != null) _request.AddParameter("username", ApiInvoker.ParameterToString(Username)); // query parameter
if (Password != null) _request.AddParameter("password", ApiInvoker.ParameterToString(Password)); // query 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;
if (Username != null) queryParams.Add("username", apiClient.ParameterToString(Username)); // query parameter
if (Password != null) queryParams.Add("password", apiClient.ParameterToString(Password)); // query parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content);
}
return (string) ApiInvoker.Deserialize(response.Content, typeof(string));
return (string) apiClient.Deserialize(response.Content, typeof(string));
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <returns></returns>
public void LogoutUser () {
var _request = new RestRequest("/user/logout", Method.GET);
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/user/logout";
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content);
}
@@ -208,7 +245,6 @@ namespace IO.Swagger.Api {
return;
}
/// <summary>
/// Get user by user name
/// </summary>
@@ -216,36 +252,39 @@ namespace IO.Swagger.Api {
/// <returns>User</returns>
public User GetUserByName (string Username) {
var _request = new RestRequest("/user/{username}", Method.GET);
// verify the required parameter 'Username' is set
if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling GetUserByName");
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/user/{username}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username));
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
_request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content);
}
return (User) ApiInvoker.Deserialize(response.Content, typeof(User));
return (User) apiClient.Deserialize(response.Content, typeof(User));
}
/// <summary>
/// Updated user This can only be done by the logged in user.
/// </summary>
@@ -254,30 +293,34 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void UpdateUser (string Username, User Body) {
var _request = new RestRequest("/user/{username}", Method.PUT);
// verify the required parameter 'Username' is set
if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling UpdateUser");
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/user/{username}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username));
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
_request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter
postBody = apiClient.Serialize(Body); // http body (model) parameter
_request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content);
}
@@ -285,7 +328,6 @@ namespace IO.Swagger.Api {
return;
}
/// <summary>
/// Delete user This can only be done by the logged in user.
/// </summary>
@@ -293,29 +335,33 @@ namespace IO.Swagger.Api {
/// <returns></returns>
public void DeleteUser (string Username) {
var _request = new RestRequest("/user/{username}", Method.DELETE);
// verify the required parameter 'Username' is set
if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling DeleteUser");
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
var path = "/user/{username}";
path = path.Replace("{format}", "json");
path = path.Replace("{" + "username" + "}", apiClient.ParameterToString(Username));
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;
_request.AddUrlSegment("format", "json"); // set format to json by default
_request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content);
}

View File

@@ -3,8 +3,13 @@ using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class Category {
@@ -18,6 +23,11 @@ namespace IO.Swagger.Model {
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");
@@ -29,7 +39,16 @@ namespace IO.Swagger.Model {
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

@@ -3,8 +3,13 @@ using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class Order {
@@ -38,6 +43,11 @@ namespace IO.Swagger.Model {
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");
@@ -57,7 +67,16 @@ namespace IO.Swagger.Model {
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

@@ -3,8 +3,13 @@ using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class Pet {
@@ -38,6 +43,11 @@ namespace IO.Swagger.Model {
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");
@@ -57,7 +67,16 @@ namespace IO.Swagger.Model {
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

@@ -3,8 +3,13 @@ using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class Tag {
@@ -18,6 +23,11 @@ namespace IO.Swagger.Model {
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");
@@ -29,7 +39,16 @@ namespace IO.Swagger.Model {
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

@@ -3,8 +3,13 @@ using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace IO.Swagger.Model {
/// <summary>
///
/// </summary>
[DataContract]
public class User {
@@ -48,6 +53,11 @@ namespace IO.Swagger.Model {
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");
@@ -71,7 +81,16 @@ namespace IO.Swagger.Model {
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

@@ -0,0 +1,212 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
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>
/// 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>
/// Gets or sets the base path.
/// </summary>
/// <value>The base path.</value>
public string basePath { get; set; }
/// <summary>
/// Gets or sets the RestClient
/// </summary>
/// <value>The RestClient.</value>
public RestClient restClient { get; set; }
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 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)restClient.Execute(request);
}
/// <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);
}
/// <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>
public string EscapeString(string 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>
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);
}
}
/// <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);
}
}
/// <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>
/// 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");
break;
case "petstore_auth":
//TODO support oauth
break;
default:
//TODO show warning about security definition not found
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);
}
}
}

View File

@@ -1,13 +1,27 @@
using System;
namespace IO.Swagger.Client {
/// <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>
/// 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;
}

View File

@@ -1,84 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
namespace IO.Swagger.Client {
public class ApiInvoker {
private static Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>();
/// <summary>
/// Add default header
/// </summary>
/// <param name="key"> Header field name
/// <param name="value"> Header field value
/// <returns></returns>
public static void AddDefaultHeader(string key, string value) {
defaultHeaderMap.Add(key, value);
}
/// <summary>
/// Get default header
/// </summary>
/// <returns>Dictionary of default header</returns>
public static Dictionary<String, String> GetDefaultHeader() {
return defaultHeaderMap;
}
/// <summary>
/// escape string (url-encoded)
/// </summary>
/// <param name="str"> String to be escaped
/// <returns>Escaped string</returns>
public static string EscapeString(string str) {
return str;
}
/// <summary>
/// if parameter is DateTime, output in ISO8601 format, otherwise just return the string
/// </summary>
/// <param name="obj"> The parameter (header, path, query, form)
/// <returns>Formatted string</returns>
public static string ParameterToString(object obj)
{
return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : 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 static 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);
}
}
/// <summary>
/// Serialize an object into JSON string
/// </summary>
/// <param name="obj"> Object
/// <returns>JSON string</returns>
public static string Serialize(object obj) {
try
{
return obj != null ? JsonConvert.SerializeObject(obj) : null;
}
catch (Exception e) {
throw new ApiException(500, e.Message);
}
}
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using IO.Swagger.Client;
namespace IO.Swagger.Client {
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration{
/// <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>
/// Gets or sets the username (HTTP basic authentication)
/// </summary>
/// <value>The username.</value>
public static String username { get; set; }
/// <summary>
/// Gets or sets the password (HTTP basic authentication)
/// </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 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>();
}
}