Skip to footer content
.NET HELP

GraphQL C# (How It Works For Developers)

GraphQL has gained significant popularity as an alternative to RESTful APIs for building flexible and efficient web services. GraphQL is available in plenty of different languages, such as Java, Python, ASP .NET core. But in this article, we'll delve into using GraphQL in the context of C#, exploring its concepts, implementation, and usage with practical examples. Also, we will be using IronPDF for C# for creating PDF files with the help of the GraphQL schema definition query class.

What is GraphQL?

GraphQL is a query language for APIs that enables clients to request exactly the data they need. Unlike RESTful APIs, where multiple endpoints might return fixed data structures, GraphQL services allow clients to specify the shape of the data they require, making it more efficient and flexible.

Setting up GraphQL in C#

To use GraphQL in a C# project, you'll need the HotChocolate library, a popular GraphQL endpoint server implementation for .NET.

First, install the Hot Chocolate NuGet package:

Install-Package HotChocolate.AspNetCore

Creating a GraphQL Schema

A GraphQL schema defines the data types and operations available in your API. Here's a simple example of schema-first implementation for a blog application:

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

In this example, we define a helloWorld field that returns a string "Hello, GraphQL!" when queried.

Creating a GraphQL Server

Next, set up a GraphQL server using ASP.NET Core:

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

Querying GraphQL from C#

Now, let's see how to query this GraphQL API from a C# client using the GraphQL.Client NuGet package:

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# offers a powerful and flexible way to design APIs, and with libraries like HotChocolate, integrating a GraphQL backend into your C# applications becomes straightforward. By defining a schema and setting up a server, you can expose your data through a GraphQL API and query it efficiently from C# clients.

Output

GraphQL C# (How It Works For Developers): Figure 1 - Console output from running the previous code

Intro to IronPDF in C#

IronPDF is a versatile C# library that allows you to create, edit, and manipulate PDF documents effortlessly. In this section, we'll introduce IronPDF and demonstrate how to use it in conjunction with GraphQL to generate dynamic PDF reports.

IronPDF excels with its HTML to PDF functionality, preserving all layouts and styles. It allows for PDF creation from web content, perfect for reports, invoices, and documentation. HTML files, URLs, and HTML strings can be seamlessly converted to PDFs.

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

Installing IronPDF

To get started with IronPDF, install the NuGet package:

Install-Package IronPdf

Generating PDF with GraphQL Data using IronPDF

Let's create a PDF report that fetches user data from our GraphQL API and displays it in a formatted manner.

Example

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

In this example, we use the GraphQL client to fetch the helloWorld message from our GraphQL API. Then, we construct an HTML template that includes this message and use IronPDF's ChromePdfRenderer to convert this HTML to a PDF file.

Output

GraphQL C# (How It Works For Developers): Figure 2 - Outputted PDF from the previous code

Conclusion

GraphQL has emerged as a game-changer in API development, offering a more flexible and efficient way to query and manipulate data compared to traditional RESTful APIs. Its ability to allow clients to request only the type query data they need makes it particularly appealing for modern web applications where performance and flexibility are paramount.

Moreover, combining GraphQL with tools and packages like IronPDF opens up a world of exciting possibilities for generating dynamic and data-driven PDF reports. Whether you're creating invoices, generating reports, or producing any other kind of documents, integrating IronPDF with GraphQL in C# provides a powerful and efficient way to automate PDF generation.

In summary, GraphQL and C# make a powerful combination for building modern, flexible, and efficient web applications. With libraries like HotChocolate, GraphQL.Client, and IronPDF, developers have all the tools they need to build robust, data-driven applications that meet the demands of today's digital landscape.

The HTML to PDF tutorial is available at the following IronPDF Licensing Guide for users to avail.

Frequently Asked Questions

What is GraphQL?

GraphQL is a query language for APIs that enables clients to request exactly the data they need, making it more efficient and flexible compared to RESTful APIs.

How do you set up GraphQL in a C# project?

To set up GraphQL in a C# project, you need to use the HotChocolate library, a popular GraphQL endpoint server implementation for .NET. Install the HotChocolate.AspNetCore NuGet package and configure your server using ASP.NET Core.

What is the purpose of a GraphQL schema?

A GraphQL schema defines the data types and operations available in your API. It allows you to specify the shape of the data that can be queried.

How can you query a GraphQL API from a C# client?

You can query a GraphQL API from a C# client using the GraphQL.Client NuGet package. Set up a GraphQLHttpClient with the endpoint URI, define your query, and send it using SendQueryAsync method.

How can you generate PDF reports using C#?

You can generate PDF reports using IronPDF, a C# library for creating, editing, and manipulating PDF documents. It can convert HTML content that includes data fetched from a GraphQL API to generate dynamic PDF reports.

How do you convert HTML to PDF in C#?

To convert HTML to PDF in C#, use IronPDF's ChromePdfRenderer to render HTML content, files, or URLs into a PDF. You can save the resulting PDF using SaveAs method.

What are the benefits of using GraphQL over RESTful APIs?

GraphQL allows clients to request only the data they need, reducing over-fetching and under-fetching. It provides a more flexible and efficient way to query and manipulate data compared to traditional RESTful APIs.

What is the HotChocolate library in the context of GraphQL?

HotChocolate is a library used to create GraphQL endpoints in a .NET environment. It provides tools to define schemas, set up servers, and manage queries and mutations efficiently.

Can you generate reports from GraphQL data?

Yes, you can generate reports from GraphQL data by fetching data from a GraphQL API, constructing an HTML template with this data, and then converting it to a PDF using IronPDF.

How do you install a PDF generation library for a C# project?

To install IronPDF for a C# project, use the NuGet package manager with the command: Install-Package IronPdf.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.