フッターコンテンツにスキップ
.NETヘルプ

GraphQL C#(開発者向けの動作方法)

GraphQL は柔軟性と効率性を備えたWebサービスを構築するためのRESTful APIの代替として大きな人気を得ています。 GraphQLは、Java、Python、ASP .NETコアなど、様々な言語で利用可能です。 しかし、この記事ではC#の文脈でGraphQLを使用する方法を掘り下げ、その概念、実装、使用方法を実用的な例と共に探ります。 また、GraphQLスキーマ定義のクエリクラスを使用してPDFファイルを作成するためにC#のIronPDFを使用します。

GraphQLとは何ですか?

GraphQLは、クライアントが必要なデータだけを要求できるAPIのためのクエリ言語です。 複数のエンドポイントが固定データ構造を返す可能性のあるRESTful APIとは異なり、GraphQLサービスではクライアントが必要なデータの形状を指定できるため、より効率的で柔軟です。

C&#でのGraphQLのセットアップ

C#プロジェクトでGraphQLを使用するには、.NET用の人気のあるGraphQLエンドポイントサーバー実装であるHotChocolateライブラリが必要です。

まず、Hot ChocolateのNuGetパッケージをインストールします:

Install-Package HotChocolate.AspNetCore

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

この例では、クエリされたときに文字列"Hello, GraphQL!"を返すhelloWorldフィールドを定義します。

GraphQLサーバーの作成

次に、ASP.NETコアを使用して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();
        });
    }
}
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 Class
$vbLabelText   $csharpLabel

C&#からのGraphQLのクエリ

GraphQL.Client NuGetパッケージを使用して、C#クライアントからこの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);
    }
}
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 Class
$vbLabelText   $csharpLabel

GraphQL C#は、APIを設計するための強力で柔軟な方法を提供し、HotChocolateのようなライブラリを使用することで、C#アプリケーションにGraphQLバックエンドを統合することが容易になります。 スキーマを定義し、サーバーをセットアップすることで、データをGraphQL APIを通じて公開し、C#クライアントから効率的にクエリを行うことができます。

出力

GraphQL C# (開発者のための動作方法): 図 1 - 前のコードからのコンソール出力

C&#におけるIronPDFの入門

IronPDFは、PDFドキュメントを簡単に作成、編集、操作できる多用途なC#ライブラリです。 このセクションでは、IronPDFの導入と、GraphQLと組み合わせて動的なPDFレポートを生成する方法を示します。

IronPDFはHTMLから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");
    }
}
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 Class
$vbLabelText   $csharpLabel

IronPDFのインストール

IronPDFの使用を開始するには、NuGetパッケージをインストールします:

Install-Package IronPdf

GraphQLデータを使用したIronPDFによる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");
    }
}
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
$vbLabelText   $csharpLabel

この例では、GraphQLクライアントを使用してGraphQL APIからhelloWorldメッセージを取得します。 そして、このメッセージを含むHTMLテンプレートを構築し、IronPDFのChromePdfRendererを使用してこのHTMLをPDFファイルに変換します。

出力

GraphQL C# (開発者のための動作方法): 図 2 - 前のコードから出力されたPDF

結論

GraphQLはAPI開発における画期的なテクノロジーとして登場し、従来のRESTful APIと比較してデータを効率的かつ柔軟にクエリし操作する方法を提供します。クライアントが必要なタイプのクエリデータのみを要求できる能力は、パフォーマンスと柔軟性が求められる現代のWebアプリケーションで特に魅力的です。

さらに、IronPDFのようなツールやパッケージとGraphQLを組み合わせることで、動的でデータ駆動型のPDFレポートを生成するエキサイティングな可能性の世界が広がります。 請求書の作成、レポートの生成、またはその他の種類のドキュメントの作成において、C#でIronPDFをGraphQLと統合することは、PDF生成を自動化するための強力で効率的な方法を提供します。

総じて、GraphQLとC#は、現代的で柔軟かつ効率的なWebアプリケーションを構築するための強力な組み合わせです。 HotChocolate、GraphQL.Client、IronPDFのようなライブラリを使用すると、開発者は今日のデジタル環境の要求に応える堅牢でデータ駆動型のアプリケーションを構築するために必要なすべてのツールを手に入れることができます。

HTMLからPDFについてのチュートリアルは、次のIronPDFライセンシングガイドで利用可能です。

よくある質問

GraphQLはRESTful APIとどのように異なりますか?

GraphQLはクライアントが必要なデータだけを要求できるため、RESTful APIに典型的なフェッチ過剰やフェッチ不足を減らします。この柔軟性により、データのクエリと操作においてより効率的です。

C#でGraphQLサーバーを設定するために推奨されるライブラリは何ですか?

C#でのGraphQLサーバー設定にはHotChocolateライブラリが推奨されます。.NET環境内でスキーマを定義し、クエリを管理するためのツールを提供します。

C#でGraphQLデータからPDFレポートを作成するにはどうすればよいですか?

GraphQL APIからデータを取得し、IronPDFを使用してそのデータを動的なPDFレポートに変換できます。IronPDFを用いると、HTMLコンテンツをPDF形式に変換してPDFドキュメントを操作可能です。

C#プロジェクトにGraphQLを統合するにはどのようなステップが含まれますか?

C#プロジェクトにGraphQLを統合するためには、HotChocolate NuGetパッケージをインストールし、データ型や操作を概説するスキーマを定義し、ASP.NET Coreを使用してサーバーを設定します。

C#クライアントを使用してGraphQL APIにクエリを行うにはどうすればよいですか?

GraphQL.Client NuGetパッケージを使用してAPIエンドポイントURIでGraphQLHttpClientをセットアップします。クエリを定義し、SendQueryAsyncメソッドを使用して送信します。

C#でURLをPDFに変換できますか?

はい、IronPDFのChromePdfRendererを使用してC#でURLをPDFに変換できます。これにより、URLからHTMLコンテンツを直接PDFドキュメントにレンダリングできます。

PDF作成のためにGraphQLと併用する場合のIronPDF使用理由は?

IronPDFはGraphQLを通じて取得した動的HTMLコンテンツをPDFに変換できるため、更新された特定のデータ出力を必要とするデータ駆動のレポートを作成するのに理想的です。

C#で基本的なGraphQLスキーマを作成するにはどうすればよいですか?

C#で基本的なGraphQLスキーマを作成するには、HotChocolateライブラリのスキーマ定義ツールを使用して利用可能なデータ型や操作を定義します。これにはフィールドとそのデータ型の指定が含まれます。

C#でのウェブアプリケーションにGraphQLを使用する利点は何ですか?

C#でGraphQLを使用すると、柔軟性とパフォーマンスの恩恵を受け、効率的なデータのクエリと操作を可能にし、現代のウェブアプリケーションを構築するために不可欠です。

C#プロジェクトでIronPDFを使用するにはどのようにインストールしますか?

C#プロジェクトでIronPDFを使用するには、NuGetパッケージマネージャーで次のコマンドを使用してインストールします:Install-Package IronPdf。これにより、そのPDF生成と操作機能にアクセスできます。

Curtis Chau
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。