
GraphQL en C# con HotChocolate | Guía 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.
Setting up GraphQL in C#
Para usar GraphQL en un proyecto de C#, necesitarás la biblioteca HotChocolate, una implementación popular de servidor de punto final GraphQL for .NET.
Primero, instala el paquete NuGet Hot Chocolate:
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!");
}
}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 ClassEn este ejemplo, definimos un campo helloWorld que retorna la 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();
});
}
}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 ClassQuerying GraphQL from C#
Ahora, veamos cómo consultar esta API de GraphQL desde un cliente en C# utilizando 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);
}
}'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 ClassGraphQL 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

Intro to IronPDF in 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");
}
}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 ClassInstalación de IronPDF
Para comenzar con IronPDF, instala el paquete NuGet:
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");
}
}'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 ClassEn este ejemplo, utilizamos el cliente de GraphQL para obtener el mensaje helloWorld de nuestra API de GraphQL. Luego, construimos una plantilla HTML que incluye este mensaje y utilizamos el ChromePdfRenderer de IronPDF para convertir este HTML a un archivo PDF.
Resultado

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 satisfacen las demandas del panorama digital actual.
El tutorial de HTML a PDF está disponible en la siguiente Guía de Licencias IronPDF para que los usuarios lo utilicen.

Jacob Mellor es Director de Tecnología de Iron Software y un ingeniero visionario pionero en la tecnología C# PDF. Como desarrollador original de la base de código principal de Iron Software, ha dado forma a la arquitectura de productos de la empresa desde su creación, transformándola, junto con el director ejecutivo Cameron Rimington, en una empresa de más de 50 personas que presta servicios a la NASA, Tesla y organismos gubernamentales de todo el mundo.
Artículos Relacionados


