theGeekster
theGeekster

Reputation: 6231

Generate WebAPI documentation in swagger json format

I have created a WebAPI using .Net 4.5 and want to document this API using Swagger. I have added swagger-ui in my .Net project. Now when i browse to ../swagger-ui/index.html it successfully opens pet store api-docs (json) in swagger UI format.

My question is how can I create such (swagger) json for my WebAPI controllers and models? As I have put in required XML summaries/comments to c# classes and attributes.

I saw that Swagger.Net and Swashbuckle are there doing similar things but I could not really understand how to generate swagger-json file using any of them. There might be very small mistake I am doing but unable to point out.

Please help.

Upvotes: 18

Views: 24517

Answers (3)

velmurugan
velmurugan

Reputation: 19

You can use "NSwagStudio" desktop application to load the json document without running the api project. By providing the api assembly.

https://github.com/RSuter/NSwag/wiki/NSwagStudio

Download the (NSwagStudio) windows desktop application.

Upvotes: 1

Matt Frear
Matt Frear

Reputation: 54801

As stated, /swagger takes you to the swagger UI.

If you're using Swashbuckle, then /swagger/docs/v1 should take you to the swagger.json file - I found this using Chrome Dev tools.

Edit: if you're using Swashbuckle.AspNetCore, then the url is slightly different - /swagger/v1/swagger.json

Upvotes: 27

Todd Smith
Todd Smith

Reputation: 17272

You need to integrate Swagger.NET into your project so that you end up with the following controller:

public class SwaggerController : ApiController { /* snip */ }

and you should also have the following route registered:

context.Routes.MapHttpRoute (
name : "Swagger",
routeTemplate: "api/swagger"
defaults: new
{
  controller = "Swagger",
  action = "Get",
});

assuming that is working you should be able to call /api/swagger and get something like the following:

{
  apiVersion: "4.0.0.0",
  swaggerVersion: "2.0",
  basePath: "http://localhost:5555",
  resourcePath: null,
  apis: [
  {
    path: "/api/docs/Values",
    description: "No Documentation Found.",
    operations: [ ]
  },
  {
    path: "/api/docs/Home",
    description: "No Documentation Found.",
    operations: [ ]
  }
]

}

then in SwaggerUI/index.html you'll want to update the discoveryUrl:

<script type="text/javascript">
    $(function () {
        window.swaggerUi = new SwaggerUi({
            discoveryUrl: "http://localhost:5555/api/swagger",
            apiKey:"",
            dom_id:"swagger-ui-container",
            supportHeaderParams: false,
            supportedSubmitMethods: ['get', 'post', 'put']
        });

        window.swaggerUi.load();
    });
</script>

Upvotes: 4

Related Questions