푸터 콘텐츠로 바로가기
.NET 도움말

OpenAPI .NET (How It Works For Developers)

OpenAPI, formerly known as Swagger, is a specification for building and describing RESTful APIs. It allows developers to define the structure of their APIs in a standardized format, enabling various tools and services to understand and interact with the REST API effectively and provide feedback. In the .NET ecosystem, OpenAPI .NET integration is facilitated through several libraries and tools that make it easier to create, document, and consume APIs.

In this article, we will learn about OpenAPI support specifications and how to create a PDF file using IronPDF and return it as an API call response.

Setting Up OpenAPI in .NET

To get started with the OpenAPI .NET project, you typically use the Swashbuckle library, which generates OpenAPI specification or documentation for your ASP.NET Core APIs.

Step 1: Install Swashbuckle

First, you need to install the Swashbuckle.AspNetCore package via NuGet in Visual Studio. You can do this using the NuGet Package Manager Console:

Install-Package Swashbuckle.AspNetCore

Or by using the .NET CLI:

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

Step 2: Configure Swashbuckle

Next, you need to configure Swashbuckle in your ASP.NET Core project. This involves updating the Program.cs file to add Swagger services and configure the Swagger middleware.

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

Generating and Viewing API Documentation

Once Swashbuckle is configured, running your application will automatically generate OpenAPI documentation. You can view these OpenAPI descriptions by navigating to the Swagger UI interface.

Using OpenAPI Definitions

OpenAPI definitions are powerful tools that can be used for generating client SDKs, testing APIs, and ensuring consistency across different services. The OpenAPI specification defines a standard, language-agnostic interface to APIs, which allows both humans and computers to understand the capabilities of a service without access to the source code.

Extending OpenAPI with Custom Annotations

Swashbuckle allows you to enhance your OpenAPI documentation with custom annotations. These annotations can be added directly to your controllers and models to provide additional information about the API's behavior and data structures.

Example: Custom Annotations

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

In this example, the SwaggerOperation and SwaggerResponse attributes are used to provide detailed OpenAPI descriptions and response codes for the endpoint.

Output

OpenAPI .NET (How It Works For Developers): Figure 1 - Custom Annotations Output

Click on the Execute button, and you will get the following response.

OpenAPI .NET (How It Works For Developers): Figure 2 - Response Output

IronPDF

IronPDF for ASP.NET is a powerful tool that enables seamless generation and manipulation of PDF documents within ASP.NET applications. With its intuitive API and robust functionality, developers can effortlessly integrate PDF generation into their web projects, offering enhanced document management capabilities to users. Whether it's creating PDFs from scratch, converting HTML content to PDF, or adding dynamic elements like images and text, IronPDF simplifies the process, ensuring efficient and professional document generation.

Steps to install using NuGet Package Manager:

  1. Open your ASP.NET project in Visual Studio and navigate to the "Tools" menu.
  2. Select "NuGet Package Manager" and then click on "Manage NuGet Packages for Solution."
  3. In the "Browse" tab, search for "IronPDF" and select the desired version. Click on "Install" to add the package to your project. IronPDF and its dependencies will be automatically downloaded and integrated, allowing you to start leveraging its functionality in your ASP.NET application seamlessly.

OpenAPI .NET (How It Works For Developers): Figure 3 - IronPDF

Get PDF File in Response to API Call

Add the following code to your controller file, it uses IronPDF to create a PDF file and return it as a response to the API call.

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

OpenAPI .NET (How It Works For Developers): Figure 4 - API Output

Download and open the attached PDF file.

OpenAPI .NET (How It Works For Developers): Figure 5 - PDF Output

Conclusion

OpenAPI, formerly known as Swagger, streamlines RESTful API design and documentation in the .NET ecosystem through libraries like Swashbuckle, facilitating automatic API documentation generation for ASP.NET Core projects. Demonstrating the synergy between OpenAPI and IronPDF, we showcased how to utilize IronPDF's capabilities to generate PDF files from HTML content and return them as API responses, enriching the functionality of ASP.NET applications. By embracing OpenAPI standards and leveraging IronPDF's robust features, developers can enhance their API documentation practices and deliver polished, feature-rich applications to users.

