Search Unity

Does unity work with Swagger.io?

Discussion in 'Formats & External Tools' started by McSwan, Aug 18, 2016.

  1. McSwan

    McSwan

    Joined:
    Nov 21, 2013
    Posts:
    129
    Hi,

    I've generated some c# code from swagger.io

    http://swagger.io/

    Does it work with unity? Has anyone else got it working inside unity?

    Here's an example of the generated code.
    It's missing RestSharp, Nextonsoft.Json. I think I can download nextonsoft.json. I don't know much about swagger.

    Code (CSharp):
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Globalization;
    4. using System.Text.RegularExpressions;
    5. using System.IO;
    6. using System.Web;
    7. using System.Linq;
    8. using System.Net;
    9. using System.Text;
    10. using Newtonsoft.Json;
    11. //using RestSharp;
    12. using RestSharp.Extensions;
    13.  
    14. namespace IO.Swagger.Client
    15. {
    16.     /// <summary>
    17.     /// API client is mainly responible for making the HTTP call to the API backend.
    18.     /// </summary>
    19.     public class ApiClient
    20.     {
    21.         private readonly Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>();
    22.  
    23.         /// <summary>
    24.         /// Initializes a new instance of the <see cref="ApiClient" /> class.
    25.         /// </summary>
    26.         /// <param name="basePath">The base path.</param>
    27.         public ApiClient(String basePath="https://vvv5285.cloudapp.net/")
    28.         {
    29.             BasePath = basePath;
    30.             RestClient = new RestClient(BasePath);
    31.         }
    32.  
    33.         /// <summary>
    34.         /// Gets or sets the base path.
    35.         /// </summary>
    36.         /// <value>The base path</value>
    37.         public string BasePath { get; set; }
    38.  
    39.         /// <summary>
    40.         /// Gets or sets the RestClient.
    41.         /// </summary>
    42.         /// <value>An instance of the RestClient</value>
    43.         public RestClient RestClient { get; set; }
    44.  
    45.         /// <summary>
    46.         /// Gets the default header.
    47.         /// </summary>
    48.         public Dictionary<String, String> DefaultHeader
    49.         {
    50.             get { return _defaultHeaderMap; }
    51.         }
    52.  
    53.         /// <summary>
    54.         /// Makes the HTTP request (Sync).
    55.         /// </summary>
    56.         /// <param name="path">URL path.</param>
    57.         /// <param name="method">HTTP method.</param>
    58.         /// <param name="queryParams">Query parameters.</param>
    59.         /// <param name="postBody">HTTP body (POST request).</param>
    60.         /// <param name="headerParams">Header parameters.</param>
    61.         /// <param name="formParams">Form parameters.</param>
    62.         /// <param name="fileParams">File parameters.</param>
    63.         /// <param name="authSettings">Authentication settings.</param>
    64.         /// <returns>Object</returns>
    65.         public Object CallApi(String path, RestSharp.Method method, Dictionary<String, String> queryParams, String postBody,
    66.             Dictionary<String, String> headerParams, Dictionary<String, String> formParams,
    67.             Dictionary<String, FileParameter> fileParams, String[] authSettings)
    68.         {
    69.  
    70.             var request = new RestRequest(path, method);
    71.  
    72.             UpdateParamsForAuth(queryParams, headerParams, authSettings);
    73.  
    74.             // add default header, if any
    75.             foreach(var defaultHeader in _defaultHeaderMap)
    76.                 request.AddHeader(defaultHeader.Key, defaultHeader.Value);
    77.  
    78.             // add header parameter, if any
    79.             foreach(var param in headerParams)
    80.                 request.AddHeader(param.Key, param.Value);
    81.  
    82.             // add query parameter, if any
    83.             foreach(var param in queryParams)
    84.                 request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
    85.  
    86.             // add form parameter, if any
    87.             foreach(var param in formParams)
    88.                 request.AddParameter(param.Key, param.Value, ParameterType.GetOrPost);
    89.  
    90.             // add file parameter, if any
    91.             foreach(var param in fileParams)
    92.                 request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType);
    93.  
    94.             if (postBody != null) // http body (model) parameter
    95.                 request.AddParameter("application/json", postBody, ParameterType.RequestBody);
    96.  
    97.             return (Object)RestClient.Execute(request);
    98.  
    99.         }
    100.  
    101.         /// <summary>
    102.         /// Add default header.
    103.         /// </summary>
    104.         /// <param name="key">Header field name.</param>
    105.         /// <param name="value">Header field value.</param>
    106.         /// <returns></returns>
    107.         public void AddDefaultHeader(string key, string value)
    108.         {
    109.             _defaultHeaderMap.Add(key, value);
    110.         }
    111.  
    112.         /// <summary>
    113.         /// Escape string (url-encoded).
    114.         /// </summary>
    115.         /// <param name="str">String to be escaped.</param>
    116.         /// <returns>Escaped string.</returns>
    117.         public string EscapeString(string str)
    118.         {
    119.             return RestSharp.Contrib.HttpUtility.UrlEncode(str);
    120.         }
    121.  
    122.         /// <summary>
    123.         /// Create FileParameter based on Stream.
    124.         /// </summary>
    125.         /// <param name="name">Parameter name.</param>
    126.         /// <param name="stream">Input stream.</param>
    127.         /// <returns>FileParameter.</returns>
    128.         public FileParameter ParameterToFile(string name, Stream stream)
    129.         {
    130.             if (stream is FileStream)
    131.                 return FileParameter.Create(name, stream.ReadAsBytes(), Path.GetFileName(((FileStream)stream).Name));
    132.             else
    133.                 return FileParameter.Create(name, stream.ReadAsBytes(), "no_file_name_provided");
    134.         }
    135.  
    136.         /// <summary>
    137.         /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime.
    138.         /// If parameter is a list of string, join the list with ",".
    139.         /// Otherwise just return the string.
    140.         /// </summary>
    141.         /// <param name="obj">The parameter (header, path, query, form).</param>
    142.         /// <returns>Formatted string.</returns>
    143.         public string ParameterToString(object obj)
    144.         {
    145.             if (obj is DateTime)
    146.                 // Return a formatted date string - Can be customized with Configuration.DateTimeFormat
    147.                 // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o")
    148.                 // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8
    149.                 // For example: 2009-06-15T13:45:30.0000000
    150.                 return ((DateTime)obj).ToString (Configuration.DateTimeFormat);
    151.             else if (obj is List<string>)
    152.                 return String.Join(",", (obj as List<string>).ToArray());
    153.             else
    154.                 return Convert.ToString (obj);
    155.         }
    156.  
    157.         /// <summary>
    158.         /// Deserialize the JSON string into a proper object.
    159.         /// </summary>
    160.         /// <param name="content">HTTP body (e.g. string, JSON).</param>
    161.         /// <param name="type">Object type.</param>
    162.         /// <param name="headers">HTTP headers.</param>
    163.         /// <returns>Object representation of the JSON string.</returns>
    164.         public object Deserialize(string content, Type type, IList<Parameter> headers=null)
    165.         {
    166.             if (type == typeof(Object)) // return an object
    167.             {
    168.                 return content;
    169.             }
    170.  
    171.             if (type == typeof(Stream))
    172.             {
    173.                 var filePath = String.IsNullOrEmpty(Configuration.TempFolderPath)
    174.                     ? Path.GetTempPath()
    175.                     : Configuration.TempFolderPath;
    176.  
    177.                 var fileName = filePath + Guid.NewGuid();
    178.                 if (headers != null)
    179.                 {
    180.                     var regex = new Regex(@"Content-Disposition:.*filename=['""]?([^'""\s]+)['""]?$");
    181.                     var match = regex.Match(headers.ToString());
    182.                     if (match.Success)
    183.                         fileName = filePath + match.Value.Replace("\"", "").Replace("'", "");
    184.                 }
    185.                 File.WriteAllText(fileName, content);
    186.                 return new FileStream(fileName, FileMode.Open);
    187.  
    188.             }
    189.  
    190.             if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object
    191.             {
    192.                 return DateTime.Parse(content,  null, System.Globalization.DateTimeStyles.RoundtripKind);
    193.             }
    194.  
    195.             if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type
    196.             {
    197.                 return ConvertType(content, type);
    198.             }
    199.  
    200.             // at this point, it must be a model (json)
    201.             try
    202.             {
    203.                 return JsonConvert.DeserializeObject(content, type);
    204.             }
    205.             catch (IOException e)
    206.             {
    207.                 throw new ApiException(500, e.Message);
    208.             }
    209.         }
    210.  
    211.         /// <summary>
    212.         /// Serialize an object into JSON string.
    213.         /// </summary>
    214.         /// <param name="obj">Object.</param>
    215.         /// <returns>JSON string.</returns>
    216.         public string Serialize(object obj)
    217.         {
    218.             try
    219.             {
    220.                 return obj != null ? JsonConvert.SerializeObject(obj) : null;
    221.             }
    222.             catch (Exception e)
    223.             {
    224.                 throw new ApiException(500, e.Message);
    225.             }
    226.         }
    227.  
    228.         /// <summary>
    229.         /// Get the API key with prefix.
    230.         /// </summary>
    231.         /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
    232.         /// <returns>API key with prefix.</returns>
    233.         public string GetApiKeyWithPrefix (string apiKeyIdentifier)
    234.         {
    235.             var apiKeyValue = "";
    236.             Configuration.ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
    237.             var apiKeyPrefix = "";
    238.             if (Configuration.ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix))
    239.                 return apiKeyPrefix + " " + apiKeyValue;
    240.             else
    241.                 return apiKeyValue;
    242.         }
    243.  
    244.         /// <summary>
    245.         /// Update parameters based on authentication.
    246.         /// </summary>
    247.         /// <param name="queryParams">Query parameters.</param>
    248.         /// <param name="headerParams">Header parameters.</param>
    249.         /// <param name="authSettings">Authentication settings.</param>
    250.         public void UpdateParamsForAuth(Dictionary<String, String> queryParams, Dictionary<String, String> headerParams, string[] authSettings)
    251.         {
    252.             if (authSettings == null || authSettings.Length == 0)
    253.                 return;
    254.  
    255.             foreach (string auth in authSettings)
    256.             {
    257.                 // determine which one to use
    258.                 switch(auth)
    259.                 {
    260.                     default:
    261.                         //TODO show warning about security definition not found
    262.                         break;
    263.                 }
    264.             }
    265.         }
    266.         /// <summary>
    267.         /// Encode string in base64 format.
    268.         /// </summary>
    269.         /// <param name="text">String to be encoded.</param>
    270.         /// <returns>Encoded string.</returns>
    271.         public static string Base64Encode(string text)
    272.         {
    273.             var textByte = System.Text.Encoding.UTF8.GetBytes(text);
    274.             return System.Convert.ToBase64String(textByte);
    275.         }
    276.  
    277.         /// <summary>
    278.         /// Dynamically cast the object into target type.
    279.         /// Ref: http://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast
    280.         /// </summary>
    281.         /// <param name="source">Object to be casted</param>
    282.         /// <param name="dest">Target type</param>
    283.         /// <returns>Casted object</returns>
    284.         public static Object ConvertType(Object source, Type dest) {
    285.             return Convert.ChangeType(source, dest);
    286.         }
    287.  
    288.     }
    289. }
    290.  
     
  2. Ishknock

    Ishknock

    Joined:
    Dec 27, 2015
    Posts:
    1
    Did you ever find out if this works? RestSharp is not a reference for any of the code that my swagger ui tools have generated. As for the Newtonsoft.Json I was kind of curious if that was cross platform or not. That can be added via a Nuget package but I've never added those to a Unity project before so not sure how cross platform friendly those are. Also since Unity regenerates the C# project file each time, I'm not sure how friendly that is going to be either. That may be a topic for a new thread entirely.
     
  3. McSwan

    McSwan

    Joined:
    Nov 21, 2013
    Posts:
    129
    Hi,
    I didn't have the time the research how to get swagger working, so I manually coded a solution rather than using script generators. Be good if there was a working solution for swagger and unity though.
     
  4. LlamaDoge

    LlamaDoge

    Joined:
    Jul 13, 2017
    Posts:
    1
    Curios if anyone else has tried using Swagger generated C# in Unity. Newtonsoft.Json will definitely work within Unity, we've used it in the past, most recently with 2017.1. So in theory it should be possible.
     
  5. SeanMcTex

    SeanMcTex

    Joined:
    Dec 12, 2016
    Posts:
    7
  6. darrensmith

    darrensmith

    Joined:
    Apr 13, 2017
    Posts:
    16
    @SeanMcTex Thank you for your insight here. Very helpful!