Saltar al pie de página
.NET AYUDA

GraphQL C# (Cómo Funciona para Desarrolladores)

GraphQL ha ganado una popularidad significativa como una alternativa a las API RESTful para construir servicios web flexibles y eficientes. GraphQL está disponible en muchos idiomas diferentes, como Java, Python, ASP .NET core. Pero en este artículo, profundizaremos en el uso de GraphQL en el contexto de C#, explorando sus conceptos, implementación y uso con ejemplos prácticos. Además, usaremos IronPDF para C# para crear archivos PDF con la ayuda de la clase de consulta de definición de esquema de GraphQL.

¿Qué es GraphQL?

GraphQL es un lenguaje de consultas para APIs que permite a los clientes solicitar exactamente los datos que necesitan. A diferencia de las API RESTful, donde múltiples puntos finales pueden devolver estructuras de datos fijas, los servicios de GraphQL permiten a los clientes especificar la forma de los datos que requieren, haciéndolo más eficiente y flexible.

Configuración de GraphQL en C#;

Para usar GraphQL en un proyecto de C#, necesitarás la biblioteca HotChocolate, una implementación popular de servidor de punto final GraphQL para .NET.

Primero, instala el paquete NuGet Hot Chocolate:

Install-Package HotChocolate.AspNetCore

Creación de un esquema GraphQL

Un esquema de GraphQL define los tipos de datos y operaciones disponibles en tu API. Aquí hay un simple ejemplo de implementación guiada por el esquema para una aplicación de blog:

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

En este ejemplo, definimos un campo helloWorld que devuelve una cadena "¡Hola, GraphQL!" cuando se consulta.

Creación de un servidor GraphQL

A continuación, configura un servidor GraphQL usando 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

Consulta GraphQL desde C#

Ahora, veamos cómo consultar esta API GraphQL desde un cliente C# usando el paquete NuGet GraphQL.Client:

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# ofrece una manera poderosa y flexible de diseñar APIs, y con bibliotecas como HotChocolate, integrar un backend GraphQL en tus aplicaciones C# se vuelve sencillo. Al definir un esquema y configurar un servidor, puedes exponer tus datos a través de una API GraphQL y consultarlos eficientemente desde clientes C#.

Resultado

GraphQL C# (Cómo Funciona para Desarrolladores): Figura 1 - Salida de consola al ejecutar el código anterior

Introducción a IronPDF en C#;

IronPDF es una biblioteca versátil en C# que te permite crear, editar y manipular documentos PDF sin esfuerzo. En esta sección, introduciremos IronPDF y demostraremos cómo usarlo junto con GraphQL para generar informes PDF dinámicos.

IronPDF sobresale con su funcionalidad HTML a PDF, preservando todos los diseños y estilos. Permite la creación de PDFs a partir de contenido web, perfecto para informes, facturas y documentación. Los archivos HTML, URLs y cadenas HTML pueden ser convertidos a PDFs sin problemas.

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

Instalación de IronPDF

Para comenzar con IronPDF, instala el paquete NuGet:

Install-Package IronPdf

Generación de PDF con datos GraphQL mediante IronPDF

Vamos a crear un informe PDF que recoja datos del usuario desde nuestra API GraphQL y los muestre de manera formateada.

Ejemplo

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

En este ejemplo, usamos el cliente GraphQL para obtener el mensaje helloWorld de nuestra API GraphQL. Luego, construimos una plantilla HTML que incluye este mensaje y usamos el ChromePdfRenderer de IronPDF para convertir este HTML en un archivo PDF.

Resultado

GraphQL C# (Cómo Funciona para Desarrolladores): Figura 2 - PDF emitido desde el código anterior

Conclusión

GraphQL ha surgido como un factor revolucionario en el desarrollo de API, ofreciendo una manera más flexible y eficiente para consultar y manipular datos en comparación con las API RESTful tradicionales. Su capacidad para permitir a los clientes solicitar solo el tipo de datos que necesitan lo hace particularmente atractivo para aplicaciones web modernas donde el rendimiento y la flexibilidad son primordiales.

Además, combinar GraphQL con herramientas y paquetes como IronPDF abre un mundo de posibilidades emocionantes para generar informes PDF dinámicos y basados en datos. Ya sea estés creando facturas, generando informes o produciendo cualquier otro tipo de documentos, integrar IronPDF con GraphQL en C# proporciona una manera poderosa y eficiente de automatizar la generación de PDF.

En resumen, GraphQL y C# hacen una combinación poderosa para crear aplicaciones web modernas, flexibles y eficientes. Con bibliotecas como HotChocolate, GraphQL.Client, e IronPDF, los desarrolladores tienen todas las herramientas que necesitan para construir aplicaciones robustas y basadas en datos que cumplen con las demandas del entorno digital actual.

El tutorial de HTML a PDF está disponible en la siguiente Guía de Licencias IronPDF para que los usuarios lo utilicen.

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.

Jacob Mellor, Director de Tecnología @ Team Iron
Director de Tecnología

Jacob Mellor es Director de Tecnología en Iron Software y un ingeniero visionario que lidera la tecnología PDF en C#. Como el desarrollador original detrás de la base de código central de Iron Software, ha moldeado la arquitectura de productos de la compañía desde ...

Leer más