Bit of Technology

  • Archive
  • About Me
    • Advertise
    • Disclaimer
  • Speaking
  • Contact

ASP.NET Web API Documentation using Swagger

August 25, 2014 By Taiseer Joudeh 120 Comments

Be Sociable, Share!

  • Tweet
  • Email
  • WhatsApp

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:

Asp.Net Web Api Swagger

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.

Swagger XML Comments

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:
Swagger XML Tags Mapping

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.

Follow me on Twitter @tjoudeh

Be Sociable, Share!

  • Tweet
  • Email
  • WhatsApp

Filed Under: ASP.Net Web API, RESTful API Tagged With: Documentation, Swagger, Swagger-ui, Swashbuckle

Comments

  1. Dave Van den Eynde (@DaveVdE) says

    August 25, 2014 at 2:07 pm

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

    Reply
    • Taiseer Joudeh says

      August 26, 2014 at 6:30 pm

      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.

      Reply
    • Joe G says

      April 12, 2016 at 7:04 pm

      @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

      Reply
      • Chris says

        October 13, 2016 at 3:42 am

        Fielding says in order to be restfull you MUST have HATEOAS, so he is correct. Still nitpicky, but correct.

        Reply
  2. Karl Gjertsen says

    August 26, 2014 at 1:30 pm

    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.

    Reply
    • Taiseer Joudeh says

      August 26, 2014 at 5:24 pm

      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.

      Reply
  3. Hendra Setiawan says

    August 27, 2014 at 9:26 am

    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.

    Reply
    • Taiseer Joudeh says

      August 27, 2014 at 10:23 pm

      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.

      Reply
      • Xavi says

        September 18, 2014 at 6:42 pm

        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 };
        });

        Reply
        • Taiseer Joudeh says

          September 18, 2014 at 6:56 pm

          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.

          Reply
          • Xavi says

            September 19, 2014 at 1:32 pm

            Thank you Taiseer, it works like a charm!

          • parersh says

            December 17, 2014 at 10:18 pm

            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

  4. mawashikid says

    September 11, 2014 at 7:13 pm

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

    Reply
    • Taiseer Joudeh says

      September 12, 2014 at 10:15 pm

      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 🙂

      Reply
      • mawashikid says

        September 12, 2014 at 10:30 pm

        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

        Reply
  5. Savvas says

    September 12, 2014 at 2:23 pm

    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

    Reply
    • Taiseer Joudeh says

      September 12, 2014 at 10:47 pm

      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?

      Reply
      • bmerrills says

        October 28, 2014 at 3:20 pm

        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?

        Reply
        • Jasper van Zuijlen says

          September 11, 2015 at 12:10 pm

          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

          Reply
  6. Gautham says

    September 23, 2014 at 5:55 pm

    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?

    Reply
  7. anilch says

    September 26, 2014 at 8:00 am

    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(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at Swashbuckle.Swagger.OperationGenerator.ApiDescriptionToOperation(ApiDescription apiDescription) at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Linq.Buffer`1..ctor(IEnumerable`1 source) at System.Linq.OrderedEnumerable`1.d__0.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at Swashbuckle.Swagger.ApiExplorerAdapter.CreateApi(IGrouping`2 apiDescriptionGroup, OperationGenerator operationGenerator) at Swashbuckle.Swagger.ApiExplorerAdapter.c__DisplayClassb.b__7(IGrouping`2 apiDescGrp) at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Linq.Buffer`1..ctor(IEnumerable`1 source) at System.Linq.OrderedEnumerable`1.d__0.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 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.ConcurrentDictionary`2.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()

    Reply
    • Taiseer Joudeh says

      September 27, 2014 at 1:12 am

      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.

      Reply
  8. ajery says

    October 4, 2014 at 12:16 am

    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.

    Reply
    • Taiseer Joudeh says

      October 5, 2014 at 9:17 am

      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 😉

      Reply
    • Hernan Guzman says

      December 10, 2014 at 9:04 pm

      You can just add two or more files and it will work.

      SwaggerSpecConfig.Customize(c =>
      {
      c.IncludeXmlComments(“Path1”);
      });

      SwaggerSpecConfig.Customize(c =>
      {
      c.IncludeXmlComments(“Path2”);
      });

      Reply
  9. Jim says

    October 14, 2014 at 9:35 am

    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

    Reply
    • Taiseer Joudeh says

      October 15, 2014 at 11:49 am

      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.

      Reply
  10. Amy says

    November 2, 2014 at 3:49 pm

    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

    Reply
    • Taiseer Joudeh says

      November 2, 2014 at 8:50 pm

      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?

      Reply
      • Amy says

        November 2, 2014 at 9:54 pm

        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

        Reply
        • Nada Yousef says

          April 26, 2020 at 4:30 pm

          did it work for you I’m facing the same issue with my project

          Reply
      • Jeff says

        December 10, 2014 at 5:54 pm

        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…

        Reply
        • Taiseer Joudeh says

          December 10, 2014 at 6:38 pm

          Sure, you can use it without OWIN, just check the documentation here.

          Reply
  11. Amy says

    November 3, 2014 at 5:22 pm

    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 ?

    Reply
  12. Amy says

    November 3, 2014 at 5:27 pm

    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?

    Reply
    • Taiseer Joudeh says

      November 3, 2014 at 11:15 pm

      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 🙂

      Reply
  13. jeepr says

    November 8, 2014 at 10:53 am

    Is it possible to only allow certain user-roles to view the API-documentation?

    Reply
    • Taiseer Joudeh says

      November 8, 2014 at 10:16 pm

      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.

      Reply
      • Andy says

        December 11, 2014 at 7:52 pm

        You can add the following to web.config to restrict access to the /swagger URL to authenticated users only:

        Reply
        • Andy says

          December 11, 2014 at 7:56 pm

          Sorry, that didn’t paste correctly. Here’s a gist: https://gist.github.com/anonymous/5a30c0592b5eb3445291

          Reply
          • Taiseer Joudeh says

            December 11, 2014 at 8:51 pm

            Thanks for sharing this Andy, hopefully it will be useful.

          • jeepr says

            December 13, 2014 at 2:34 pm

            Hi Andy,

            Thanks for this, it works perfectly.

  14. David says

    November 20, 2014 at 6:39 pm

    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

    Reply
    • Taiseer Joudeh says

      November 21, 2014 at 3:55 am

      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.

      Reply
  15. parersh says

    December 22, 2014 at 11:07 pm

    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

    Reply
    • Taiseer Joudeh says

      December 24, 2014 at 5:15 pm

      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.

      Reply
  16. Meet says

    December 26, 2014 at 12:23 pm

    Hi
    I want to some api to show some not How can i do in swagger ui + webapi

    Reply
    • Taiseer Joudeh says

      December 27, 2014 at 3:53 pm

      Meet in this comment thread you should find your answer.

      Reply
  17. gomesnayagam says

    December 29, 2014 at 8:07 pm

    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?

    Reply
    • Taiseer Joudeh says

      December 30, 2014 at 2:28 pm

      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.

      Reply
      • gomesnayagam says

        December 30, 2014 at 7:44 pm

        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.

        Reply
  18. meet says

    December 30, 2014 at 2:22 pm

    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

    Reply
  19. meet says

    December 30, 2014 at 2:24 pm

    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.

    Reply
  20. vmorenomello says

    December 30, 2014 at 2:37 pm

    Thanks man, this really helps me!

    Reply
  21. Corey Howard says

    January 17, 2015 at 5:46 pm

    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.

    Reply
  22. Sean says

    January 18, 2015 at 3:41 pm

    Re step 2, with the current version out of nuget, it seems Swashbuckle does not have a symbol Bootstrapper.

    Reply
  23. Shane says

    January 29, 2015 at 9:24 pm

    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!

    Reply
    • Taiseer Joudeh says

      January 29, 2015 at 11:14 pm

      Thanks for sharing Shane, i’m sure it will be useful, nice work!

      Reply
  24. Misaki says

    February 19, 2015 at 6:37 pm

    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

    Reply
    • Taiseer Joudeh says

      February 19, 2015 at 8:55 pm

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

      Reply
  25. Sam says

    February 26, 2015 at 10:20 am

    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?

    Reply
    • Taiseer Joudeh says

      February 27, 2015 at 5:54 am

      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.

      Reply
  26. Sagar says

    March 17, 2015 at 3:05 pm

    Hi,

    This is a great write thanks.
    I have query, I’m using basic http authentication. How can I make swashbuckle to pass Credentials ?

    Reply
    • Taiseer Joudeh says

      March 18, 2015 at 7:21 pm

      Can you check this comment, it will give you idea on how to integrate basic authentication with swashbuckle

      Reply
      • john says

        April 2, 2015 at 11:15 pm

        I am also not able to get basic auth setup for he api calls for swagger UI, using swashbuckle…any help would be great.

        Reply
        • Taiseer Joudeh says

          April 3, 2015 at 7:09 pm

          I recommend you to open issue on here, it will be easier to have the answer from Repo author.

          Reply
  27. gnagakarthik says

    May 22, 2015 at 3:40 am

    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.

    Reply
    • Taiseer Joudeh says

      May 24, 2015 at 7:56 am

      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.

      Reply
  28. Pål K. Tønder says

    June 26, 2015 at 3:15 pm

    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?

    Reply
  29. Albert says

    July 24, 2015 at 4:59 am

    Nice article! It is mentioned that this tool is language-agnostic. Can I use Swagger / Swashbuckle for oData Web API?

    Reply
    • Taiseer Joudeh says

      July 27, 2015 at 4:30 am

      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!

      Reply
      • Richard Beauchamp says

        November 18, 2015 at 5:55 am

        FYI, I just started a project to enable Swashbuckle OData support. See https://github.com/rbeauchamp/Swashbuckle.OData

        Reply
        • Albert says

          December 23, 2015 at 1:19 am

          Thanks Richard. I’ll be checking this it out.

          Reply
  30. Prashant says

    August 7, 2015 at 9:34 am

    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?

    Reply
    • Taiseer Joudeh says

      August 8, 2015 at 7:41 am

      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

      Reply
  31. Prashant says

    August 10, 2015 at 3:12 am

    Hi,

    Can we set a windows authentication to provide authorize access to swagger documentation?

    Thanks in advance

    Reply
    • Taiseer Joudeh says

      August 15, 2015 at 1:23 am

      I’m not sure, but I guess not. What is the use case you want to enable windows authentication for your APIs?

      Reply
  32. raghu says

    August 27, 2015 at 7:48 pm

    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.

    Reply
    • Taiseer Joudeh says

      September 7, 2015 at 6:56 am

      I’m not sure of all those configuration, better to submit issue at the GitHub repo of Swashbuckle. Thanks

      Reply
  33. jean fevre says

    August 29, 2015 at 3:02 am

    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

    Reply
  34. J StottJim says

    September 1, 2015 at 8:31 pm

    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

    Reply
    • Taiseer Joudeh says

      September 5, 2015 at 10:22 pm

      Thanks for the heads up and for your message 🙂

      Reply
    • haroonlatif says

      September 16, 2015 at 7:45 pm

      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.

      Reply
  35. Arvind (@arviman) says

    September 22, 2015 at 3:43 pm

    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.

    Reply
  36. Bhupinder Singh says

    September 24, 2015 at 12:42 am

    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 ?

    Reply
    • Taiseer Joudeh says

      October 3, 2015 at 6:00 pm

      Hi Singh,
      I’m not sure how you can implement this, better to open issue on Swashbuckle Github repo.

      Reply
      • Bhupinder Singh says

        October 6, 2015 at 5:36 am

        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.

        Reply
        • Bhupinder Singh says

          October 9, 2015 at 5:08 am

          BTW, is it possible to set in the api to accept username and password credentials as a json format instead of form-url encoded ?

          Reply
          • Taiseer Joudeh says

            October 12, 2015 at 10:23 am

            The Oauth Specs uses form-urlencoded as specified here, why would you like to post JSON instead?

  37. Cisco says

    December 1, 2015 at 3:23 pm

    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!!

    Reply
    • Taiseer Joudeh says

      December 2, 2015 at 12:30 pm

      Thanks for you message Cisco,
      So far I guess it only supports the implicit grant flow, you can open issue here.

      Reply
  38. Nishant Dave says

    February 2, 2016 at 2:25 am

    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?

    Reply
    • Taiseer Joudeh says

      February 3, 2016 at 2:00 am

      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…

      Reply
      • geddonion says

        March 3, 2016 at 12:03 am

        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.

        Reply
        • Taiseer Joudeh says

          March 3, 2016 at 1:21 pm

          What is the error you are facing? just 401 response?

          Reply
  39. Nae says

    February 5, 2016 at 4:14 pm

    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

    Reply
  40. Jose Antonio Lopez (@jalopezsuarez) says

    March 14, 2016 at 1:21 am

    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.

    Reply
    • Taiseer Joudeh says

      March 15, 2016 at 10:57 am

      Looks interesting, I will check apidox.net soon.

      Reply
  41. bagusflyer says

    August 23, 2016 at 8:18 am

    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.

    Reply
    • Taiseer Joudeh says

      August 24, 2016 at 11:28 am

      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.

      Reply
  42. Caspar Kleijne says

    October 29, 2016 at 12:42 pm

    Great Article! Was ready in 1 hour to have my API documented!

    Reply
    • Taiseer Joudeh says

      November 3, 2016 at 7:19 pm

      Happy to hear that it is still working after 2 years, thanks Casper for your comment 🙂

      Reply
  43. jp says

    December 21, 2016 at 9:59 pm

    /api/Students/{userName} for DELETE request must be changed for /api/Students/{student_id}

    Reply
    • Taiseer Joudeh says

      December 23, 2016 at 2:14 am

      Thanks for the heads up, I will check and update it 🙂

      Reply
  44. tbw says

    January 2, 2017 at 10:17 pm

    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!

    Reply
    • Taiseer Joudeh says

      January 8, 2017 at 9:22 pm

      You are welcome, happy to know posts still useful after 3 years 🙂

      Reply
  45. JARVIS says

    February 2, 2017 at 9:20 pm

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

    Reply
    • JARVIS says

      February 2, 2017 at 9:54 pm

      found my question answer here :

      http://www.wmpratt.com/swagger-and-asp-net-web-api-part-1/

      Reply
      • JARVIS says

        February 2, 2017 at 10:07 pm

        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.

        Reply
      • Taiseer Joudeh says

        February 14, 2017 at 1:25 am

        Sorry Harvis for the late reply and happy that you find the answer already.

        Reply
  46. Sima says

    September 27, 2017 at 10:28 pm

    Great article! I would like to know if we can customize the swagger documentation with only some routes. Help is appreciated. Thank you.

    Reply
  47. Cui says

    October 19, 2017 at 10:36 am

    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 ?

    Reply
  48. moh says

    October 25, 2017 at 12:57 pm

    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.

    Reply
    • moh says

      October 25, 2017 at 12:59 pm

      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.

      Reply
  49. Shivanand Koli says

    December 14, 2017 at 4:33 pm

    Nice Article

    Reply
  50. Oangodd says

    December 17, 2017 at 8:57 pm

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

    Reply

Trackbacks

  1. Web API Deep Dive – Customizing Auto-Generated Documentation (Part 1 of 6) – Code Thug says:
    January 16, 2015 at 3:51 pm

    […] Including Extra Files with MSDeploy Deploying Extra Files Web API Documentation Tools Swagger – an better looking documentation generator Swashbuckle, a utility to help install Swagger […]

    Reply
  2. Support Token Based Authentication in Swagger Documentation for Web API - DexPage says:
    July 6, 2015 at 6:33 am

    […] for generating web api documentation. I have successfully generated the documentation using Web API documentation using swagger but I am not able to successfully send API requests, as we have token based authentication (custom […]

    Reply
  3. Confluence: Sentience Cloud says:
    October 23, 2017 at 7:15 am

    Configure Swagger for Web Api Documentation

      How to add new web api Tests\Tools\SwaggerBulldo

    Reply
  4. Libido Force Reviews says:
    July 12, 2019 at 1:01 pm

    Libido Force Reviews

    ERROR: The requested URL could not be retrieved

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About Taiseer

Husband, Father, Consultant @ MSFT, Life Time Learner... Read More…

Buy me a coffeeBuy me a coffee

Recent Posts

  • Integrate Azure AD B2C with ASP.NET MVC Web App – Part 3
  • Secure ASP.NET Web API 2 using Azure AD B2C – Part 2
  • Azure Active Directory B2C Overview and Policies Management – Part 1
  • ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 – Part 5
  • ASP.NET Identity 2.1 Roles Based Authorization with ASP.NET Web API – Part 4

Blog Archives

Recent Posts

  • Integrate Azure AD B2C with ASP.NET MVC Web App – Part 3
  • Secure ASP.NET Web API 2 using Azure AD B2C – Part 2
  • Azure Active Directory B2C Overview and Policies Management – Part 1
  • ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 – Part 5
  • ASP.NET Identity 2.1 Roles Based Authorization with ASP.NET Web API – Part 4

Tags

AJAX AngularJS API API Versioning ASP.NET Authentication Autherization Server Azure Active Directory B2C Azure AD B2C basic authentication C# CacheCow Client Side Templating Code First Dependency Injection Entity Framework ETag Foursquare API HTTP Caching HTTP Verbs IMDB API IoC Javascript jQuery JSON JSON Web Tokens JWT Model Factory Ninject OAuth OData Pagination Resources Association Resource Server REST RESTful Single Page Applications SPA Token Authentication Tutorial Web API Web API 2 Web API Security Web Service wordpress.com

Search

Copyright © 2021 · eleven40 Pro Theme on Genesis Framework · WordPress · Log in

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.