Swagger lets you define API structure in a machine-readable way. This enables all kinds of cool functionality: automatic docs, code generation across languages, etc. Here’s the workflow I’ve been able to sort out for consuming Swagger APIs in Unity. (Note: I’ve tested this on a Mac, but haven’t tried it on a PC yet.)
- Load your Swagger specification into the editor at http://editor.swagger.io. (The easiest way is just to copy and paste it into the editor window.)
- Verify that the auto-generated documentation on the right looks correct.
- Choose “CsharpDotNet2” from the “Generate Client” dropdown.
- Unzip the downloaded CsharpDotNet2-client-generated.zip file.
- Open a terminal window.
- Go to the vendor directory of the new unzipped download. (e.g. “cd ~/Downloads/CsharpDotNet2-client/vendor/”)
- Download the required JSON library by typing this in the command line: nuget install Newtonsoft.Json -version 7.0.1
- Download the required REST library: nuget install RestSharp.Net2 -version 1.1.11
- Move back to the root of the downloaded folder. cd .. or cd ~/Downloads/CsharpDotNet2-client/.
- Build your DLL: ./compile-mono.sh. You’ll get a warning about not being able to open nuget.exe. This is fine.
- Your DLL is now in the “build” subdirectory of the downloaded folder and is called “IO.Swagger.dll”. Copy this to your “Scripts” folder in Unity.
- Find “Newtonsoft.Json.dll” (vendor/Newtonsoft.Json.7.0..1/lib/net20/Newtonsoft.Json.dll) and copy it to your “Scripts” folder in Unity.
- Find “RestSharp.Net2.dll” (vendor/RestSharp.Net22.214.171.124/lib/net20/RestSharp.Net2.dll) and copy it to your “Scripts” folder in Unity.
- Unity loads the DLL and makes the IO.Swagger namespace available to you.
Take a look in the docs folder of the project you downloaded from the Swagger editor. It includes nice Markup files with C# sample code documenting the APIs in your new DLL. The sample code makes a great starting point for accessing the DLL’s functionality.
Big Frustrating Caveat:
The RestSharp library defines “System.Action” and “System.Func” as does the .NET runtime. Unfortunately, this means that if you have code in your project that relies on either of these (like Google’s Daydream library), you won’t be able to get it to compile. In theory, you should be able to work around this by setting up Unity to use external references and referencing those that way, but I’ve been unable to get that to work. As far as I can tell at this point, the best way forward in this case is simply to write your own client code using RestSharp Unity or another library designed for creating REST clients. If someone has a better working approach, I’d love to know about it.