Thursday, June 30, 2016

Sitecore & Swagger's duplication theory

A simple post for a simple challenge.

Have you had a REST API exposed within the same application as Sitecore?

And have you also wanted to document your REST API as well? Maybe by using the industry standard Swagger?

If so, i think you're familiar with the following challenges:



This is because Swagger maps a URL to an action whilst ignoring the query string. Hence, more methods exposed by the API doing apparently the same thing.

I've used Swashbuckle on my solution and as the error states, config states and Swashbuckle's board states: You should really try and avoid this when designing your API. 

But it's Sitecore's API... Yes yes, Swagger is not biased! It's all for one and one for all here!

If you got this issue from Sitecore's API or because your API does this it's probably too late for a redesign and I believe this is why we're here. We can still use the following workaround: 

In the SwaggerConfig.cs file you have, you just need to uncomment the following line:


As the suggestive comments state, you'll need to let Swagger know, how to deal with these "duplicates" (we know they're not, but let's leave Swagger have it's way this time - you know what they say, shake hands with the devil until you cross the bridge).

PS: You'll also need to use System.Linq for the extension methods in case you missed that. 

For me that did the trick. 

However, my project had another duplication flagged by Swagger. (which of course I didn't agree with, but hey, i'll let it have this as well..). See below:



I'll translate as it may not seem relevant with the censor in place: If you have models that have the same class name, regardless if they're in different namespaces, Swagger matched a duplication!

Funny like that, the fix is also suggested in SwaggerConfig.cs comments. So just uncomment this line, which basically states use the full name of the model when mapping to your API:


And ta-da! it works!

It looks like Swagger has a problem with duplication and is quite strict on that. But at the same time, at the end of the day, it probably grabs a cold one, reflects on the day and still provides us with a solution. It's tough to admit mistakes, so let's just be the bigger man here, and accept this step forward and leave it at that!

Happy coding!