AYUDA .NET

OpenAPI .NET (Cómo funciona para los desarrolladores)

Actualizado julio 1, 2024
Compartir:

OpenAPI, antes conocida como Swagger, es una especificación para construir y describir API RESTful. Permite a los desarrolladores definir la estructura de sus API en un formato estandarizado, lo que permite a diversas herramientas y servicios entender e interactuar con la API REST de manera eficaz y proporcionar retroalimentación. En el ecosistema .NET, la integración de OpenAPI .NET se facilita a través de varias bibliotecas y herramientas que facilitan la creación, documentación y consumo de API.

En este artículo, aprenderemos acerca de las especificaciones de soporte OpenAPI y cómo crear un archivo PDF utilizando IronPDF y devolverlo como una respuesta de llamada API.

Configuración de OpenAPI en .NET

Para empezar con el proyecto OpenAPI .NET, normalmente se utiliza la biblioteca Swashbuckle, que genera la especificación o documentación OpenAPI para sus API ASP.NET Core.

Paso 1: Instalar Swashbuckle

En primer lugar, debe instalar el paquete Swashbuckle.AspNetCore a través de NuGet en Visual Studio. Puede hacerlo utilizando la consola del gestor de paquetes NuGet:

Install-Package Swashbuckle.AspNetCore

O utilizando la CLI .NET:

dotnet add package Swashbuckle.AspNetCore

Paso 2: Configurar Swashbuckle

A continuación, debe configurar Swashbuckle en su proyecto ASP.NET Core. Esto implica actualizar el archivo Startup.cs para añadir servicios Swagger y configurar el middleware Swagger.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI description at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI description at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Dim builder = WebApplication.CreateBuilder(args)

' Add services to the container.
builder.Services.AddControllers()
' Learn more about configuring Swagger/OpenAPI description at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer()
builder.Services.AddSwaggerGen()

Dim app = builder.Build()

' Configure the HTTP request pipeline.
If app.Environment.IsDevelopment() Then
	app.UseSwagger()
	app.UseSwaggerUI()
End If

app.UseHttpsRedirection()
app.UseAuthorization()
app.MapControllers()
app.Run()
VB   C#

Generación y visualización de la documentación de la API

Una vez configurado Swashbuckle, la ejecución de su aplicación generará automáticamente la documentación OpenAPI. Puede ver estas descripciones OpenAPI navegando a la Swagger UI, normalmente accesible en http://localhost:5000/swagger.

Uso de las definiciones OpenAPI

Las definiciones OpenAPI son potentes herramientas que pueden utilizarse para generar SDK de cliente, probar API y garantizar la coherencia entre distintos servicios. La especificación OpenAPI define una interfaz estándar e independiente del lenguaje para las API, que permite tanto a humanos como a ordenadores comprender las capacidades de un servicio sin necesidad de acceder al código fuente.

Ampliación de OpenAPI con anotaciones personalizadas

Swashbuckle le permite mejorar su documentación OpenAPI con anotaciones personalizadas. Estas anotaciones pueden añadirse directamente a sus controladores y modelos para proporcionar información adicional sobre el comportamiento y las estructuras de datos de la API.

Ejemplo: Anotaciones personalizadas

using Microsoft.AspNetCore.Mvc;

