Introduction

GraphQL is a query language for APIs and a runtime that executes those queries against a typed schema. Instead of always receiving a fixed representation of a resource, the client describes the fields it needs; the server validates the operation, calls the responsible resolvers and returns JSON in that shape. I would consider GraphQL when different clients need varied combinations of data or when a screen depends on related information that today requires several calls, as long as the team is also prepared to control the cost of queries.

That flexibility does not make GraphQL automatically faster, smaller or simpler than REST. It shifts part of the work to the schema and the resolvers: the client chooses the fields, but the server remains responsible for authorization, validation, query limits, pagination and efficient data access. A poorly controlled query can still make the backend do excessive work.

In this guide I explain schemas, types, queries, mutations and resolvers, show a runnable implementation with GraphQL.NET on ASP.NET Core/.NET 10 and compare the same read with a REST endpoint. I also separate what the demo actually implements from the measures a production API needs to add. This is the second article in the APIs and Communication in .NET series: part 1 introduces gRPC and its usage criteria; the next one will be a dedicated SignalR guide.

ℹ️ Info: The tested sample uses GraphQL.NET 8.8.5, GraphQL.Server.Transports.AspNetCore 8.3.3 and .NET SDK 10.0.402. The query, the mutation, the validation and the REST endpoint were exercised over HTTP against the real API process.

Prerequisites

To follow the example, you need basic C#, familiarity with HTTP and .NET SDK 10.0.400 or later. The complete code is in the BlogSamples repository; clone it and start the API with the explicit URL:

1
2
3
git clone https://github.com/lzocateli/blog-zocateli-sample.git
cd blog-zocateli-sample
dotnet run --project src/BlogSamples --urls http://localhost:5101

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

The aggregating API also starts other domains of the repository. The existing outbox worker depends on PostgreSQL and logs connection failures if the service is unavailable; that is not a dependency of the GraphQL tutorial. This example’s endpoints use the in-memory product service, and any product created disappears when the process ends.

What GraphQL is and how an operation is executed

GraphQL is not a synonym for JSON or HTTP. GraphQL defines a language for expressing operations and a specification for schemas, types, validation and execution. HTTP usually carries the operation and the response, but the transport is a separate layer. A GraphQL API can use an HTTP endpoint such as /graphql; the query is sent in the body of a POST request or, in appropriate scenarios, in a GET request.

The schema is the contract that describes the types, fields, arguments and operations the server accepts. A query walks that graph of fields. For example, product can return a Product, and that type can offer id, name, price and category. The contract describes what can be requested, not necessarily how the data is stored: it can come from a table, an external API, a cache or more than one source.

In a request, the server first parses the operation’s syntax. Then it validates whether the fields and arguments exist in the schema and whether the types are compatible. If the operation passes, the executor resolves the requested fields and builds a JSON response with the same shape as the selection. A validation failure stops the operation before the resolvers are called; a failure during execution can return partial or null data together with errors.

GraphQL execution flow showing the query, schema validation, resolver and JSON response

⚠️ Warning: The GraphQL language defines the operation, not a promise of universal transport. The example uses HTTP POST with JSON; WebSockets and subscriptions are a different scope and are not part of this implementation.

Schema, types, queries, mutations and inputs

A type is a type in the schema. GraphQL defines scalars such as String, Int, Float, Boolean and ID; the schema can also declare enums, object types and input objects. Product and Category are output types: they describe the data the server can return. An input object groups received values, usually for a mutation with several parameters.

The schema has a root read type, usually called Query, and can have a root Mutation for write operations. Subscription is used for continuous updates when the implementation chooses a compatible transport. Those names are contract conventions, not mandatory table or class names. A field can receive arguments and return an object, a list, a scalar or a nullable value.

The example uses CreateProductInput to group name, description, price, stock and categoryId. That keeps the mutation signature readable and makes it easier to evolve the input data. In the resolver, the values are converted to the CriarProdutoRequest the API already uses. The input goes through explicit validation of name, price, stock and category before the service is called.

An enum restricts a field to named values, such as DRAFT and PUBLISHED, instead of accepting any string. Non-null types (Product!) and lists ([Product!]!) also express nullability in the contract; use those guarantees only when the application can honor them.

