
GraphQL em C# (Como funciona para desenvolvedores)
GraphQL ganhou popularidade significativa como uma alternativa às APIs RESTful para a construção de serviços web flexíveis e eficientes. GraphQL está disponível em várias linguagens diferentes, como Java, Python e .NET Core. Mas neste artigo, vamos nos aprofundar no uso do GraphQL no contexto do C#, explorando seus conceitos, implementação e utilização com exemplos práticos. Além disso, utilizaremos o IronPDF para C# para criar arquivos PDF com a ajuda da classe de consulta de definição de esquema GraphQL.
O que é GraphQL?
GraphQL é uma linguagem de consulta para APIs que permite aos clientes solicitar exatamente os dados de que precisam. Diferentemente das APIs RESTful, onde vários endpoints podem retornar estruturas de dados fixas, os serviços GraphQL permitem que os clientes especifiquem o formato dos dados que necessitam, tornando-os mais eficientes e flexíveis.
Setting up GraphQL in C#
Para usar GraphQL em um projeto C#, você precisará da biblioteca HotChocolate, uma implementação popular de servidor de endpoints GraphQL for .NET.
Primeiro, instale o pacote NuGet Hot Chocolate:
Criando um esquema GraphQL
Um esquema GraphQL define os tipos de dados e as operações disponíveis em sua API. Aqui está um exemplo simples de implementação "schema-first" para um aplicativo 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 ClassNeste exemplo, definimos um campo helloWorld que retorna uma string "Olá, GraphQL!" quando consultado.
Criando um servidor GraphQL
Em seguida, configure um servidor GraphQL usando o 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#
Agora, vamos ver como consultar esta API GraphQL a partir de um cliente C# usando o pacote 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# oferece uma maneira poderosa e flexível de projetar APIs e, com bibliotecas como HotChocolate, integrar um backend GraphQL em seus aplicativos C# torna-se simples. Ao definir um esquema e configurar um servidor, você pode expor seus dados por meio de uma API GraphQL e consultá-los de forma eficiente a partir de clientes C#.
Saída

Intro to IronPDF in C#
IronPDF é uma biblioteca C# versátil que permite criar, editar e manipular documentos PDF sem esforço. Nesta seção, apresentaremos o IronPDF e demonstraremos como usá-lo em conjunto com o GraphQL para gerar relatórios PDF dinâmicos.
O IronPDF se destaca por sua funcionalidade de conversão de HTML para PDF , preservando todos os layouts e estilos. Permite a criação de PDFs a partir de conteúdo da web, ideal para relatórios, faturas e documentação. Arquivos HTML, URLs e strings HTML podem ser convertidos em PDFs sem 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 ClassInstalando o IronPDF
Para começar a usar o IronPDF, instale o pacote NuGet :
Gerando PDF com dados GraphQL usando IronPDF
Vamos criar um relatório em PDF que busque dados do usuário em nossa API GraphQL e os exiba de forma formatada.
Exemplo
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 ClassNeste exemplo, usamos o cliente GraphQL para buscar a mensagem helloWorld da nossa API GraphQL. Em seguida, construímos um modelo HTML que inclui essa mensagem e usamos o ChromePdfRenderer do IronPDF para converter este HTML em um arquivo PDF.
Saída

Conclusão
O GraphQL surgiu como um divisor de águas no desenvolvimento de APIs, oferecendo uma maneira mais flexível e eficiente de consultar e manipular dados em comparação com as APIs RESTful tradicionais. Sua capacidade de permitir que os clientes solicitem apenas o tipo de dados de consulta de que precisam o torna particularmente atraente para aplicações web modernas, onde desempenho e flexibilidade são fundamentais.
Além disso, a combinação de GraphQL com ferramentas e pacotes como o IronPDF abre um mundo de possibilidades empolgantes para a geração de relatórios em PDF dinâmicos e orientados a dados. Seja para criar faturas, gerar relatórios ou produzir qualquer outro tipo de documento, a integração do IronPDF com GraphQL em C# oferece uma maneira poderosa e eficiente de automatizar a geração de PDFs.
Em resumo, GraphQL e C# formam uma combinação poderosa para a criação de aplicações web modernas, flexíveis e eficientes. Com bibliotecas como HotChocolate, GraphQL.Client, e IronPDF, os desenvolvedores têm todas as ferramentas necessárias para criar aplicações robustas e orientadas a dados que atendam às demandas do cenário digital atual.
O tutorial de conversão de HTML para PDF está disponível no seguinte Guia de Licenciamento do IronPDF para os usuários.

Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais bem estruturados e visualmente atraentes.
Artigos relacionados


