Saltar al pie de página
.NET AYUDA

GraphQL C# (Cómo Funciona para Desarrolladores)

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.

Preguntas Frecuentes

¿En qué se diferencia GraphQL de las APIs RESTful?

GraphQL permite a los clientes solicitar exactamente los datos que necesitan, reduciendo la sobrecarga típica de las APIs RESTful. Esta flexibilidad lo hace más eficiente para consultar y manipular datos.

¿Qué biblioteca se recomienda para configurar un servidor GraphQL en C#?

Se recomienda la biblioteca HotChocolate para configurar un servidor GraphQL en C#. Proporciona herramientas para definir esquemas y gestionar consultas dentro de un entorno .NET.

¿Cómo puedo crear un informe PDF a partir de datos de GraphQL en C#?

Puedes obtener datos de una API GraphQL y usar IronPDF para convertir los datos en un informe PDF dinámico. IronPDF te permite manipular documentos PDF convirtiendo contenido HTML en formato PDF.

¿Qué pasos están involucrados en la integración de GraphQL en un proyecto C#?

Para integrar GraphQL en un proyecto C#, instala el paquete NuGet HotChocolate, define un esquema para delinear tipos y operaciones de datos, y configura el servidor usando ASP.NET Core.

¿Cómo se realiza una consulta a una API GraphQL utilizando un cliente C#?

Usa el paquete NuGet GraphQL.Client para configurar un GraphQLHttpClient con la URI del punto final de la API. Define tu consulta y envíala usando el método SendQueryAsync.

¿Puedo convertir una URL a PDF en C#?

Sí, puedes convertir una URL a PDF en C# usando el ChromePdfRenderer de IronPDF. Te permite renderizar contenido HTML de URLs directamente en un documento PDF.

¿Por qué usar IronPDF junto con GraphQL para la creación de PDFs?

IronPDF puede convertir contenido HTML dinámico obtenido a través de GraphQL en PDFs, lo cual es ideal para crear informes basados en datos que requieren salidas actualizadas y específicas.

¿Cómo se crea un esquema básico de GraphQL en C#?

Para crear un esquema básico de GraphQL en C#, define los tipos de datos y operaciones disponibles utilizando las herramientas de definición de esquemas de la biblioteca HotChocolate. Esto implica especificar campos y sus tipos de datos.

¿Cuáles son las ventajas de usar GraphQL con C# para aplicaciones web?

Usar GraphQL con C# proporciona beneficios en flexibilidad y rendimiento, permitiendo una consulta y manipulación de datos eficientes, lo cual es esencial para construir aplicaciones web modernas.

¿Cómo se instala IronPDF para usar en un proyecto C#?

Instala IronPDF para un proyecto C# usando el gestor de paquetes NuGet con el comando: Install-Package IronPdf. Esto te permite acceder a sus capacidades de generación y manipulación de PDF.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más