A mutation does not replace domain rules or a transaction. The schema determines the shape of input and output; the resolver calls the application, which must validate invariants, authorize the user and control persistence and side effects. In the sample, storage is deliberately in memory and there is no authentication. That is enough to demonstrate the flow, not to represent a production API.

The role of resolvers and the N+1 problem

A resolver is the function that obtains a field’s value. It can read an already-loaded property, query a service or compose results from different sources. Query arguments reach the resolver through the execution context; application dependencies can be accessed through the dependency injection container. The schema does not require each field to run its own query: sibling fields can share data, and an application layer can return an already-prepared object.

In the sample, the root product(id:) resolver calls IProdutoService.ObterProdutoPorIdAsync. The category field uses the DTO’s CategoriaId and asks the same service for the category. In a query for a single product, that is easy to follow. If the schema started listing dozens of products and each item fetched its category individually, the pattern could generate one query for the list plus one more for each category: the N+1 problem.

The DataLoader groups keys requested during an execution and lets you fetch several values in batch; it can also reuse the result for repeated keys within that context. With 50 orders that load users, for example, the application can do one fetch for the orders and one batch fetch for the users, instead of 51 separate accesses. The gain depends on the source offering a batch operation and on the loader being configured in the correct scope; it is not an automatic optimization of any resolver.

So keep resolvers thin: forward the operation to services that concentrate authorization and domain rules, limit lists and propagate cancellation and errors. The demo does not implement DataLoader because it queries only one product and one category, with no list that exposes N+1.

GraphQL.NET on ASP.NET Core and .NET 10

GraphQL.NET provides the executor, the types and the dependency injection integration features. The ASP.NET Core transport adds HTTP middleware to receive operations at the endpoint. In the sample, GraphQL and its DI and serialization packages are pinned to 8.8.5, while GraphQL.Server.Transports.AspNetCore is on 8.3.3; the verified packages declare the MIT license and targets compatible with later frameworks.

The current GraphQL.NET integration documentation presents a quickstart whose TargetFramework is net10.0. The NuGet page for transport 8.3.3 still describes the middleware’s compatibility up to ASP.NET Core 9. Since those pieces of information do not line up, I do not treat the NuGet target declaration as standalone proof about the runtime: I restored and compiled the packages on SDK 10.0.402 and ran a query, a mutation and a validation error against the sample’s real endpoint on .NET 10.

Service registration binds the schema to the JSON implementation. The graph types the schema discovers also need to be available in DI:

1
2
3
4
5
6
7
// Registers the graph types and the API's typed schema.
builder.Services.AddSingleton<ProdutoGraphType>();
builder.Services.AddSingleton<CategoriaGraphType>();
builder.Services.AddSingleton<CriarProdutoInputGraphType>();
builder.Services.AddGraphQL(options => options
    .AddSchema<ProdutoSchema>()
    .AddSystemTextJson());

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

After building the application, the middleware receives operations at /graphql:

1
2
app.UseWebSockets();
app.UseGraphQL<ProdutoSchema>("/graphql");

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

The sample registers ProdutoSchema, whose root Query contains product(id:) and whose root Mutation contains createProduct(input:). There is no GraphiQL, subscriptions, new database or other GraphQL engine in this example.

Practical Example

I will query the product with ID 1, which in the API seed is the Smartphone Galaxy S25. The query asks only for the identifier, name, price and category name; the variables are kept separate from the operation text, which makes it easier to reuse the query without interpolating values into the string.

1
2
3
4
# Sends the operation and the id argument as a JSON variable.
curl -i http://localhost:5101/graphql \
  -H 'Content-Type: application/json' \
  -d '{"query":"query($id:Int!){product(id:$id){id name price category{name}}}","variables":{"id":1}}'

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

Response observed in the sample (the seed data is in Portuguese):

1
{"data":{"product":{"id":1,"name":"Smartphone Galaxy S25","price":4299.00,"category":{"name":"Eletrônicos"}}}}

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

Now I do the REST read of the same ID:

1
curl -i http://localhost:5101/api/products/1

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

1
{"id":1,"name":"Smartphone Galaxy S25","description":"Tela AMOLED 6.2\", 256GB, 5G","price":4299.00,"stock":45,"active":true,"categoryId":1,"categoryName":"Eletrônicos"}

