Recently I was working on designing and implementing a large scale RESTful API using ASP.NET Web API, this RESTful API contains large number of endpoints with different data models used in the request/response payloads.
Proper documentation and having a solid API explorer (Playground) is a crucial thing for your API success and likability by developers. There is a very informative slides by John Musser which highlights the top 10 reasons which makes developers hate your API, and unsurprisingly the top one is the lack of documentation and the absence of interactive documentation; so to avoid this pitfall I decided to document my Web API using Swagger.
Swagger basically is a framework for describing, consuming, and visualizing RESTful APIs. The nice thing about Swagger that it is really keeps the documentation system, the client, and the server code in sync always, in other words the documentation of methods, parameters, and models are tightly integrated into the server code.
ASP.NET Web API Documentation using Swagger
So in this short post I decided to add documentation using Swagger for a simple ASP.NET Web API project which contains a single controller with different HTTP methods, the live demo API explorer can be accessed here, and the source code can be found on GitHub. The final result for the API explorer will look as the image below:
Swagger is language-agnostic so there are different implementations for different platforms. For the ASP.NET Web API world there is a solid open source implementation named “Swashbuckle” this implementation simplifies adding Swagger to any Web API project by following simple steps which I’ll highlight in this post.
The nice thing about Swashbuckle that it has no dependency on ASP.NET MVC, so there is no need to include any MVC Nuget packages in order to enable API documentation, as well Swashbuckle contains an embedded version of swagger-ui which will automatically serve up once Swashbuckle is installed.
Swagger-ui basically is a dependency-free collection of HTML, Javascript, and CSS files that dynamically generate documentation and sandbox from a Swagger-compliant API, it is a Single Page Application which forms the play ground shown in the image above.
Steps to Add Swashbuckle to ASP.NET Web API
The sample ASP.NET Web API project I want to document is built using Owin middleware and hosted on IIS, I’ll not go into details on how I built the Web API, but I’ll focus on how I added Swashbuckle to the API.
For brevity the API contains single controller named “StudentsController”, the source code for the controller can be viewed here, as well it contains a simple “Student” Model class which can be viewed here.
Step 1: Install the needed Nuget Package
Open NuGet Package Manager Console and install the below package:
1 |
Install-Package Swashbuckle |
Once this package is installed it will install a bootstrapper (App_Start/SwaggerConfig.cs) file which initiates Swashbuckle on application start-up using WebActivatorEx.
Step 2: Call the bootstrapper in “Startup” class
Now we need to add the highlighted line below to “Startup” class, so open the Startup class and replace it with the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
[assembly: OwinStartup(typeof(WebApiSwagger.Startup))] namespace WebApiSwagger { public class Startup { public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); Swashbuckle.Bootstrapper.Init(config); app.UseWebApi(config); } } } |
Step 3: Enable generating XML documentation
This is not required step to use “Swashbuckle” but I believe it is very useful for API consumers especially if you have complex data models, so to enable XML documentation, right click on your Web API project — >”Properties” then choose “Build” tab, after you choose it scroll down to the “Output” section and check “XML documentation file” check box and set the file path to: “bin\[YourProjectName].XML” as the image below. This will add an XML file to the bin folder which contains all the XML comments you added as annotation to the controllers or data models.
Step 4: Configure Swashbuckle to use XML Comments
By default Swashbuckle doesn’t include the annotated XML comments on the API controllers and data models into the generated specification and the UI, to include them we need to configure it, so open file “SwaggerConfig.cs” and paste the highlighted code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public class SwaggerConfig { public static void Register() { Swashbuckle.Bootstrapper.Init(GlobalConfiguration.Configuration); // NOTE: If you want to customize the generated swagger or UI, use SwaggerSpecConfig and/or SwaggerUiConfig here ... SwaggerSpecConfig.Customize(c => { c.IncludeXmlComments(GetXmlCommentsPath()); }); } protected static string GetXmlCommentsPath() { return System.String.Format(@"{0}\bin\WebApiSwagger.XML", System.AppDomain.CurrentDomain.BaseDirectory); } } |
Step 5: Start annotating your API methods and data models
Now we can start adding XML comments to API methods so for example if we take a look on the HTTP POST method in Students Controller as the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/// <summary> /// Add new student /// </summary> /// <param name="student">Student Model</param> /// <remarks>Insert new student</remarks> /// <response code="400">Bad request</response> /// <response code="500">Internal Server Error</response> [Route("")] [ResponseType(typeof(Student))] public IHttpActionResult Post(Student student) { //Method implementation goes here.... } |
You will notice that each XML tag is reflected on the Swagger properties as the image below:
Summary
You can add Swashbuckle seamlessly to any Web API project, and then you can easily customize the generated specification along with the UI (swagger-ui). You can check the documentation and troubleshooting section here.
That’s it for now, hopefully this post will be useful for anyone looking to document their ASP.NET Web API, if you have any question or you have used another tool for documentation please drop me a comment.
The live demo API explorer can be accessed here, and the source code can be found on GitHub.
Too bad your API is not really RESTful. The documentation is focussing on the availability of specific resources and the URL templates they live at, instead of focussing on the types of resources that are available and how they link together to form your API.
I’d like to see a toolkit that follows REST practices and does just exactly that. Not that you’ll be in for a free lunch, as Web API itself does not focus on REST (which it doesn’t claim to, depending on who you speak to).
Also, /api/Students returns a JSON array, and you should never return a JSON array by itself. See http://haacked.com/archive/2009/06/25/json-hijacking.aspx/.
Thanks for your feedback.
Well why the API used in this sample is not RESTful? I’m following the REST constraints here.
Thanks for sharing the vulnerability of returning a JSON array by itself.
@DaveVdE, your post is somewhat vague- are you saying that his API is not RESTful because it lacks hypermedia controls? This does not follow.
Just because it is not level 3 of the Richardson Maturity Model does not mean it is not RESTful. This API is clearly within level 2 territory. Your post is very nitpicky, I think.
http://martinfowler.com/articles/richardsonMaturityModel.html
Fielding says in order to be restfull you MUST have HATEOAS, so he is correct. Still nitpicky, but correct.
Thanks for the great article, but how do you access the documentation after you have followed the above steps?
You jumped from adding the XML documents to seeing how they are displayed in the documentation, but don’t say how to view them.
Hi Karl,
Sorry I didn’t get your question. But after you add the XML comments on the controller and data models it will be reflected on swagger spec and you can check them here: http://webapiswagger.azurewebsites.net/swagger/ui/index.html#!/Students In other words it will be available on: [your-api-endpoint]/swagger
Hope this answers your question.
Hi Taiseer, this is great article and I success replicating on what you wrote here. No problem at all.
And, I also followed your token based authentication with Web API article and successfully implemented it.
Do you have any plan to write how to implement swashbuckle to your Web API article? I know it’s already here, but you see, on the swagger demo here (http://petstore.swagger.wordnik.com/) they have oauth authentication. Maybe you can teach us how to implement swagger with oauth on your token based authentication with Web API article. Thanks.
Hi Hendra,
Thanks for your feedback, I’ll consider this soon, but if you need to know how to set the bearer authorization header with swagger for each API call please drop me message, I’ve done it but not blogged about it yet.
Hi Taiseer, congratulations for your blog.
I just wondering how to set bearer authorization header with swagger. I can’t wait for your post about this topic.
I’ve tried to achive it using some property of SwaggerUiConfig, but I don’t know which one.
SwaggerUiConfig.Customize(c =>
{
c.SupportHeaderParams = true;
c.DocExpansion = DocExpansion.List;
c.SupportedSubmitMethods = new[] { HttpMethod.Get, HttpMethod.Post, HttpMethod.Put };
});
Thank you Xavi 🙂 You can find below the steps I followed to set the authorization header:
1. Added new file named “SwaggerExtensions”, then added new JS file named “onComplete.js”, you have to change the build action for this file to “Embedded Resource”.
2. Inside the file “onComplete.js” paste the following code:
$(‘#input_apiKey’).change(function () {
var key = $(‘#input_apiKey’)[0].value;
if (key && key.trim() != “”) {
key = “Bearer ” + key;
window.authorizations.add(“key”, new ApiKeyAuthorization(“Authorization”, key, “header”));
}
});
3. Open file “SwaggerConfig.cs” and inside the register method paste the code below:
SwaggerUiConfig.Customize(c =>
{
c.SupportHeaderParams = true;
c.InjectJavaScript(typeof(SwaggerConfig).Assembly, “AngularJSAuthentication.API.SwaggerExtensions.onComplete.js”);
});
Note that you need to change the full assembly name to match your assembly name.
I believe thats it, once you run the UI you will notice that this file has been downloaded and it will set the authorization header correctly.
Hope this will help.
Thank you Taiseer, it works like a charm!
Hi Taiseer,
I really liked your token based authentication with Web API article This is another great article from you.
I have question regarding oAuth implementation using swashbuckle. As per swagger-ui pet store example you can add button for oAuth authentication which pop ups the oAuth dialogue . is same thing possible using swashbuckle?
Thanks,
Paresh
Hi Taiseer,
Happy to see things are now back and running… 😉
I was already aware of Swagger – which actually released a Swagger 2.0 version -, though I must say I was glad to find a “Web API oriented Swagger” version with no dependency on ASP.NET MVC. Hmmm sounds cool, so I gave it a try [based on your instructions] and as usual, I must say things went straight forward with no ambiguities.
BTW someone mentioned he was looking for any useful links for generating the documentation for ASP.NET Web API 2.0
on Stackoverflow:
http://stackoverflow.com/questions/21811006/using-swagger-net-to-generate-asp-net-web-api-2-0-documentation/25791975#25791975
so I thought it would be a good initiative to refer them to your site. 😉
Thanks for your comment, yes the website down for 6 hours. I’m hosting at bluehost. They are good but the outage was long!
Thanks for letting me know about the question, I noticed someone answered the question and referenced by post, I believe it is you 🙂
RE: I believe it is you…
Indeed it was…
BTW I’m just about to check your latest post on Secure ASP.NET Web API 2 using Azure Active Directory, Owin Middleware, and ADAL. Sure will take a deep close look at it. Thank’s
Hi Taiseer,
Your article was really helpful. Can you please point me to the right direction in regards to implementing file upload. what I want to do is to have a file upload capability in my Swagger documentation (something like the pet store demo: http://petstore.swagger.wordnik.com/#!/pet/uploadFile).
Your help will be appreciated
Hi Savvas,
I really have no clear answer now, will do my best to check how this can be done. But are you asking how you implement the swagger part or how you can upload images using Web API?
Hi, what was the solution to this? I have a webapi i am using swagger to document, and want the swagger ui to show an upload button (like the pet example). What decoration is needed for swagger to do this?
I made it as such:
// In the controller
[HttpPost]
[SwaggerAddFileUpload]
public HttpResponseMessage UploadFile() { return null; }
// New attribute
[AttributeUsage(AttributeTargets.Method)]
public class SwaggerAddFileUploadAttribute : Attribute
{
public bool Required { get; private set; }
public SwaggerAddFileUploadAttribute(bool Required = true)
{
this.Required = Required;
}
}
// In the swagger config
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{ //[…]
c.OperationFilter();
// New filter
public class AddFileUploadFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var fileUploadAttribute = apiDescription.GetControllerAndActionAttributes();
foreach (var attr in fileUploadAttribute)
{
operation.consumes.Add(“multipart/form-data”);
operation.parameters.Add(new Parameter
{
name = “file”,
@in = “formData”,
description = “file to upload”,
required = attr.Required,
type = “file”
});
}
}
}
That’s it! “Instant” file upload =D
Mr. Jasper, It is amazing and works for me, Thank You and God bless you.
ur process is supporting only application/json in response tyep,i need it to support even application/xml.What is the fix??Is it possible in swashbuckle?
How do you handle Attribute Routing. I am getting the following error
///
///
///
/// aliasId
///
[Route(“members/{aliasId}/Status”)]
[HttpGet]
public IEnumerable GetStatus()
{
var memberStatusModel = new MemberStatusModel[1];
memberStatusModel[0] = new MemberStatusModel();
memberStatusModel[0].Status = “OKAY”;
return memberStatusModel;
}
}
}
Error:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
An error has occurred.
Object reference not set to an instance of an object.
System.NullReferenceException
at Swashbuckle.Swagger.OperationGenerator.CreateParameter(ApiParameterDescription apiParamDesc, String apiPath) at Swashbuckle.Swagger.OperationGenerator.c__DisplayClass2.b__1(ApiParameterDescription paramDesc) at System.Linq.Enumerable.WhereSelectEnumerableIterator
2.MoveNext() at System.Collections.Generic.List
1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable
1 source) at Swashbuckle.Swagger.OperationGenerator.ApiDescriptionToOperation(ApiDescription apiDescription) at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at System.Linq.Buffer
1..ctor(IEnumerable1 source) at System.Linq.OrderedEnumerable
1.d__0.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable
1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at Swashbuckle.Swagger.ApiExplorerAdapter.CreateApi(IGrouping
2 apiDescriptionGroup, OperationGenerator operationGenerator) at Swashbuckle.Swagger.ApiExplorerAdapter.c__DisplayClassb.b__7(IGrouping2 apiDescGrp) at System.Linq.Enumerable.WhereSelectEnumerableIterator
2.MoveNext() at System.Linq.Buffer1..ctor(IEnumerable
1 source) at System.Linq.OrderedEnumerable1.d__0.MoveNext() at System.Collections.Generic.List
1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable
1 source) at Swashbuckle.Swagger.ApiExplorerAdapter.GetDeclaration(String basePath, String version, String resourceName) at Swashbuckle.Application.CachingSwaggerProvider.c__DisplayClass4.b__3(String k) at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func
2 valueFactory) at Swashbuckle.Application.CachingSwaggerProvider.GetDeclaration(String basePath, String version, String resourceName) at Swashbuckle.Application.SwaggerSpecHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.HttpServer.n__FabricatedMethod9(HttpRequestMessage , CancellationToken ) at System.Web.Http.HttpServer.d__0.MoveNext()Hi,
I do not have clear answer now, what you can do is to open issue on this github repo if you can’t find solution for your problem.
Your steps were very clear and easy to follow.
I have only had one problem: the documentation on my controller methods isn’t showing up. However everything is working correctly for the data models. I am using two different xml files to build the documentation from (controllers and models are in separate projects) and have them both included in the SwaggerConfig file. Do you have any possible insight to this problem?
Thanks.
I believe because you have 2 XML files, I never tried to do this, you can post issue request on github so plug author can answer you, he built it so he know the hacks 😉
You can just add two or more files and it will work.
SwaggerSpecConfig.Customize(c =>
{
c.IncludeXmlComments(“Path1”);
});
SwaggerSpecConfig.Customize(c =>
{
c.IncludeXmlComments(“Path2”);
});
Hi, I’m sorry that I’m a bit confused about your “startup” class. can you explain more? I can’t seem to locate such file
What is not clear about is? Please check the source code for this project, this file is responsible to build your configure your Owin components and chain them. It will only run once when you application Statrup (IIS reset, Pool recycle, etc..) Hope this answers your question.
Why this StartUp.cs file is needed. We do have Global.asax in case of asp.net mvc. Also your sample project is not working. No swagger is there
I’m using web api using Owin, that’s why there is Startup class. The sample project and the demo application contains everything you need. What is the missing in the sample project?
Hi Taiseer Joudeh,
Thanks for your quick response. Please let me clarify what I need and what I’m trying to do.
I’m using a ASP.NET WEB API2 for building Rest APIs. So there is nothing like startup.cs. If that code needs to put into a startup file then I can put it in Application_Start() method in Global.asax.
I cloned the sample project but that didn’t worked at all. I tried to run it but it always gives an xml response for Students list. Exactly the same for what its configured.
I’m very new to SwashBuckle. My Application is using .NET Framework 4.5.1. But usual swagger project is not working there. It seems to be dead with .NET Framework above 4.0. Seriously I don’t want to degrade my Framework just because of this kind of stupid reason. Could you please let me know what’s wrong with Swagger.NET project and why its not working with those framework.
If you can guide me on above mentioned issue then it would be great. Otherwise I’v no other way rather than moving to SwashBuckle. I tried to setup this thing as mentioned in sample project but that didn’t worked. If you need my code then please let me know your email Id and I’ll give to access to the remote repo. I’m stucked with this issue from last 2 weeks and losing my hope to get it resolved.
Please mind that I need JSON response from my API instead of XML. Let me know if you can guide me there and need code access. Your efforts are much appreciated.
Thanks.
Amy
did it work for you I’m facing the same issue with my project
Hi, seems like a nice project to easily add Swagger to my solution! But would it be possible to make it works without Owin? I would like to limit the dependencies of my project…
Sure, you can use it without OWIN, just check the documentation here.
Hi Taiseer Joudeh,
I got the thing. Thanks for the post. It worked well but what I want it to customize the look and feel of Swagger but I can’t locate the actual location of index.html page and swagger js files and css files. Where are they located ?
Also, the default path like as base path always remains as [ base url: http://localhost:49210/swagger/api-docs , api version: 1.0 ]
Where I can change it?
Glad it is working correctly now.
If you need more customization for Swashbuckle I recommend you to check the Issues and the documentation sections because I didn’t create this nice tool, so better to ask the experts 🙂
Is it possible to only allow certain user-roles to view the API-documentation?
Hi Jeepr,
Well as long your API end points are protected by token then I guess there is no harm to have the documentation for the API available for public. To be honest I do not know if there is straight way to do this. You can drop a comment for plugin creator.
You can add the following to web.config to restrict access to the /swagger URL to authenticated users only:
Sorry, that didn’t paste correctly. Here’s a gist: https://gist.github.com/anonymous/5a30c0592b5eb3445291
Thanks for sharing this Andy, hopefully it will be useful.
Hi Andy,
Thanks for this, it works perfectly.
I have this problem:
Error 56 ‘Owin.IAppBuilder’ does not contain a definition for ‘UseWebApi’ and no extension method ‘UseWebApi’ accepting a first argument of type ‘Owin.IAppBuilder’ could be found (are you missing a using directive or an assembly reference?)
I have a project with mvc4 y and I can not find the dll System.Web.Http.Owin. If the dll example by giving me this error:
Error 2 Assembly ‘System.Web.Http.Owin, Version=5.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ uses ‘System.Web.Http, Version=5.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ which has a higher version than referenced assembly ‘System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ c:\Users\xxxxxxx\WebApiSwagger-master\packages\Microsoft.AspNet.WebApi.Owin.5.2.0\lib\net45\System.Web.Http.Owin.dll MvcApplication1
I guess it is supported only with Web API 2, not Web API 1 (MVC 4) not sure tho.
Try to upgrade your Web API to version 2. There should not be any breaking compatibility.
Hi Taiseer,
I really liked your token based authentication with Web API article This is another great article from you.
I have question regarding oAuth implementation using swashbuckle. As per swagger-ui pet store example you can add button for oAuth authentication which pop ups the oAuth dialogue . is same thing possible using swashbuckle?
Thanks,
Paresh
Sorry for the late reply but I didn’t check if this is doable try to drop the question on GitHub repo for the plugin.
Hi
I want to some api to show some not How can i do in swagger ui + webapi
Meet in this comment thread you should find your answer.
Hey, when i hosted this in IIS i am getting 404 error while browsing the index.html and i made the changes in too , but no help. Any thoughts?
hmmm that is strange, use developer tools (F12) to check the absolute URI for index.html, most propabbly there is issue in swagger configuration file here.
http://xxx.com/pe/swagger/ui/index.html this is the url, i strongly feel some routing issue but unfortunately unable to trace the proper error in anywhere. I too commented the configuration except the init part, nothing works, as per the code, it should display the UI.
Swagger Ui and Swagger .net is Compatible with .net framework 4.5, .net framework 4.5.1, .net framework 4.5.2, .net framework 4.6
Swagger Ui and Swagger .net is Compatible with .net framework 4.5, .net framework 4.5.1, .net framework 4.5.2, .net framework 4.6 ??
Actually I Get Error…
Method ‘GetDocumentation’ in type ‘Swagger.Net.XmlCommentDocumentationProvider’ from assembly ‘Swagger.Net, Version=0.5.1.0, Culture=neutral, PublicKeyToken=null’ does not have an implementation.
Thanks man, this really helps me!
Once I configure everything, and hit the swagger endpoint is tells me no Json data was found at http://blah.com…/api-doca/. I have an XML doc an the path configured in the SwaggerConfig I am at a loss. Thanks for all of your help and tutorials,your oAuth2 tutorials thought me so much.
Re step 2, with the current version out of nuget, it seems Swashbuckle does not have a symbol Bootstrapper.
I was trying to get this working with OAUTH 2.0 Bearer tokens like they have in the pet store sample. After many tries, I finally got it figured out. Here is my stackoverflow link: http://stackoverflow.com/questions/28033857/web-api-with-oauth-using-swagger-swashbuckle/28222859#28222859
Hope this helps someone!
Thanks for sharing Shane, i’m sure it will be useful, nice work!
Nice article. I followed your steps but I met one 403.14 error. I already enabled the directory browse, however, it didn’t work. Could you give me some suggestions? Thanks
Hi Misaki,
I do not think enabling browser directory has any affect, can you elaborate more about this error?
Are you using the same version in of Swagger I’m using in the post or you are using the latest version (V 5)?
hi taiseer
In step 2 , when i add “Swashbuckle.Bootstrapper.Init(config);” line to my owin startup , it doesn’t recognize Bootstrapper. am i missing reference?
Hi Sam, make sure u are using the same version of Swagger I’m referring in the post. Maybe you are using latest one so there is breaking compatibly in the contract.
Hi,
This is a great write thanks.
I have query, I’m using basic http authentication. How can I make swashbuckle to pass Credentials ?
Can you check this comment, it will give you idea on how to integrate basic authentication with swashbuckle
I am also not able to get basic auth setup for he api calls for swagger UI, using swashbuckle…any help would be great.
I recommend you to open issue on here, it will be easier to have the answer from Repo author.
Hey Taiseer its a great article. I have a couple of questions:
1. We are using a combination of resource parameter i.e. http://test.net/api/Product/{productid} and also the web method also accepts values through headers, is there a way to test using swagger and pass those headers, rather than using POST man like tools to test away from swagger documentation?
2. Is there a way to rename the url from swagger to “mydocumentation” if so how? i.e.
http://webapiswagger.azurewebsites.net/{swagger}/ui/index.html#!/Students
http://webapiswagger.azurewebsites.net/{mydocumentation}/ui/index.html#!/Students
Thanks in advance.
Hi, to be honest I don’t have clear answer for those questions, I do not know all the in/out of swachbukle as I didn’t implement it, my recommendation is to contact plugin author or open issue on his Repo.
Hi, I’ve followed your example and everything looks good but one thing. My models show up with namespace and all (Company.Product.Area.Class) instead of just the class name as in your example. Do you know how to remove the namespaces?
Nice article! It is mentioned that this tool is language-agnostic. Can I use Swagger / Swashbuckle for oData Web API?
Thats a good question, I’ve faced the same situation one month ago, Swagger doesn’t fully support OData controllers, but there is a side tool that might help to generate swagger specification file from OData service.
Good luck!
FYI, I just started a project to enable Swashbuckle OData support. See https://github.com/rbeauchamp/Swashbuckle.OData
Thanks Richard. I’ll be checking this it out.
Hi Taiseer,
Is there any way we can suppress the methods from appearing in documentation? We have some controller methods, plus have some entries in webapi config. So it ends up having duplicate method in swagger documentation. Is there any workaround to avoid this?
Hi Prashant,
I guess you need to attribute the actions with [obsolete] attribute, not the prettiest thing to do, but it should work. Check the documentation here
Hi,
Can we set a windows authentication to provide authorize access to swagger documentation?
Thanks in advance
I’m not sure, but I guess not. What is the use case you want to enable windows authentication for your APIs?
Hi Taiseer Joudeh,
Great article, easily understandable even for beginners, kudos.
I have a different scenario, let me know if you can help me out.
-> As of now on load, we get all the documentation of the methods, but I want them to be loaded only after entering a valid API_Key and click on Explore button, is there any possible way for that. I mean, only users with valid API key should be able to see the documentation, and that API key should be matching with my App.config key value.
Thanks in advance.
I’m not sure of all those configuration, better to submit issue at the GitHub repo of Swashbuckle. Thanks
Hi Taiseer,
Great blog post. I created an ASP.NET WEB API that work fine. I follow what you wrote to install Swashbuckle everything worked fine but “Step 2: Call the bootstrapper in “Startup” class”. I had no startup class.
I run swagger and it run in debug in VS 2015. But when I compile in release to install on IIS I get only swagger header and nothing else ?
Can you help me please ?
cheers
Jean
Very helpful, thank you!
One issue to be aware of – if you encounter a 500 server error after deploying a non-debug (Release) build when navigating to …./swagger/ui/index:
Make sure you’ve set the xml document output for the Release configuration as well! Doh!
The issue is abundantly clear if you add to your web.config element to debug, but ahem, you may not think of it right off with a remote server and/or azure web app.
All the best!
Jim
Thanks for the heads up and for your message 🙂
Hi Stott, I am having the same issue. I have enabled the xml doc. I have enabled it for all configrations and it is working fine locally but it gives 500 error on azure web api app. any idea.
When I try to use nuget to add swashbuckle, I’m unable to reference the swashbuckle classes. The relative path to the dll in the .csproj doesn’t work but when I change it to an absolute path, it works. So bizarre. I noticed that the relative path works in your sample project though.
Hi Taiseer, this is another great article from you. Previously, I follow your access token based api article which use Microsoft.Owin. Now, I also followed this great article. Everything works as expected, however I want to show a method to our api consumer on how to call the api to get the access token. FYI – I have already implemented built in functionality of swash buckle to pass access token in the header. I want to display the documentation of my http://localhost/api/v1/token method as well in the swagger UI. Is that possible to show ?
Hi Singh,
I’m not sure how you can implement this, better to open issue on Swashbuckle Github repo.
Hi, I tried to achieve this by replicating the oauth token endpoint with an account controller endpoint. For eg: my api has an account controller which has bunch of methods showing in the swagger the documentation. I wanted to put token endpoint as well under the same controller to make the documentation more clearer to the user.. I created an another empty action under account controller by the name of token so that i can make look like same in the swagger – the endpoint became like api/v1/Account/token. Now, I gave the token endpoint path in Configure Oauth function in the start up like below:
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp=true,
TokenEndpointPath=new PathString(“/api/v1/Account/token”),
AccessTokenExpireTimeSpan=TimeSpan.FromDays(1),
Provider=new SimpleAuthorizationServerProvider()
};
So, when an user is making the call to the token endpoint, it actually goes through the oauth authentication, not through the method that i created in action controller which is good. So, I achieved what i wanted show. However, now the only concern is how can i describe to my users to pass the credentials to get the access_token as a one string (grant_type=password&username=myuser&password=mypsw) which makes me wondering.
BTW, is it possible to set in the api to accept username and password credentials as a json format instead of form-url encoded ?
The Oauth Specs uses form-urlencoded as specified here, why would you like to post JSON instead?
Hi Taiseer, congratulations for all your blogs.
I’m using Swashbuckle 5 and I’m trying to configure it to enable token based authentication. I mean, I want to enable password grant flow but I don’t figure out how can I do it. Is possible swashbuckle 5 not support password grant flow yet?
Thanks!!
Thanks for you message Cisco,
So far I guess it only supports the implicit grant flow, you can open issue here.
I have deployed my webapi as a windows service, and it runs find in debug mode from VS. but when I install it using installutil it does not load the JS/CSS/Image etc and gives 401 for each resource. can you please suggest?
I’m little bit lost here, did you deploy the API only as a windows service? or you deployed the entire application? As far as I know You can host the Api in windows application but you can’t host the static files, css, images, etc…
I am getting this exact same error. In debug mode it works great locally, in release mode it doesnt work locally and i get 401 errors etc. I have enabled the xml output for releasemode as well, so this shouldnt be the issue.
What is the error you are facing? just 401 response?
Hello,
Thanks for this great a article. Please keep it coming 🙂
Following your example, I created a basic OWIN ASP.NET Web API2, installed SwashBuckle via Nuget, then configured the SwaggerConfig.vb file as follow:
***********************************************
Public Module SwaggerConfig
Public Sub Register()
Swashbuckle.Bootstrapper.Init(GlobalConfiguration.Configuration)
SwaggerSpecConfig.Customize(Sub(c)
c.IncludeXmlComments(GetXmlCommentsPath())
End Sub)
End Sub
Private Function GetXmlCommentsPath() As String
Return String.Format(“{0}bin\AuthServerApi.xml”, System.AppDomain.CurrentDomain.BaseDirectory)
End Function
End Module
***********************************************
When I hit the “Try it out!” button – On the Remote Server – to test the API, here’s what I get:
http://mydevwebserver/myapi/swagger/api-docs
http://localhost:50648/swagger/api-docs
On IIS Express (Debug Mode) – works as expected
Request URL:
http://localhost:50648/api/audiences
Response Code: 200
On IIS (Release Mode) – NOT WORKING – “myapi” is missing from the URL
Request URL:
http://mydevwebserver:80/api/audiences
Response Code: 404
Thanks for your insight.
Nae
What about apidox.net? we use this tool in order to have a way to have documented, test and shareable API of our projects. Hope is useful for someone as alternative.
Looks interesting, I will check apidox.net soon.
The parameters for model won’t be shown in document for current Swashbuckle/Swagger now. I copied your Student/StudentController to my project and followed your instruction. But the Student Model part was not show on my document.
Are you using the same Nuget package version or the latest ones? The psot is a bit old so maybe there is now breaking changes with the new version.
Great Article! Was ready in 1 hour to have my API documented!
Happy to hear that it is still working after 2 years, thanks Casper for your comment 🙂
Is there any way available to change the example value and provide our custom example?
/api/Students/{userName} for DELETE request must be changed for /api/Students/{student_id}
Thanks for the heads up, I will check and update it 🙂
I found this helpful in 2017, irrespective of API qualities–restfulness is in the eye of the beholder, apparently. Thanks for sharing–and keep it up!
You are welcome, happy to know posts still useful after 3 years 🙂
I have a ASP.NET web API, which is OWIN hosted. It refers to another project (c# library) which contains Contoller, endpoints. Is it possible to configure Swagger to show the endpoints which are in referenced dll?
Following is the code in my host (startup class). When I do this, it only the lists the endpoints, which are in controllers of host project.
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Get your HttpConfiguration.
var config = new HttpConfiguration();
config.EnableSwagger(c =>
{
c.SingleApiVersion(“v1”, “Swagger Test API”); c.IncludeXmlComments(GetXmlCommentsPath());
c.ResolveConflictingActions(x => x.First());
}).EnableSwaggerUi();
app.UseCors(CorsOptions.AllowAll);
WebApiConfig.Register(config);
app.UseWebApi(config);
}
Great Article! But I have one question like, when I enable this documentation feature through swagger I am able to see all kind of information about my documentation but their no details about your API return type.
I am only able to see status code.
so for example if my method signature is like below :
///
/// Add some xyz entity
///
/// The list of xyz
///
/// Returns true if xyz are added successfully,else false.
///
[HttpPost]
public bool Add(IList xyz)
{
return true;
}
Then I am not able to see “Returns true if xyz are added successfully,else false” on swagger API documentation.
Please help me on this…….
found my question answer here :
http://www.wmpratt.com/swagger-and-asp-net-web-api-part-1/
But now I am stuck with how to show controller documentation content like for example
///
/// Represents the XYZ api controller class.
///
public class XYZController : ApiController
{
}
On enabling swagger I am not able to see this content any where ” Represents the XYZ api controller class.”
Please help how can I tackle this issue.
Sorry Harvis for the late reply and happy that you find the answer already.
Great article! I would like to know if we can customize the swagger documentation with only some routes. Help is appreciated. Thank you.
Hi.
Thanks for this great a article.
I added a note to the front of the controller class, but it doesn’t show in the web api document.
How to do ?
Hi,
i am using swash buckle 5.6.0 version and its converting my request dataModel Example into camel casing even my model in pascal casing in c#.
[SwaggerRequestExample(typeof(BookDto), typeof(BookModelExample))].
any help ..how can i convert my model into pascal case in swash buckle.
i am using
[SwaggerResponseExample(HttpStatusCode.OK, typeof(PenModelExample),typeof(DefaultContractResolver))]
and its working fine for response model and converting into pascal case.but not working for my SwaggerRequestExample.
any help.
Nice Article
Hi,
I have looked all over but I did not see a post on how to modify Swagger Example Value. Please show how to modify Example Value to display polymorphic objects (parent and child objects).
Hi.
Thanks for this great a article.