For detailed information on IronPDF licensing, please refer to the IronPDF licensing details. Additionally, you can explore our HTML to PDF conversion tutorial for further guidance.

자주 묻는 질문

ASP.NET 애플리케이션에서 HTML 콘텐츠를 PDF로 변환하려면 어떻게 해야 하나요?

ASP.NET 애플리케이션에서 IronPDF를 사용하여 HTML 콘텐츠를 PDF로 변환할 수 있습니다. IronPDF의 기능을 활용하여 HTML 문자열 또는 파일을 PDF 문서로 렌더링한 다음 API 응답으로 제공하거나 문서 관리 목적으로 저장할 수 있습니다.

.NET 생태계에서 OpenAPI는 어떤 역할을 하나요?

OpenAPI는 RESTful API를 정의하고 문서화하는 표준화된 방법을 제공함으로써 .NET 생태계에서 중요한 역할을 합니다. 이러한 통합은 OpenAPI 사양을 생성하고 ASP.NET Core 프로젝트 내에서 API를 쉽게 사용할 수 있도록 지원하는 Swashbuckle과 같은 도구를 통해 촉진되는 경우가 많습니다.

스와시버클을 사용하여 .NET 프로젝트에서 Swagger UI를 설정하려면 어떻게 해야 하나요?

스와시버클을 사용하여 .NET 프로젝트에서 스와거 UI를 설정하려면 NuGet을 통해 Swashbuckle.AspNetCore 패키지를 설치합니다. 그런 다음 Program.cs 파일에서 Swagger 서비스를 구성하고 Swagger UI를 통해 API 문서를 자동으로 생성하고 액세스할 수 있도록 Swagger 미들웨어를 설정합니다.

.NET의 OpenAPI 정의에서 클라이언트 SDK를 생성하려면 어떻게 해야 하나요?

OpenAPI 정의는 API 호출의 복잡성을 추상화하여 API 사용을 용이하게 하는 클라이언트 SDK를 생성하는 데 사용할 수 있습니다. .NET에서는 스와시버클과 같은 도구로 이러한 정의를 생성할 수 있으며, 이를 AutoRest와 같은 도구와 함께 사용하여 다양한 프로그래밍 언어로 클라이언트 SDK를 만들 수 있습니다.

OpenAPI 문서에서 사용자 지정 주석을 사용하면 어떤 이점이 있나요?

OpenAPI 문서의 사용자 지정 주석은 API 사양의 명확성과 세부 사항을 향상시킵니다. .NET에서는 스와시버클을 사용하면 SwaggerOperationSwaggerResponse와 같은 속성을 사용하여 설명 및 응답 코드를 추가할 수 있으므로 개발자가 API 문서를 더욱 유익하고 이해하기 쉽게 만들 수 있습니다.

ASP.NET Core에서 PDF 파일을 API 응답으로 전달하려면 어떻게 해야 하나요?

IronPDF를 사용하여 ASP.NET Core에서 PDF 파일을 API 응답으로 전달할 수 있습니다. IronPDF의 렌더링 메서드를 사용하여 HTML 콘텐츠에서 PDF를 생성하고, ASP.NET Core의 IActionResult를 사용하여 API 컨트롤러 액션에서 PDF 파일을 반환하여 파일을 응답의 일부로 출력합니다.

OpenAPI와 PDF 생성 도구를 결합하면 ASP.NET 애플리케이션에 어떤 이점이 있을까요?

ASP.NET 애플리케이션에서 OpenAPI와 IronPDF와 같은 PDF 생성 도구를 결합하면 포괄적인 API 문서를 제공하고 API가 전문적인 PDF 문서를 반환할 수 있도록 하여 기능을 향상시킬 수 있습니다. 이러한 통합은 효율적인 문서 관리를 지원하고 애플리케이션의 전반적인 기능을 강화합니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.