The sample’s REST endpoint returns the representation its contract defined; the example’s GraphQL query asked for a specific projection in the document itself. That illustrates two concrete interfaces, not an intrinsic limitation of REST. A REST API can also have specialized endpoints, projection parameters or different representations. Both JSON payloads come from the same in-memory source, but each contract exposes a different format.

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

To create a product, I send a CreateProductInput. The first product created in a clean run received ID 53; the mutation returns that value and the selected fields:

1
2
3
curl -i http://localhost:5101/graphql \
  -H 'Content-Type: application/json' \
  -d '{"query":"mutation($input:CreateProductInput!){createProduct(input:$input){id name price category{name}}}","variables":{"input":{"name":"Mouse GraphQL","description":"Produto de demonstração","price":99.90,"stock":10,"categoryId":1}}}'

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

1
{"data":{"createProduct":{"id":53,"name":"Mouse GraphQL","price":99.90,"category":{"name":"Eletrônicos"}}}}

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

The resolver rejects a price equal to zero before calling IProdutoService. The transport returns HTTP 200, but the response includes errors and createProduct: null; so a GraphQL client must examine the response body, not just the HTTP status.

1
2
3
curl -i http://localhost:5101/graphql \
  -H 'Content-Type: application/json' \
  -d '{"query":"mutation($input:CreateProductInput!){createProduct(input:$input){id name price}}","variables":{"input":{"name":"Produto inválido","price":0,"stock":10,"categoryId":1}}}'

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

1
{"errors":[{"message":"Preço deve ser entre R$ 0,01 e R$ 999.999,99.","path":["createProduct"]}],"data":{"createProduct":null}}

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

A query that tries to select a nonexistent field is rejected before execution. On the tested server, that validation failure returned HTTP 400 with the code FIELDS_ON_CORRECT_TYPE.

1
2
3
curl -i http://localhost:5101/graphql \
  -H 'Content-Type: application/json' \
  -d '{"query":"{ product(id:1) { missingField } }"}'

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

1
{"errors":[{"message":"Cannot query field 'missingField' on type 'Product'.","extensions":{"code":"FIELDS_ON_CORRECT_TYPE","number":"5.3.1"}}]}

📂 Source Code: The complete example is available in the blog’s samples repository: BlogSamples/GraphQL/

Security and operational limits

GraphQL does not replace authentication or authorization. Knowing an object’s ID does not prove that the user can read or change it. The server must check authorization at the resource level and, when necessary, at the level of each field; mutations need to validate the user and the domain rule before producing effects. A check only at the endpoint may be insufficient when the same schema exposes data with different access levels.

Flexibility also creates an execution budget. An API that accepts lists must enforce pagination with a maximum limit, restrict depth and complexity when the graph allows expensive queries, control batching and apply timeouts and rate limits per identity or client. The size of the HTTP body also needs a limit. Counting requests in isolation does not measure the work: a single operation can select many fields or repeat calls to different objects.

Introspection lets clients query the schema itself. It is useful for tooling, but evaluate its exposure; restricting it does not replace authorization or cost limits. Do not expose GraphiQL unnecessarily and avoid stack traces and internal details in production errors.

The GraphQL.NET 8.3.3 transport enables CSRF protection by default and does not enable processing of POST forms by default. Even so, an API with cookie authentication needs to review accepted methods, CORS, headers and CSRF mechanisms in the real configuration. For mutations, use POST; do not treat type validation as authorization, and do not trust client data without validating invariants in the domain.

In the demo, validation of name, price, stock and category is implemented, but the API has no login, authorization policy, rate limit, complexity limit or persistence. Introspection remains available and there is no GraphiQL interface. These are deliberate limits of the teaching example; do not interpret them as a recommended configuration for a public API.

⚠️ Warning: The schema describes available fields, not who can access them. Each resolver or use case needs to apply the access rules for the data and the operation.

GraphQL, REST and gRPC: how to choose

I would start with the consumers, contract and traffic, not with the team’s preference. GraphQL serves variable combinations of data; REST organizes resources and HTTP semantics; gRPC defines typed methods and messages for controlled services and streaming.

