.NET HELP

GraphQL C# (How It Works For Developers)

Published June 6, 2024
Share:

Introduction

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 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 implementation schema defines the data types and operations available in your API. Here's a simple example of schema first, of a GraphQL service schema for a blog application:

using HotChocolate.Types;
public class QueryType : ObjectType
{
    protected override void Configure(IObjectTypeDescriptor descriptor)
    {
        descriptor.Field("hello world")
            .Type<StringType>()
            .Resolve(context => "Hello, GraphQL!");
    }
}
using HotChocolate.Types;
public class QueryType : ObjectType
{
    protected override void Configure(IObjectTypeDescriptor descriptor)
    {
        descriptor.Field("hello world")
            .Type<StringType>()
            .Resolve(context => "Hello, GraphQL!");
    }
}
Imports HotChocolate.Types
Public Class QueryType
	Inherits ObjectType

	Protected Overrides Sub Configure(ByVal descriptor As IObjectTypeDescriptor)
		descriptor.Field("hello world").Type(Of StringType)().Resolve(Function(context) "Hello, GraphQL!")
	End Sub
End Class
VB   C#

In this example, we define a hello world 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
VB   C#

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;
using GraphQL.Client.Http;
using System;
using System.Threading.Tasks;
// query class
public class query
{
    public static async Task Main()
    {
        using var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions
        {
            EndPoint = new Uri("http://localhost:5000/graphql")
        });
        var schema = new GraphQLRequest
        {
            Query = @"
                {
                    hello world
                }"
        };
        var response = await graphQLClient.SendQueryAsync<dynamic>(shema);
        Console.WriteLine(response.Data.hello);
    }
}
using GraphQL.Client;
using GraphQL.Client.Http;
using System;
using System.Threading.Tasks;
// query class
public class query
{
    public static async Task Main()
    {
        using var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions
        {
            EndPoint = new Uri("http://localhost:5000/graphql")
        });
        var schema = new GraphQLRequest
        {
            Query = @"
                {
                    hello world
                }"
        };
        var response = await graphQLClient.SendQueryAsync<dynamic>(shema);
        Console.WriteLine(response.Data.hello);
    }
}
'INSTANT VB NOTE: 'Option Strict Off' is used here since dynamic typing is used:
Option Strict Off

Imports GraphQL.Client
Imports GraphQL.Client.Http
Imports System
Imports System.Threading.Tasks
' query class
Public Class query
	Public Shared Async Function Main() As Task
		Dim graphQLClient = New GraphQLHttpClient(New GraphQLHttpClientOptions With {.EndPoint = New Uri("http://localhost:5000/graphql")})
		Dim schema = New GraphQLRequest With {.Query = "
                {
                    hello world
                }"}
'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)(shema)
		Console.WriteLine(response.Data.hello)
	End Function
End Class
VB   C#

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 function, 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();

        // 1. 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");

        // 2. 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");

        // 3. 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();

        // 1. 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");

        // 2. 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");

        // 3. 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()

		' 1. 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")

		' 2. 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")

		' 3. 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
VB   C#

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;
using GraphQL.Client.Http;
using System.Threading.Tasks;
using System;
public class PdfGenerator
{
    public async Task GeneratePdfAsync()
    {
        var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions
        {
            EndPoint = new Uri("http://localhost:5000/graphql")
        });
        // graphql queries & graphql requests
        var query = new GraphQLRequest 
        {
            Query = @"
                {
                    hello world
                }"
        };
        var response = await graphQLClient.SendQueryAsync<dynamic>(query);
        var helloMessage = response.Data.hello.ToString();
        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;
using GraphQL.Client.Http;
using System.Threading.Tasks;
using System;
public class PdfGenerator
{
    public async Task GeneratePdfAsync()
    {
        var graphQLClient = new GraphQLHttpClient(new GraphQLHttpClientOptions
        {
            EndPoint = new Uri("http://localhost:5000/graphql")
        });
        // graphql queries & graphql requests
        var query = new GraphQLRequest 
        {
            Query = @"
                {
                    hello world
                }"
        };
        var response = await graphQLClient.SendQueryAsync<dynamic>(query);
        var helloMessage = response.Data.hello.ToString();
        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
Imports GraphQL.Client.Http
Imports System.Threading.Tasks
Imports System
Public Class PdfGenerator
	Public Async Function GeneratePdfAsync() As Task
		Dim graphQLClient = New GraphQLHttpClient(New GraphQLHttpClientOptions With {.EndPoint = New Uri("http://localhost:5000/graphql")})
		' graphql queries & graphql requests
		Dim query As New GraphQLRequest With {.Query = "
                {
                    hello world
                }"}
'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.hello.ToString()
		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
VB   C#

In this example, we use the GraphQL client to fetch the 'hello world' 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 link for users to avail.

< PREVIOUS
C# Call Base Constructor (How It Works For Developers)
NEXT >
C# Long to String (How It Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,173,334 View Licenses >