namespace WebApplication8.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")] 
        [SwaggerOperation(Summary = "Gets the weather forecast for the next 5 days")]
        [SwaggerResponse(200, "Successfully retrieved weather forecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}
using Microsoft.AspNetCore.Mvc;

namespace WebApplication8.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")] 
        [SwaggerOperation(Summary = "Gets the weather forecast for the next 5 days")]
        [SwaggerResponse(200, "Successfully retrieved weather forecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}
Imports Microsoft.AspNetCore.Mvc

Namespace WebApplication8.Controllers
	<ApiController>
	<Route("[controller]")>
	Public Class WeatherForecastController
		Inherits ControllerBase

		Private Shared ReadOnly Summaries() As String = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }

		Private ReadOnly _logger As ILogger(Of WeatherForecastController)

		Public Sub New(ByVal logger As ILogger(Of WeatherForecastController))
			_logger = logger
		End Sub

		<HttpGet(Name := "GetWeatherForecast")>
		<SwaggerOperation(Summary := "Gets the weather forecast for the next 5 days")>
		<SwaggerResponse(200, "Successfully retrieved weather forecast")>
		Public Function [Get]() As IEnumerable(Of WeatherForecast)
			Return Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
				.Date = DateTime.Now.AddDays(index),
				.TemperatureC = Random.Shared.Next(-20, 55),
				.Summary = Summaries(Random.Shared.Next(Summaries.Length))
			}).ToArray()
		End Function
	End Class
End Namespace
VB   C#

En este ejemplo, los atributos SwaggerOperation y SwaggerResponse se utilizan para proporcionar descripciones OpenAPI detalladas y códigos de respuesta para el endpoint.

Salida

OpenAPI .NET (Cómo funciona para los desarrolladores): Figura 1 - Salida de anotaciones personalizadas

Haga clic en el botón Ejecutar y obtendrá la siguiente respuesta.

OpenAPI .NET (Cómo funciona para los desarrolladores): Figura 2 - Salida de respuesta

IronPDF

IronPDF for .NET es una potente herramienta que permite generar y manipular sin problemas documentos PDF dentro de aplicaciones ASP.NET. Gracias a su intuitiva API y su sólida funcionalidad, los desarrolladores pueden integrar sin esfuerzo la generación de PDF en sus proyectos web, ofreciendo a los usuarios una mayor capacidad de gestión de documentos. Ya se trate de crear PDF desde cero, convertir contenido HTML a PDF o añadir elementos dinámicos como imágenes y texto, IronPDF simplifica el proceso, garantizando una generación de documentos eficaz y profesional.

Pasos para instalar utilizando NuGet Package Manager:

  1. Abra su proyecto ASP.NET en Visual Studio y vaya al menú "Herramientas".

  2. Seleccione "NuGet Package Manager" y, a continuación, haga clic en "Manage NuGet Packages for Solution"

  3. En la pestaña "Examinar", busque "IronPDF" y seleccione la versión deseada. Haga clic en "Instalar" para añadir el paquete a su proyecto. IronPDF y sus dependencias se descargarán e integrarán automáticamente, lo que le permitirá empezar a aprovechar su funcionalidad en su aplicación ASP.NET sin problemas.

    OpenAPI .NET (Cómo funciona para los desarrolladores): Figura 3 - IronPDF

Obtener un archivo PDF como respuesta a una llamada API

Añada el siguiente código a su archivo controlador, utiliza IronPDF para crear un archivo PDF y devolver un archivo PDF a la llamada API.

using Microsoft.AspNetCore.Mvc;
using IronPdf;

namespace WebApplication8.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IActionResult GetWeatherForecastPdf()
        {
            var htmlContent = @"
        <html>
        <head>
            <title>Weather Forecast</title>
        </head>
        <body>
            <h1>Weather Forecast</h1>
            <table>
                <tr>
                    <th>Date</th>
                    <th>Temperature (Celsius)</th>
                    <th>Summary</th>
                </tr>";

            var forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            });

            foreach (var forecast in forecasts)
            {
                htmlContent += $@"
            <tr>
                <td>{forecast.Date.ToShortDateString()}</td>
                <td>{forecast.TemperatureC}</td>
                <td>{forecast.Summary}</td>
            </tr>";
            }

            htmlContent += @"
            </table>
        </body>
        </html>";

            // Convert HTML to PDF
            var renderer = new ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

            // Return PDF file
            var pdfBytes = pdfDocument.BinaryData;
            return File(pdfBytes, "application/pdf", "WeatherForecast.pdf");
        }
    }
}
using Microsoft.AspNetCore.Mvc;
using IronPdf;

