
GraphQL C# (개발자에게 어떻게 작동하는가)
GraphQL은 유연하고 효율적인 웹 서비스를 구축하는 RESTful API의 대안으로 상당한 인기를 얻고 있습니다. GraphQL은 Java, Python, ASP .NET core와 같은 다양한 언어로 제공됩니다. 하지만 이 기사에서는 C#의 맥락에서 GraphQL을 사용하는 방법을 탐구하고 그 개념, 구현 및 실제 예제를 사용한 사용법을 살펴볼 것입니다. 또한, C#용 IronPDF를 사용하여 GraphQL 스키마 정의 쿼리 클래스를 통해 PDF 파일을 생성할 것입니다.
GraphQL이란 무엇인가?
GraphQL은 클라이언트가 필요한 정확한 데이터를 요청할 수 있는 API용 쿼리 언어입니다. 여러 Endpoint가 고정된 데이터 구조를 반환할 수 있는 RESTful API와 달리, GraphQL 서비스는 클라이언트가 필요로 하는 데이터의 모양을 지정할 수 있게 하여 더 효율적이고 유연합니다.
Setting up GraphQL in C#
C# 프로젝트에서 GraphQL을 사용하려면 .NET용 인기 있는 GraphQL Endpoint 서버 구현인 HotChocolate 라이브러리가 필요합니다.
먼저 Hot Chocolate NuGet 패키지를 설치하세요:
GraphQL 스키마 생성하기
GraphQL 스키마는 API에서 사용할 수 있는 데이터 유형과 연산을 정의합니다. 다음은 블로그 애플리케이션을 위한 스키마 우선 구현의 간단한 예제입니다:
using HotChocolate.Types;
public class QueryType : ObjectType
{
protected override void Configure(IObjectTypeDescriptor descriptor)
{
descriptor.Field("helloWorld")
.Type<StringType>()
.Resolve(context => "Hello, GraphQL!");
}
}Imports HotChocolate.Types
Public Class QueryType
Inherits ObjectType
Protected Overrides Sub Configure(ByVal descriptor As IObjectTypeDescriptor)
descriptor.Field("helloWorld").Type(Of StringType)().Resolve(Function(context) "Hello, GraphQL!")
End Sub
End Class이 예제에서는 질문할 때 문자열 "Hello, GraphQL!"을 반환하는 helloWorld 필드를 정의합니다.
GraphQL 서버 생성하기
다음으로, ASP.NET Core를 사용하여 GraphQL 서버를 설정하세요:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddGraphQLServer()
.AddQueryType<QueryType>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGraphQL();
});
}
}Imports Microsoft.AspNetCore.Builder
Imports Microsoft.AspNetCore.Hosting
Imports Microsoft.Extensions.DependencyInjection
Public Class Startup
Public Sub ConfigureServices(ByVal services As IServiceCollection)
services.AddGraphQLServer().AddQueryType(Of QueryType)()
End Sub
Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment)
app.UseRouting()
app.UseEndpoints(Sub(endpoints)
endpoints.MapGraphQL()
End Sub)
End Sub
End ClassQuerying GraphQL from C#
이제, C# 클라이언트에서 GraphQL.Client NuGet 패키지를 사용하여 이 GraphQL API를 쿼리하는 방법을 살펴봅시다:
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;
using System;
using System.Threading.Tasks;
// GraphQL query class to interact with the API
public class Query
{
public static async Task Main()
{
// Set up the GraphQL client
using var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions
{
EndPoint = new Uri("http://localhost:5000/graphql") // GraphQL endpoint
}, new NewtonsoftJsonSerializer());
// Define the GraphQL query
var request = new GraphQLRequest
{
Query = @"
{
helloWorld
}"
};
var response = await graphQLClient.SendQueryAsync<dynamic>(request);
// Print the response from the GraphQL server
Console.WriteLine((string)response.Data.helloWorld);
}
}'INSTANT VB NOTE: 'Option Strict Off' is used here since dynamic typing is used:
Option Strict Off
Imports GraphQL.Client.Http
Imports GraphQL.Client.Serializer.Newtonsoft
Imports System
Imports System.Threading.Tasks
' GraphQL query class to interact with the API
Public Class Query
Public Shared Async Function Main() As Task
' Set up the GraphQL client
Dim graphQLClient = New GraphQLHttpClient(New GraphQLHttpClientOptions With {.EndPoint = New Uri("http://localhost:5000/graphql")}, New NewtonsoftJsonSerializer())
' Define the GraphQL query
Dim request = New GraphQLRequest With {.Query = "
{
helloWorld
}"}
'INSTANT VB NOTE: In the following line, Instant VB substituted 'Object' for 'dynamic' - this will work in VB with Option Strict Off:
Dim response = Await graphQLClient.SendQueryAsync(Of Object)(request)
' Print the response from the GraphQL server
Console.WriteLine(CStr(response.Data.helloWorld))
End Function
End ClassGraphQL C#은 API를 설계하는 데 강력하고 유연한 방법을 제공하며, HotChocolate 같은 라이브러리로 C# 애플리케이션에 GraphQL 백엔드를 통합하는 것이 간편해집니다. 스키마를 정의하고 서버를 설정함으로써 GraphQL API를 통해 데이터를 노출하고 C# 클라이언트에서 효율적으로 쿼리할 수 있습니다.
산출

Intro to IronPDF in C#
IronPDF는 PDF 문서를 손쉽게 생성, 편집 및 조작할 수 있는 다재다능한 C# 라이브러리입니다. 이 섹션에서는 IronPDF를 소개하고 GraphQL과 결합하여 동적 PDF 보고서를 생성하는 방법을 보여드리겠습니다.
IronPDF는 HTML to PDF 기능을 통해 모든 레이아웃 및 스타일을 보존하는 데 탁월합니다. 웹 콘텐츠에서 PDF를 생성할 수 있어 보고서, 청구서 및 문서 작성에 적합합니다. HTML 파일, URL, HTML 문자열은 무리 없이 PDF로 변환할 수 있습니다.
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End ClassIronPDF 설치 중
IronPDF를 시작하려면 NuGet 패키지를 설치하세요:
IronPDF를 사용하여 GraphQL 데이터로 PDF 생성하기
GraphQL API에서 사용자 데이터를 가져와 형식화된 방식으로 표시하는 PDF 보고서를 만들어 보겠습니다.
예제
using IronPdf;
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;
using System;
using System.Threading.Tasks;
public class PdfGenerator
{
public async Task GeneratePdfAsync()
{
// Initialize GraphQL client
var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions
{
EndPoint = new Uri("http://localhost:5000/graphql")
}, new NewtonsoftJsonSerializer());
// Define GraphQL query
var query = new GraphQLRequest
{
Query = @"
{
helloWorld
}"
};
var response = await graphQLClient.SendQueryAsync<dynamic>(query);
var helloMessage = response.Data.helloWorld.ToString();
// Create HTML content for the PDF
var htmlContent = $@"
<html>
<head><title>GraphQL Report</title></head>
<body>
<h1>GraphQL Report</h1>
<p>{helloMessage}</p>
</body>
</html>";
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("GraphQLReport.pdf");
}
}'INSTANT VB NOTE: 'Option Strict Off' is used here since dynamic typing is used:
Option Strict Off
Imports IronPdf
Imports GraphQL.Client.Http
Imports GraphQL.Client.Serializer.Newtonsoft
Imports System
Imports System.Threading.Tasks
Public Class PdfGenerator
Public Async Function GeneratePdfAsync() As Task
' Initialize GraphQL client
Dim graphQLClient = New GraphQLHttpClient(New GraphQLHttpClientOptions With {.EndPoint = New Uri("http://localhost:5000/graphql")}, New NewtonsoftJsonSerializer())
' Define GraphQL query
Dim query As New GraphQLRequest With {.Query = "
{
helloWorld
}"}
'INSTANT VB NOTE: In the following line, Instant VB substituted 'Object' for 'dynamic' - this will work in VB with Option Strict Off:
Dim response = Await graphQLClient.SendQueryAsync(Of Object)(query)
Dim helloMessage = response.Data.helloWorld.ToString()
' Create HTML content for the PDF
Dim htmlContent = $"
<html>
<head><title>GraphQL Report</title></head>
<body>
<h1>GraphQL Report</h1>
<p>{helloMessage}</p>
</body>
</html>"
Dim renderer = New ChromePdfRenderer()
Dim pdf = renderer.RenderHtmlAsPdf(htmlContent)
pdf.SaveAs("GraphQLReport.pdf")
End Function
End Class이 예제에서는 GraphQL 클라이언트를 사용하여 GraphQL API에서 helloWorld 메시지를 가져옵니다. 그런 다음, 이 메시지를 포함한 HTML 템플릿을 구성하고 IronPDF의 ChromePdfRenderer을 사용하여 이 HTML을 PDF 파일로 변환합니다.
산출

결론
GraphQL은 API 개발에서 기존의 RESTful API에 비해 데이터를 더 유연하고 효율적으로 쿼리하고 조작할 수 있는 방법을 제공하여 게임체인저로 부상했습니다. 클라이언트가 필요로 하는 타입의 쿼리 데이터만 요청할 수 있는 기능은 성능과 유연성이 중요한 현대 웹 애플리케이션에 특히 매력적입니다.
또한, IronPDF와 같은 도구 및 패키지와 GraphQL을 결합하면 동적이며 데이터 중심의 PDF 보고서를 생성할 수 있는 흥미로운 가능성을 열어줍니다. 청구서를 만들든, 보고서를 생성하든, 기타 문서를 제작하든, C#에서 IronPDF와 GraphQL을 통합하면 PDF 생성을 자동화할 수 있는 강력하고 효율적인 방법을 제공합니다.
요약하자면, GraphQL과 C#은 현대적이고 유연하며 효율적인 웹 애플리케이션을 구축하기 위한 강력한 조합입니다. HotChocolate, GraphQL.Client 및 IronPDF와 같은 라이브러리를 사용하면 개발자는 오늘날의 디지털 환경의 요구를 충족하는 강력하고 데이터 중심의 애플리케이션을 구축하기 위해 필요한 모든 도구를 갖추게 됩니다.
HTML to PDF 튜토리얼은 사용자가 사용할 수 있는 다음 IronPDF Licensing Guide에서 확인할 수 있습니다.

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.
관련 기사


