Saltar al pie de página
.NET AYUDA

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 mediante NuGet en Visual Studio. Puede hacer esto usando la Consola del Administrador de Paquetes NuGet:

Install-Package Swashbuckle.AspNetCore

O usando la CLI de .NET:

dotnet add package Swashbuckle.AspNetCore
dotnet add package Swashbuckle.AspNetCore
SHELL

Paso 2: Configurar Swashbuckle

A continuación, necesitas configurar Swashbuckle en tu proyecto ASP.NET Core. Esto implica actualizar el archivo Program.cs para agregar servicios Swagger y configurar el middleware 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();
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()
$vbLabelText   $csharpLabel

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();
        }
    }
}
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
$vbLabelText   $csharpLabel

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

Producción

OpenAPI .NET (Cómo Funcionan Para Desarrolladores): Figura 1 - Salida de Anotaciones Personalizadas

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

OpenAPI .NET (Cómo Funcionan Para Desarrolladores): Figura 2 - Salida de Respuesta

HierroPDF

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:

  1. Abre tu proyecto ASP.NET en Visual Studio y navega al menú "Herramientas".
  2. Selecciona "Administrador de Paquetes NuGet" y luego haz clic en "Administrar Paquetes NuGet para la Solución".
  3. 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.

OpenAPI .NET (Cómo Funcionan Para Desarrolladores): Figura 3 - IronPDF

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");
        }
    }
}
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
$vbLabelText   $csharpLabel

OpenAPI .NET (Cómo Funcionan Para Desarrolladores): Figura 4 - Salida de API

Descarga y abre el archivo PDF adjunto.

OpenAPI .NET (Cómo Funcionan Para Desarrolladores): Figura 5 - Salida de PDF

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.

Preguntas Frecuentes

¿Cómo puedo convertir contenido HTML a PDF en una aplicación ASP.NET?

Puede usar IronPDF en una aplicación ASP.NET para convertir contenido HTML a PDF. Al aprovechar las capacidades de IronPDF, puede renderizar cadenas o archivos HTML en documentos PDF, que luego pueden ser servidos como respuestas de API o guardados para fines de gestión de documentos.

¿Cuál es el papel de OpenAPI en el ecosistema .NET?

OpenAPI juega un papel crucial en el ecosistema .NET al proporcionar una forma estandarizada de definir y documentar APIs RESTful. Esta integración a menudo se facilita a través de herramientas como Swashbuckle, que ayuda a generar especificaciones OpenAPI y habilita el consumo fácil de APIs dentro de proyectos ASP.NET Core.

¿Cómo configuro Swagger UI en un proyecto .NET usando Swashbuckle?

Para configurar Swagger UI en un proyecto .NET usando Swashbuckle, instale el paquete Swashbuckle.AspNetCore a través de NuGet. Luego, configure los servicios Swagger en su archivo Program.cs y configure el middleware de Swagger para habilitar la generación automática y el acceso a la documentación de API a través de Swagger UI.

¿Cómo puedo generar SDKs de cliente a partir de definiciones OpenAPI en .NET?

Las definiciones OpenAPI pueden usarse para generar SDKs de cliente, que facilitan el consumo de APIs al abstraer la complejidad de las llamadas se API. En .NET, herramientas como Swashbuckle pueden generar estas definiciones, que luego pueden usarse con herramientas como AutoRest para crear SDKs de cliente en diversos lenguajes de programación.

¿Cuáles son las ventajas de usar anotaciones personalizadas en la documentación OpenAPI?

Las anotaciones personalizadas en la documentación OpenAPI mejoran la claridad y el detalle de las especificaciones de API. En .NET, Swashbuckle le permite usar atributos como SwaggerOperation y SwaggerResponse para agregar descripciones y códigos de respuesta, haciendo la documentación de la API más informativa y fácil de entender para los desarrolladores.

¿Cómo puedo entregar un archivo PDF como respuesta de API en ASP.NET Core?

Puede entregar un archivo PDF como respuesta de API en ASP.NET Core usando IronPDF. Genere el PDF a partir de contenido HTML usando los métodos de renderizado de IronPDF y devuelva el archivo PDF en su acción de controlador API usando IActionResult de ASP.NET Core para enviar el archivo como parte de la respuesta.

¿Qué beneficios trae la combinación de OpenAPI y herramientas de generación de PDF a las aplicaciones ASP.NET?

La combinación de OpenAPI y herramientas de generación de PDF como IronPDF en aplicaciones ASP.NET proporciona una documentación de API integral y mejora la funcionalidad al permitir que las APIs devuelvan documentos PDF profesionales. Esta integración apoya la gestión eficiente de documentos y enriquece las capacidades generales de la aplicación.

Jacob Mellor, Director de Tecnología @ Team Iron
Director de Tecnología

Jacob Mellor es Director de Tecnología en Iron Software y un ingeniero visionario que lidera la tecnología PDF en C#. Como el desarrollador original detrás de la base de código central de Iron Software, ha moldeado la arquitectura de productos de la compañía desde ...

Leer más