namespace WebApplication8.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IActionResult GetWeatherForecastPdf()
        {
            var htmlContent = @"
        <html>
        <head>
            <title>Weather Forecast</title>
        </head>
        <body>
            <h1>Weather Forecast</h1>
            <table>
                <tr>
                    <th>Date</th>
                    <th>Temperature (Celsius)</th>
                    <th>Summary</th>
                </tr>";

            var forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            });

            foreach (var forecast in forecasts)
            {
                htmlContent += $@"
            <tr>
                <td>{forecast.Date.ToShortDateString()}</td>
                <td>{forecast.TemperatureC}</td>
                <td>{forecast.Summary}</td>
            </tr>";
            }

            htmlContent += @"
            </table>
        </body>
        </html>";

            // Convert HTML to PDF
            var renderer = new ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);

            // Return PDF file
            var pdfBytes = pdfDocument.BinaryData;
            return File(pdfBytes, "application/pdf", "WeatherForecast.pdf");
        }
    }
}
Imports Microsoft.AspNetCore.Mvc
Imports IronPdf

Namespace WebApplication8.Controllers
	<ApiController>
	<Route("[controller]")>
	Public Class WeatherForecastController
		Inherits ControllerBase

		Private Shared ReadOnly Summaries() As String = { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }

		Private ReadOnly _logger As ILogger(Of WeatherForecastController)

		Public Sub New(ByVal logger As ILogger(Of WeatherForecastController))
			_logger = logger
		End Sub

		<HttpGet(Name := "GetWeatherForecast")>
		Public Function GetWeatherForecastPdf() As IActionResult
			Dim htmlContent = "
        <html>
        <head>
            <title>Weather Forecast</title>
        </head>
        <body>
            <h1>Weather Forecast</h1>
            <table>
                <tr>
                    <th>Date</th>
                    <th>Temperature (Celsius)</th>
                    <th>Summary</th>
                </tr>"

			Dim forecasts = Enumerable.Range(1, 5).Select(Function(index) New WeatherForecast With {
				.Date = DateTime.Now.AddDays(index),
				.TemperatureC = Random.Shared.Next(-20, 55),
				.Summary = Summaries(Random.Shared.Next(Summaries.Length))
			})

			For Each forecast In forecasts
				htmlContent &= $"
            <tr>
                <td>{forecast.Date.ToShortDateString()}</td>
                <td>{forecast.TemperatureC}</td>
                <td>{forecast.Summary}</td>
            </tr>"
			Next forecast

			htmlContent &= "
            </table>
        </body>
        </html>"

			' Convert HTML to PDF
			Dim renderer = New ChromePdfRenderer()
			Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

			' Return PDF file
			Dim pdfBytes = pdfDocument.BinaryData
			Return File(pdfBytes, "application/pdf", "WeatherForecast.pdf")
		End Function
	End Class
End Namespace
VB   C#

OpenAPI .NET (Cómo funciona para los desarrolladores): Figura 4 - Salida de la API

Descargue y abra el archivo PDF adjunto.

OpenAPI .NET (Cómo funciona para los desarrolladores): Figura 5 - Salida PDF

Conclusión

OpenAPI, antes conocido como Swagger, agiliza el diseño y la documentación de API RESTful en el ecosistema .NET a través de bibliotecas como Swashbuckle, facilitando la generación automática de documentación de API para proyectos ASP.NET Core. Demostrando la sinergia entre OpenAPI e IronPDF, mostramos cómo utilizar las capacidades de IronPDF para generar archivos PDF a partir de contenido HTML y devolverlos como respuestas API, enriqueciendo la funcionalidad de las aplicaciones ASP.NET. Al adoptar los estándares OpenAPI y aprovechar las sólidas funciones de IronPDF, los desarrolladores pueden mejorar sus prácticas de documentación de API y ofrecer a los usuarios aplicaciones pulidas y repletas de funciones.

Para obtener información detallada sobre las licencias de IronPDF, consulte la página de licencias de IronPDF. Además, puede explorar nuestro tutorial en profundidad sobre la conversión de HTML a PDF para obtener más orientación.

< ANTERIOR
Humanizer C# (Cómo funciona para desarrolladores)
SIGUIENTE >
Microsoft.Extensions.Caching.Memory Ejemplo (Con PDF) en C#

¿Listo para empezar? Versión: 2024.9 acaba de salir

Descarga gratuita de NuGet Descargas totales: 10,516,730 View Licenses >