CriterionRESTGraphQLgRPC
ContractResources, URLs and HTTP semanticsTyped schema and selectable fieldsServices and messages in a Protobuf contract
Data selectionRepresentation defined by the endpoint; can have projectionsSelection written in each queryMessage structure defined by the method
CachingIntegrates directly with HTTP caching semantics for GETDepends on the transport, the operation and the adopted caching strategyUsually requires an application strategy or a compatible intermediary
StreamingHTTP allows streaming, depending on endpoint and formatSubscriptions depend on a configured transport and protocolUnary, server, client or bidirectional streaming is part of the RPC model
Common clientBrowsers, services and HTTP toolsClients that understand the schema and send GraphQL operationsServices with a contract and generated client; browsers may need gRPC-Web
Operational costModeling resources and evolving representationsOperating schema, resolvers, authorization and query limitsGenerating/versioning contracts, configuring HTTP/2 and operating streams

In the example above, GET /api/products/1 returns description, stock and a flattened category, while the GraphQL query selects id, name, price and category { name }. That shows the contract I implemented: it does not prove that REST always returns too many fields. A REST route could offer a projection or a smaller representation; compare concrete contracts instead of caricatured patterns.

For a web client with composite reads and variable requirements, GraphQL can concentrate the coordination and reduce specific calls, as long as limits and resolvers are well designed. For resources that fit HTTP methods and conventional caching, REST can be simpler. For internal services that need generated contracts or continuous streams, gRPC may fit better. You can use more than one style in different parts of a product; none wins in every scenario.

Tips and Good Practices

  • Model the domain before the database. Types and fields should represent the contract that is useful to clients, not mirror tables or internal entities. That lets the API evolve without exposing the persistence structure.

  • Keep resolvers small. Use them to forward arguments to services and assemble results, not to concentrate authorization, business rules and ad hoc queries. The important logic needs to be reusable and testable outside GraphQL.

  • Put limits on every list. Pagination with a maximum size prevents a valid selection from requesting an unlimited volume of objects. Combine that limit with depth or cost analysis when the schema has broad relationships.

  • Treat N+1 as a data-access risk. Measure how many calls each query triggers and use DataLoader when several resolvers request keys that can be grouped. Batching needs to respect tenant, authorization and request scope.

  • Validate and authorize mutations in the domain. GraphQL types help reject invalid formats, but they do not replace business rules or per-record permissions. Return useful errors without exposing stack traces, SQL or internal data.

  • Evolve the schema compatibly. Prefer adding fields and deprecating old ones with a clear deadline before removing them. Track which clients still use each field and treat incompatible changes as an explicit migration.

Conclusion

GraphQL gives the client a language to select data within a typed contract. That model is especially useful when consumers need different combinations of information, but it requires attention to the cost of each operation, to resolvers, to authorization and to schema evolution. The implementation shown uses GraphQL.NET 8.8.5 and the ASP.NET Core 8.3.3 transport on .NET 10, over the same in-memory products that feed a REST endpoint.

I would not choose GraphQL just because a query can ask for few fields. REST also allows projections and specialized representations, and gRPC solves other contract and streaming problems. The decision should start from the clients, the read and write flows, caching, transport and the ability to operate the solution. In the next part of the series, I will cover SignalR as an option for real-time communication in .NET, without confusing that problem with data queries.

Objective Summary

  • GraphQL is a query language and a runtime that executes operations against a typed schema; the client selects fields and the server validates and resolves each operation.
  • Query and Mutation are GraphQL schema roots usually used for reading and writing; mutations still need domain validation, authorization and control of side effects.
  • GraphQL.NET 8.8.5 and GraphQL.Server.Transports.AspNetCore 8.3.3 ran a query, a mutation and HTTP validation in an ASP.NET Core/.NET 10 API from the BlogSamples sample.
  • DataLoader can group fetches made by resolvers and reduce the N+1 pattern when the data source offers a batch operation; it does not remove the need for limits or authorization.
  • REST can offer projections and specialized representations; the difference between the JSON payloads in this article describes only the concrete contracts tested.
  • GraphQL, REST and gRPC have different models and operational costs; the choice depends on the clients, the contract, the transport and the streaming and caching needs.

Read Also

References