Skip to content

Use RestSharp for CSharp API client #700

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 21, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import java.io.File;

public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
protected String invokerPackage = "IO.Swagger.Client";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-csharp-client";
protected String artifactVersion = "1.0.0";
Expand All @@ -31,8 +31,8 @@ public CSharpClientCodegen() {
modelTemplateFiles.put("model.mustache", ".cs");
apiTemplateFiles.put("api.mustache", ".cs");
templateDir = "csharp";
apiPackage = "io.swagger.Api";
modelPackage = "io.swagger.Model";
apiPackage = "IO.Swagger.Api";
modelPackage = "IO.Swagger.Model";

reservedWords = new HashSet<String> (
Arrays.asList(
Expand Down Expand Up @@ -80,7 +80,7 @@ public CSharpClientCodegen() {
typeMapping.put("double", "double?");
typeMapping.put("number", "double?");
typeMapping.put("Date", "DateTime");
typeMapping.put("file", "byte[]");
typeMapping.put("file", "string"); // path to file
typeMapping.put("array", "List");
typeMapping.put("map", "Dictionary");

Expand Down
115 changes: 44 additions & 71 deletions modules/swagger-codegen/src/main/resources/csharp/api.mustache
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using RestSharp;
using {{invokerPackage}};
using {{modelPackage}};
{{#imports}}
Expand All @@ -9,101 +10,73 @@ namespace {{package}} {
{{#operations}}
public class {{classname}} {
string basePath;
private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance();
protected RestClient restClient;

public {{classname}}(String basePath = "{{basePath}}")
{
this.basePath = basePath;
this.restClient = new RestClient(basePath);
}

public ApiInvoker getInvoker() {
return apiInvoker;
}

// Sets the endpoint base url for the services being accessed
public void setBasePath(string basePath) {
/// <summary>
/// Sets the endpoint base url for the services being accessed
/// </summary>
/// <param name="basePath"> Base URL
/// <returns></returns>
public void SetBasePath(string basePath) {
this.basePath = basePath;
}

// Gets the endpoint base url for the services being accessed
public String getBasePath() {
return basePath;
/// <summary>
/// Gets the endpoint base url for the services being accessed
/// <returns>Base URL</returns>
/// </summary>
public String GetBasePath() {
return this.basePath;
}

{{#operation}}

/// <summary>
/// {{summary}} {{notes}}
/// </summary>
{{#allParams}}/// <param name="{{paramName}}">{{description}}</param>
{{#hasMore}} {{/hasMore}}{{/allParams}}
/// <returns></returns>
public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
// create path and map variables
var path = "{{path}}".Replace("{format}","json"){{#pathParams}}.Replace("{" + "{{baseName}}" + "}", apiInvoker.ParameterToString({{{paramName}}})){{/pathParams}};
{{#allParams}} /// <param name="{{paramName}}">{{description}}</param>
{{/allParams}}
/// <returns>{{#returnType}}{{{returnType}}}{{/returnType}}</returns>
public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {

// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, object>();
var _request = new RestRequest("{{path}}", Method.{{httpMethod}});

{{#requiredParamCount}}
// verify required params are set
if ({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) {
throw new ApiException(400, "missing required params");
}
{{/requiredParamCount}}
{{#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}}

{{#queryParams}}if ({{paramName}} != null){
queryParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}}));
// add default header, if any
foreach(KeyValuePair<string, string> defaultHeader in ApiInvoker.GetDefaultHeader())
{
_request.AddHeader(defaultHeader.Key, defaultHeader.Value);
}
{{/queryParams}}

{{#headerParams}}headerParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}}));
_request.AddUrlSegment("format", "json"); // set format to json by default
{{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter
{{/pathParams}}
{{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // query parameter
{{/queryParams}}
{{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter
{{/headerParams}}

{{#formParams}}if ({{paramName}} != null){
if({{paramName}} is byte[]) {
formParams.Add("{{baseName}}", {{paramName}});
} else {
formParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}}));
}
}
{{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // form parameter{{/isFile}}
{{/formParams}}
{{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter
{{/bodyParam}}

try {
if (typeof({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}) == typeof(byte[])) {
{{#returnType}}
var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams);
return ((object)response) as {{{returnType}}};
{{/returnType}}
{{^returnType}}
apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams);
return;
{{/returnType}}
} else {
{{#returnType}}
var response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams);
if (response != null){
return ({{{returnType}}}) ApiInvoker.deserialize(response, typeof({{{returnType}}}));
}
else {
return null;
}
{{/returnType}}
{{^returnType}}
apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams);
return;
{{/returnType}}
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return {{#returnType}}null{{/returnType}};
}
else {
throw ex;
}
// make the HTTP request
IRestResponse response = restClient.Execute(_request);
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}}
return;{{/returnType}}
}
{{/operation}}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
using System;

namespace {{invokerPackage}} {

public class ApiException : Exception {

private int errorCode = 0;

public ApiException() {}
public int ErrorCode { get; set; }

public int ErrorCode {
get
{
return errorCode;
}
}
public ApiException() {}

public ApiException(int errorCode, string message) : base(message) {
this.errorCode = errorCode;
this.ErrorCode = errorCode;
}

}
}

}
Loading