February 6, 2018 Update: I figured out a workflow with the experimental .NET 4.6 support in Unity to actually make this work with Daydream, and have updated the workflow here. This solves the annoying caveat that I’d previously posted.
Swagger (aka OpenAPI) lets you define API structure in a machine-readable way. This allows all kinds of cool functionality: automatic docs, code generation across languages, etc. Here’s the workflow we’ve devised 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 https://app.swaggerhub.com/. (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 “Csharp” from the “Download → Client” dropdown.
- Unzip the downloaded
- Open a terminal window.
- Go to the directory of the new unzipped download. (e.g. “
- Build your DLL:
build.batif you’re on windows.
- Your DLL is now in the “bin” subdirectory of the downloaded folder and is called “IO.Swagger.dll”. Copy this to your “Scripts” folder in Unity.
- Find “Newtonsoft.Json.dll” (
packages/Newtonsoft.Json.10.0.3/lib/net45/Newtonsoft.Json.dll) and copy it to your “Scripts” folder in Unity.
- Find “RestSharp.Net2.dll” (
packages/RestSharp.105.1.0/lib/net452/RestSharp.dll) and copy it to your “Scripts” folder in Unity.
- You’ll also need to round up the DataAnnotations DLL from somewhere in your Unity package (
Unity.app/Contents/MonoBleedingEdge/lib/mono/4.5/System.ComponentModel.DataAnnotations.dll) and copy it into 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.
Great Big Obnoxious Caveat:
This doesn’t currently work when running on Android due to this bug in Unity’s .NET implementation. We ended up doing a last-minute rewrite to use Best HTTP instead, which was a crying shame. Hoping this bug will indeed be fixed in the future and make this workflow viable on that platform.