a blog for those who code

Thursday 13 September 2018

How I added Swagger in LetsDisc Repo

Swagger UI allows the development team to visualize and interact with the API without actually implementing logic in place. Its automatically generated from the specification, which makes it really easy for back end implementation and client side consumption.

I have created a LetsDisc which will be a Clone of StackOverflow on Steem Blockchain. LetsDisc can solve the problem to keep everything on one place. Though you will have an option to Post on Steem, if you do not have the Steem Account, you can use it without posting it. As of now you can Login, Register, Create/Edit Question, Upvote other users questions.


I tried to change the normal JavaScript code to AngularJS, so for that I try to use SwaggerUI for consuming in my frontend. To do it I have done like below,

At first Install the Swashbuckle.AspNetCore NuGet package(https://www.nuget.org/packages/Swashbuckle.AspNetCore/) to your Web project.

Then added the below code in ConfigureServices function of Startup.cs

services.AddSwaggerGen(options =>
{
 options.SwaggerDoc("v1", new Info { Title = "LetsDisc API", Version = "v1" });
 options.DocInclusionPredicate((docName, description) => true);
});


Then added the below code in Configure function of Startup.cs

// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUI(options =>
{
  options.SwaggerEndpoint(_appConfiguration["App:ServerRootAddress"] + "/swagger/v1/swagger.json", "LetsDisc API V1");
  options.IndexStream = () => Assembly.GetExecutingAssembly()
                    .GetManifestResourceStream("LetsDisc.Web.Host.wwwroot.swagger.ui.index.html");
}); // URL: /swagger


That's it, when you run your application and go to /swagger/index.html you will see all the API's are documented.

Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a Comment