Using Swagger APIs with Unity

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.)

  1. 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.)
  2. Verify that the auto-generated documentation on the right looks correct.
  3. Choose “Csharp” from the “Download → Client” dropdown.
  4. Unzip the downloaded csharp-client-generated.zip file.
  5. Open a terminal window.
  6. Go to the directory of the new unzipped download. (e.g. “cd ~/Downloads/csharp-client-generated/“)
  7. Build your DLL: /bin/sh build.sh or build.bat if you’re on windows.
  8. 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.
  9. Find “Newtonsoft.Json.dll” (packages/Newtonsoft.Json.10.0.3/lib/net45/Newtonsoft.Json.dll) and copy it to your “Scripts” folder in Unity.
  10. Find “RestSharp.Net2.dll” (packages/RestSharp.105.1.0/lib/net452/RestSharp.dll) and copy it to your “Scripts” folder in Unity.
  11. 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.
  12. Unity loads the DLL and makes the IO.Swagger namespace available to you.

Using it:

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.