
OpenAPI .NET (Cómo Funciona para Desarrolladores)
OpenAPI, anteriormente conocido como Swagger, es una especificación para construir y describir APIs RESTful. Permite a los desarrolladores definir la estructura de sus APIs en un formato estandarizado, habilitando diversas herramientas y servicios para entender e interactuar con la API REST de manera efectiva 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 hacen que sea más fácil crear, documentar y consumir APIs.
En este artículo, aprenderemos sobre las especificaciones de soporte de OpenAPI y cómo crear un archivo PDF utilizando IronPDF y devolverlo como respuesta a una llamada API.
Cómo configurar OpenAPI en .NET
Para comenzar con el proyecto OpenAPI .NET, normalmente se usa la biblioteca Swashbuckle, que genera especificaciones o documentación OpenAPI para tus APIs de ASP.NET Core.
Paso 1: Instalar Swashbuckle
Primero, necesitas instalar el paquete Swashbuckle.AspNetCore a través de NuGet en Visual Studio. Puede hacer esto usando la Consola del Administrador de Paquetes NuGet:
O usando la CLI de .NET:
dotnet add package Swashbuckle.AspNetCore
Paso 2: Configurar Swashbuckle
A continuación, necesitas configurar Swashbuckle en tu proyecto ASP.NET Core. Esto implica actualizar el archivo Program.cs para añadir servicios Swagger y configurar el middleware de Swagger.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Configures Swagger/OpenAPI descriptions.
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()
' Configures Swagger/OpenAPI descriptions.
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()Generación y visualización de documentación de API
Una vez configurado Swashbuckle, ejecutar tu aplicación generará automáticamente documentación OpenAPI. Puedes ver estas descripciones OpenAPI navegando a la interfaz de usuario de Swagger.
Uso de las definiciones OpenAPI
Las definiciones OpenAPI son herramientas poderosas que se pueden usar para generar SDKs de cliente, probar APIs y asegurar la consistencia entre diferentes servicios. La especificación OpenAPI define una interfaz estándar e independiente de lenguaje para APIs, la cual permite tanto a humanos como a computadoras entender las capacidades de un servicio sin acceso al código fuente.
Ampliación de OpenAPI con anotaciones personalizadas
Swashbuckle te permite mejorar tu documentación OpenAPI con anotaciones personalizadas. Estas anotaciones se pueden agregar directamente a tus controladores y modelos para proporcionar información adicional sobre el comportamiento del API y las estructuras de datos.
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();
}
}
}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 NamespaceEn este ejemplo, los atributos SwaggerOperation y SwaggerResponse se utilizan para proporcionar descripciones detalladas de OpenAPI y códigos de respuesta para el endpoint.
Producción

Haz clic en el botón Ejecutar, y obtendrás la siguiente respuesta.

IronPDF
IronPDF para ASP.NET es una herramienta poderosa que permite la generación y manipulación sin problemas de documentos PDF dentro de aplicaciones ASP.NET. Con su API intuitiva y funcionalidad robusta, los desarrolladores pueden integrar sin esfuerzo la generación de PDF en sus proyectos web, ofreciendo capacidades mejoradas de gestión de documentos a los usuarios. Ya sea creando PDFs desde cero, convirtiendo contenido HTML a PDF, o agregando elementos dinámicos como imágenes y texto, IronPDF simplifica el proceso, asegurando una generación eficiente y profesional de documentos.
Pasos para instalar usando el Administrador de Paquetes NuGet:
- Abre tu proyecto ASP.NET en Visual Studio y navega al menú "Herramientas".
- Selecciona "Administrador de Paquetes NuGet" y luego haz clic en "Administrar Paquetes NuGet para la Solución".
- En la pestaña "Explorar", busca "IronPDF" y selecciona la versión deseada. Haz clic en "Instalar" para agregar el paquete a tu proyecto. IronPDF y sus dependencias se descargarán e integrarán automáticamente, permitiéndote comenzar a aprovechar su funcionalidad en tu aplicación ASP.NET sin problemas.

Obtener un archivo PDF en respuesta a una llamada API
Agrega el siguiente código a tu archivo de controlador, el cual utiliza IronPDF para crear un archivo PDF y devolverlo como respuesta 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)]
});
// Iterate over the forecasts and add data to the HTML string
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 the HTML string to a PDF using IronPDF
var renderer = new ChromePdfRenderer();
var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
// Retrieve the byte array of the generated PDF
var pdfBytes = pdfDocument.BinaryData;
// Return the PDF file to the client
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))
})
' Iterate over the forecasts and add data to the HTML string
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 the HTML string to a PDF using IronPDF
Dim renderer = New ChromePdfRenderer()
Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
' Retrieve the byte array of the generated PDF
Dim pdfBytes = pdfDocument.BinaryData
' Return the PDF file to the client
Return File(pdfBytes, "application/pdf", "WeatherForecast.pdf")
End Function
End Class
End Namespace
Descarga y abre el archivo PDF adjunto.

Conclusión
OpenAPI, anteriormente conocido como Swagger, agiliza el diseño y la documentación de APIs 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 de API, enriqueciendo la funcionalidad de las aplicaciones ASP.NET. Al adoptar los estándares OpenAPI y aprovechar las características robustas de IronPDF, los desarrolladores pueden mejorar sus prácticas de documentación de API y ofrecer aplicaciones pulidas y ricas en características a los usuarios.
Para información detallada sobre licencias de IronPDF, por favor consulta los detalles de licenciamiento de IronPDF. Además, puedes explorar nuestro tutorial de conversión de HTML a PDF para más orientación.

Jacob Mellor es Director de Tecnología de Iron Software y un ingeniero visionario pionero en la tecnología C# PDF. Como desarrollador original de la base de código principal de Iron Software, ha dado forma a la arquitectura de productos de la empresa desde su creación, transformándola, junto con el director ejecutivo Cameron Rimington, en una empresa de más de 50 personas que presta servicios a la NASA, Tesla y organismos gubernamentales de todo el mundo.
Artículos Relacionados


