Buscar contenidos

miércoles, 12 de julio de 2017

Swagger, framework para generar documentación de APIs RESTful (WebAPI)

Link artículo


WebApi - FullFramework - Página Inicio Swagger

   void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Request.AppRelativeCurrentExecutionFilePath == "~/")
                Response.Redirect("~/swagger");
        }


Swagger es una herramienta extremadamente útil para describir, producir, consumir y visualizar APIs RESTful. El principal objetivo de este framework es enganchar el sistema de documentación con el código del servidor para que esté sincronizado a cada cambio. Casi documentamos al mismo tiempo que creamos la implementación.








        [System.Web.Http.Route("Method")]
        public string Method(string userName, string password)
        {
             return "Hello";
        }






.Net Core



http://www.talkingdotnet.com/add-swagger-to-asp-net-core-2-0-web-api/






Add Swagger to ASP.NET Core 2.0 Web API


Open Startup.cs file to add swagger service to middleware. Like:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "My API",
Description = "My First ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact() { Name = "Talking Dotnet", Email = "contact@talkingdotnet.com", Url = "www.talkingdotnet.com" }
});
});
}
view rawSwaggerStartup.cs hosted with ❤ by GitHub
And enable the Swagger UI in Configure() method.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
This is all required to set up Swagger. The one last thing to do is to change the application launch URL so that Swagger UI loads on launch. To set Swagger UI as launch URL, right-click on Project -> select properties -> navigate to debug tab. On debug tab, change Launch Browser value to “swagger”.

Run the APP and you should see Swagger UI for ValuesContoller.

Swagger uses different colors for each HTTP verb to differentiate API actions. Clicking on any method will give you details about accepted parameters, return type and allows you to test the method.
This is achieved with minimal configuration and without any customization. Swagger can be customized to include method’s XML comments, showing enum values as string values and generating different swagger document for different API version.

Show action’s XML Comments

We all are familiar with XML comments for documentation. By default, swagger does not show XML comments. There is an option to display them with Swagger UI. First, we need to ensure that when the project is built, all the XML comments get saved in an XML file. Swagger will use this file to show XML comments on the Swagger UI.
To save XML comments in a file, right-click on the project -> properties and navigate to the build tab. On this tab, check “XML documentation file” option.

By enabling this option, xml comments are saved in an XML file with the name [your assembly].xml. This file is located at bin\[Debug/Release]\netcoreapp2.0 folder. We need to pass this path Swashbuckle’s IncludeXMLComments method.
Add a method in Startup.cs to get the path of generated XML. This code to get the XML path will work in your local environment as well as in the production environment.
1
2
3
4
5
private string GetXmlCommentsPath()
{
    var app = System.AppContext.BaseDirectory;
    return System.IO.Path.Combine(app.ApplicationBasePath, “ASPNETCoreSwaggerDemo.xml”);
}
Next, add code to include XML comments in ConfigureService method. Like:
1
2
3
4
services.AddSwaggerGen(c =>
{
   c.IncludeXmlComments(GetXmlCommentsPath());
}
Next, add XML comments to our actions. Here is XML comment for Delete method.
1
2
3
4
5
6
7
8
9
10
// DELETE api/values/5
/// <summary>
/// Delete API Value
/// </summary>
/// <remarks>This API will delete the values.</remarks>
/// <param name="id"></param>
[HttpDelete("{id}")]
public void Delete(int id)
{
}
Now run the app, you should see XML comments.

No hay comentarios:

Publicar un comentario