Saturday 17 August 2019

Adding support for a Swagger REST API in a Dynamics Plugin

So recently I've been working on consuming a Swagger REST API in a Sandboxed plugin.

Visual Studio now includes some nice features to support this such as the ability to automatically generate an API Client and the models used by an API directly using Swagger.
You simply right click > add > REST API Client and then enter the url to the Swagger documentation (EG. http://api.yourapi.com/swagger/docs/v1).
Visual Studio generates all the classes for you.

So far so good... :)

However, before you skip happily off into the sunset there are a couple of gotchas....

1. The APIClient classes generated cannot be consumed from a Sandbox plugin - they cause security exceptions as they reference libraries not supported by plugins running in isolation mode. If you are running on prem outside the Sandbox you're good to go - if not... you'll need to call the API directly using HttpClient instead.

            var content = new StringContent(json);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpClient client = new HttpClient();
            HttpResponseMessage resp = await client.PostAsync($"{apiUrl}api/dostuff", content);
            return resp;

2. If your Plugin consumes other libraries using ILMerge and you also reference NewtonSoft you may hit issues. This is because at the point you generate the REST API classes a nuget package reference is added to your project. In my case I already had a reference to NewtonSoft version 12. The REST API package references version 6. This works fine - the version difference is handled and the classes are generated correctly. However, when I attempt to compile after the operation has completed, ILMerge barfs and the build fails.
The fix is to delete the nuget package and recompile. Everything works again... but you've lost a couple of hours of life and that right click, add REST API Client has lost some of it's sparkle ;)