### GraphQL GET Request Example Source: https://chillicream.com/docs/hotchocolate/v16/server/cache-control Demonstrates a basic GraphQL GET request for querying products. ```http GET /graphql?query=query GetProducts{products{nodes{name}}} ``` -------------------------------- ### Install OpenAPI Adapter Package Source: https://chillicream.com/docs/hotchocolate/v16/guides/openapi-adapter Install the HotChocolate.Adapters.OpenApi NuGet package using the .NET CLI. ```bash dotnet add package HotChocolate.Adapters.OpenApi ``` -------------------------------- ### Install Entity Framework Core Integration Package Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/integrations/entity-framework Install the necessary HotChocolate.Data.EntityFramework package using the .NET CLI. ```bash dotnet add package HotChocolate.Data.EntityFramework ``` -------------------------------- ### Install Hot Chocolate Templates Source: https://chillicream.com/docs/hotchocolate/v16/get-started-with-graphql-in-net-core Installs the necessary Hot Chocolate project templates for .NET. ```bash dotnet new install HotChocolate.Templates ``` -------------------------------- ### Install PostgreSQL Subscriptions Package Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/subscriptions Installs the HotChocolate PostgreSQL subscriptions package using the .NET CLI. ```bash dotnet add package HotChocolate.Subscriptions.Postgres ``` -------------------------------- ### Install MCP Adapter Package Source: https://chillicream.com/docs/hotchocolate/v16/guides/mcp-adapter Install the HotChocolate.Adapters.Mcp NuGet package using the .NET CLI. ```bash dotnet add package HotChocolate.Adapters.Mcp ``` -------------------------------- ### Run the GraphQL Server Source: https://chillicream.com/docs/hotchocolate/v16/get-started-with-graphql-in-net-core Starts the .NET Core application, running the configured GraphQL server. ```bash dotnet run ``` -------------------------------- ### Client Subscription Example Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/subscriptions An example of a GraphQL subscription query a client would send to receive 'bookAdded' events. The client will receive a stream of 'Book' objects. ```graphql subscription { bookAdded { title author } } ``` -------------------------------- ### GraphQL GET Request Example Source: https://chillicream.com/docs/hotchocolate/v16/server/http-transport Example of sending a GraphQL query and variables via HTTP GET request parameters. This method is suitable for caching. ```graphql query ($id: ID!) { user(id: $id) { name } } ``` ```json { "id": "QVBJcy5ndXJ1" } ``` ```http GET /graphql?query=query(%24id%3A%20ID!)%7Buser(id%3A%24id)%7Bname%7D%7D&variables=%7B%22id%22%3A%22QVBJcy5ndXJ1%22%7D` HOST: foo.example ``` ```http HTTP/1.1 200 OK Content-Type: application/json { "data": { "user": { "name": "Jon Doe" } } } ``` -------------------------------- ### Install Redis Subscriptions Package Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/subscriptions Installs the HotChocolate Redis subscriptions package using the .NET CLI. ```bash dotnet add package HotChocolate.Subscriptions.Redis ``` -------------------------------- ### Set up Redis Docker Container Source: https://chillicream.com/docs/hotchocolate/v16/performance/automatic-persisted-operations Start a Redis Docker container to use as a persisted operation document storage. ```bash docker run --name redis-stitching -p 7000:6379 -d redis ``` -------------------------------- ### Install NATS Subscriptions Package Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/subscriptions Installs the HotChocolate NATS subscriptions package using the .NET CLI. ```bash dotnet add package HotChocolate.Subscriptions.Nats ``` -------------------------------- ### Install Marten Package Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/integrations/marten Install the necessary Hot Chocolate Marten integration package using the .NET CLI. ```bash dotnet add package HotChocolate.Data.Marten ``` -------------------------------- ### Install Hot Chocolate Authorization Package Source: https://chillicream.com/docs/hotchocolate/v16/security/authentication Install the Hot Chocolate authorization package using the .NET CLI. ```bash dotnet add package HotChocolate.AspNetCore.Authorization ``` -------------------------------- ### Complete Program.cs with OpenTelemetry Source: https://chillicream.com/docs/hotchocolate/v16/server/instrumentation A full example of Program.cs demonstrating the integration of Hot Chocolate GraphQL server with OpenTelemetry for comprehensive tracing. ```csharp using OpenTelemetry.Resources; using OpenTelemetry.Trace; var builder = WebApplication.CreateBuilder(args); builder .AddGraphQL() .AddQueryType() .AddInstrumentation(); builder.Logging.AddOpenTelemetry( b => b.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("Demo"))); builder.Services .AddOpenTelemetry() .WithTracing( b => { b.AddHttpClientInstrumentation(); b.AddAspNetCoreInstrumentation(); b.AddHotChocolateInstrumentation(); b.AddOtlpExporter(); }); var app = builder.Build(); app.MapGraphQL(); app.Run(); ``` -------------------------------- ### GraphQL Query Example Source: https://chillicream.com/docs/hotchocolate/v16/resolvers A sample GraphQL query to fetch user and company information. ```graphql query { me { name company { id name } } } ``` -------------------------------- ### Install HotChocolate.Spatial Package Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/spatial-data Install the HotChocolate.Spatial package using the .NET CLI. Ensure all HotChocolate packages share the same version. ```bash dotnet add package HotChocolate.Spatial ``` -------------------------------- ### Configure SSE Preflight Headers Globally Source: https://chillicream.com/docs/hotchocolate/v16/server/http-transport Enforces preflight headers for both GET and multipart requests by configuring server options globally within the application setup. ```csharp builder .AddGraphQL() .ModifyServerOptions(o => { o.EnforceGetRequestsPreflightHeader = true; o.EnforceMultipartRequestsPreflightHeader = true; }); ``` -------------------------------- ### Install JWT Bearer Package Source: https://chillicream.com/docs/hotchocolate/v16/security/authentication Install the necessary NuGet package for JWT bearer authentication using the .NET CLI. ```bash dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer ``` -------------------------------- ### Client GraphQL Query Example Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/queries A sample client query to fetch book titles and author names. ```graphql query { books { title } author(id: 1) { name } } ``` -------------------------------- ### Install OpenTelemetry Packages Source: https://chillicream.com/docs/hotchocolate/v16/server/instrumentation Add the necessary OpenTelemetry packages for ASP.NET Core integration, HTTP client instrumentation, and OTLP export. ```bash dotnet add package OpenTelemetry.Extensions.Hosting dotnet add package OpenTelemetry.Instrumentation.AspNetCore dotnet add package OpenTelemetry.Instrumentation.Http dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol ``` -------------------------------- ### Add MCP Adapter Package Source: https://chillicream.com/docs/hotchocolate/v16/build/adapters/mcp Install the MCP adapter package to your server project using the .NET CLI. ```bash dotnet add package HotChocolate.Adapters.Mcp ``` -------------------------------- ### Install Filesystem Package Source: https://chillicream.com/docs/hotchocolate/v16/performance/trusted-documents Command to add the HotChocolate.PersistedOperations.FileSystem package to your project. ```bash dotnet add package HotChocolate.PersistedOperations.FileSystem ``` -------------------------------- ### Install HotChocolate.ApolloFederation Package Source: https://chillicream.com/docs/hotchocolate/v16/guides/federation Install the necessary package for Apollo Federation support in Hot Chocolate. Ensure all HotChocolate.* packages share the same version. ```bash dotnet add package HotChocolate.ApolloFederation ``` -------------------------------- ### Install MongoDB Data Package Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/integrations/mongodb Install the `HotChocolate.Data.MongoDb` package using the .NET CLI. Ensure all `HotChocolate.*` packages share the same version. ```bash dotnet add package HotChocolate.Data.MongoDb ``` -------------------------------- ### GraphQL Schema Example for Interface Usage Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/unions Demonstrates an interface `Event` with shared fields and conditional fragments for specific types. ```graphql interface Event { id: ID! timestamp: DateTime! } # Shared fields are queryable directly query { events { id timestamp ... on UserEvent { user { name } } ... on SystemEvent { severity } } } ``` -------------------------------- ### Install Nitro Packages Source: https://chillicream.com/docs/hotchocolate/v16/build/adapters/mcp Install the core Nitro package and the Hot Chocolate integration package using the .NET CLI. ```bash dotnet add package ChilliCream.Nitro dotnet add package ChilliCream.Nitro.HotChocolate ``` -------------------------------- ### Add HotChocolate.Caching Package Source: https://chillicream.com/docs/hotchocolate/v16/server/cache-control Install the HotChocolate.Caching package using the .NET CLI. ```bash dotnet add package HotChocolate.Caching ``` -------------------------------- ### Install HotChocolate.Data.Spatial Package Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/spatial-data If using data extensions for database projection, install the HotChocolate.Data.Spatial package. Ensure all HotChocolate packages share the same version. ```bash dotnet add package HotChocolate.Data.Spatial ``` -------------------------------- ### Install Redis Package Source: https://chillicream.com/docs/hotchocolate/v16/performance/trusted-documents Command to add the HotChocolate.PersistedOperations.Redis package to your project. ```bash dotnet add package HotChocolate.PersistedOperations.Redis ``` -------------------------------- ### Install Azure Blob Storage Package Source: https://chillicream.com/docs/hotchocolate/v16/performance/trusted-documents Command to add the HotChocolate.PersistedOperations.AzureBlobStorage package to your project. ```bash dotnet add package HotChocolate.PersistedOperations.AzureBlobStorage ``` -------------------------------- ### ConfigureServices: New Schema Configuration Source: https://chillicream.com/docs/hotchocolate/v16/migrating/migrate-from-10-to-11 This demonstrates the new unified configuration API in version 11, starting with `AddGraphQLServer`. ```csharp services .AddGraphQLServer() .AddQueryType() .AddMutationType() ... ``` -------------------------------- ### Client Query Example Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/batching/dataloader This GraphQL query requests a list of products along with their associated brand names, which can lead to the N+1 problem if not handled efficiently. ```graphql query { products(first: 5) { nodes { name brand { name } } } } ``` -------------------------------- ### Create New Hot Chocolate GraphQL Project Source: https://chillicream.com/docs/hotchocolate/v16/performance/automatic-persisted-operations Creates a new Hot Chocolate GraphQL server project using the installed templates. ```bash dotnet new graphql ``` -------------------------------- ### GraphQL Schema Example for Union vs Interface Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/unions Illustrates a union type `SearchResult` and contrasts it with interface usage. ```graphql union SearchResult = User | Post | Comment # Client must fragment into each type query { search(term: "graphql") { ... on User { name } ... on Post { title } ... on Comment { body } } } ``` -------------------------------- ### GraphQL Schema with Descriptions Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/documentation Example of a GraphQL schema definition with descriptions for types and fields. ```graphql "Represents a registered user." type User { "The unique username." username: String! } ``` -------------------------------- ### GraphQL POST Request Example Source: https://chillicream.com/docs/hotchocolate/v16/server/http-transport Standard POST request for GraphQL queries. Ensure the Content-Type is application/json. ```http POST /graphql HOST: foo.example Content-Type: application/json { "query": "query($id: ID!){user(id:$id){name}}", "variables": { "id": "QVBJcy5ndXJ1" } } ``` ```http HTTP/1.1 200 OK Content-Type: application/json { "data": { "user": { "name": "Jon Doe" } } } ``` -------------------------------- ### DataLoader Instantiation (v10) Source: https://chillicream.com/docs/hotchocolate/v16/migrating/migrate-from-10-to-11 The v10 constructor for DataLoader did not require a scheduler. This example shows the older way of creating a DataLoader instance. ```csharp FooDataLoader dataLoader = new FooDataLoader( fooRepoMock.Object); ``` -------------------------------- ### Configure GraphQL HTTP Endpoint Options Source: https://chillicream.com/docs/hotchocolate/v16/server/endpoints Customize HTTP endpoint behavior using `WithOptions`. For example, disable GET requests. ```csharp endpoints.MapGraphQLHttp("/graphql/http").WithOptions(o => o.EnableGetRequests = false); ``` -------------------------------- ### GraphQL Schema Example Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/batching/dataloader This schema defines types for products and brands, illustrating a common scenario where related data needs to be fetched. ```graphql type Query { products(first: 5): ProductsConnection } type Product { id: ID! name: String! brand: Brand! } type Brand { id: ID! name: String! } ``` -------------------------------- ### Update DataLoaderOptions in Constructor Source: https://chillicream.com/docs/hotchocolate/v16/migrating/migrate-from-14-to-15 Starting with Hot Chocolate 15, DataLoaderOptions must be passed to the DataLoaderBase constructor. This example shows the required change in the constructor signature. ```csharp public class ProductByIdDataLoader : BatchDataLoader { private readonly IServiceProvider _services; public ProductDataLoader1( IBatchScheduler batchScheduler, DataLoaderOptions options) // the options are now required ... : base(batchScheduler, options) { } } ``` -------------------------------- ### Create New GraphQL Project Source: https://chillicream.com/docs/hotchocolate/v16/get-started-with-graphql-in-net-core Creates a new GraphQL project named 'GettingStarted' using the Hot Chocolate template. ```bash dotnet new graphql --name GettingStarted ``` -------------------------------- ### GraphQL Query for Cursor Pagination Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/integrations/mongodb Example GraphQL query demonstrating how to request paginated data with cursor information. ```graphql query GetPersons { persons(first: 50, after: "OTk=") { nodes { name addresses { city } } pageInfo { endCursor hasNextPage hasPreviousPage startCursor } } } ``` -------------------------------- ### Export Schema on Startup Source: https://chillicream.com/docs/hotchocolate/v16/server/warmup Use `ExportSchemaOnStartup()` to write the schema SDL to a file during server initialization, useful for CI/CD or schema registry integration. ```csharp builder .AddGraphQL() .ExportSchemaOnStartup("./schema.graphql"); ``` -------------------------------- ### GraphQL Client Query and Mutation Example Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema Illustrates how a client would query for a book by ID and create a new book using the defined schema. It shows the usage of fields and arguments. ```graphql query { bookById(id: "1") { title authors { name } } } mutation { createBook(input: { title: "New Book", authorIds: ["2"] }) { id title } } ``` -------------------------------- ### Rename Field via Resolver Method Name Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/object-types When using a separate resolver class, the method name determines the field name. The `Get` prefix is stripped and the result is camel-cased. For example, `GetFullName` becomes `fullName`. ```csharp public class Author { public string Name { get; set; } } [ObjectType] public static partial class AuthorNode { public static string GetFullName([Parent] Author author) => author.Name; } ``` -------------------------------- ### Configure Server Options for HTTP Behavior Source: https://chillicream.com/docs/hotchocolate/v16/server/options Enable or disable GET requests, multipart requests, and schema retrieval. Configure batching behavior and maximum batch size. ```csharp builder .AddGraphQL() .ModifyServerOptions(o => { o.EnableGetRequests = true; o.EnableMultipartRequests = true; o.Batching = AllowedBatching.All; o.MaxBatchSize = 50; o.EnableSchemaRequests = true; }); ``` -------------------------------- ### Migrate InitializeOnStartup to AddWarmupTask Source: https://chillicream.com/docs/hotchocolate/v16/migrating/migrate-from-15-to-16 Replace the `InitializeOnStartup` method with `AddWarmupTask` when migrating warmup tasks. This ensures that tasks run during application startup and schema updates. ```csharp builder.AddGraphQL() - .InitializeOnStartup(warmup: (executor, ct) => { /* ... */ }); + .AddWarmupTask((executor, ct) => { /* ... */ }); ``` -------------------------------- ### Complete Program.cs Configuration Source: https://chillicream.com/docs/hotchocolate/v16/guides/public-api This snippet shows a full Program.cs file integrating authentication, authorization policies, rate limiting, and GraphQL server configuration including execution rules, paging options, cost limits, and batch operation settings. It also configures endpoint mapping and middleware pipeline. ```csharp var builder = WebApplication.CreateBuilder(args); // Authentication (configure for your identity provider) builder.Services .AddAuthentication("Bearer") .AddJwtBearer(); // Authorization policies builder.Services.AddAuthorization(options => { options.AddPolicy("CanReadBilling", policy => policy.RequireClaim("scope", "billing:read")); }); // Rate limiting builder.Services.AddRateLimiter(options => { options.AddFixedWindowLimiter("graphql", opt => { opt.PermitLimit = 100; opt.Window = TimeSpan.FromMinutes(1); }); }); // GraphQL server builder .AddGraphQL() .AddAuthorization() .AddMaxExecutionDepthRule(15) .ModifyPagingOptions(opt => { opt.MaxPageSize = 100; opt.DefaultPageSize = 25; opt.RequirePagingBoundaries = true; }) .ModifyCostOptions(options => { options.MaxFieldCost = 5_000; options.MaxTypeCost = 5_000; options.EnforceCostLimits = true; }) .ModifyRequestOptions(opt => opt.AllowedBatchOperations = AllowedBatchOperations.None) .AllowIntrospection(builder.Environment.IsDevelopment()) .AddTypes(); var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); app.UseRateLimiter(); app.UseEndpoints(endpoints => { endpoints.MapGraphQL().RequireRateLimiting("graphql"); }); app.Run(); ``` -------------------------------- ### Using CreateStartCursor and CreateEndCursor Source: https://chillicream.com/docs/hotchocolate/v16/migrating/migrate-from-15-to-16 Use the new convenience extension methods `CreateStartCursor()` and `CreateEndCursor()` for creating boundary cursors, simplifying the process compared to manually calling `CreateCursor` with the first or last item. ```csharp -var startCursor = page.First is not null ? page.CreateCursor(page.First) : null; -var endCursor = page.Last is not null ? page.CreateCursor(page.Last) : null; +var startCursor = page.CreateStartCursor(); +var endCursor = page.CreateEndCursor(); ``` -------------------------------- ### Implement IMcpStorage for File-Based Tool Definitions Source: https://chillicream.com/docs/hotchocolate/v16/guides/mcp-adapter This C# code demonstrates how to implement the IMcpStorage interface to load GraphQL tool definitions from the file system. It parses a .graphql file and returns OperationToolDefinition objects. It also includes placeholders for prompt definitions and observable subscriptions. ```csharp using HotChocolate.Adapters.Mcp.Storage; public class FileMcpStorage : IMcpStorage { public async ValueTask> GetOperationToolDefinitionsAsync( CancellationToken cancellationToken = default) { // Load tool definitions from your preferred source. var graphql = await File.ReadAllTextAsync( "tools/get-books.graphql", cancellationToken); var document = Utf8GraphQLParser.Parse(graphql); return [new OperationToolDefinition(document)]; } public ValueTask> GetPromptDefinitionsAsync( CancellationToken cancellationToken = default) { return ValueTask.FromResult( Enumerable.Empty()); } // IMcpStorage also extends IObservable for both tool and // prompt events, enabling hot-reload when definitions change. public IDisposable Subscribe( IObserver observer) => /* your subscription logic */; public IDisposable Subscribe( IObserver observer) => /* your subscription logic */; } ``` -------------------------------- ### GraphQL GET Request with Variables Source: https://chillicream.com/docs/hotchocolate/v16/server/cache-control Shows a GraphQL GET request that includes variables for query parameters. ```http GET /graphql?query=query GetProducts($first:Int!){products(first:$first){nodes{name}}}&variables={"first":5} ``` -------------------------------- ### Client-side GraphQL Mutation Request Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/mutations An example of how a client would send a mutation request to add a book, specifying the input and the fields to return. ```graphql mutation { addBook(input: { title: "C# in depth" }) { book { id title } } } ``` -------------------------------- ### Enable Runtime XML Documentation in .csproj Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/documentation Configures the project file to generate an XML documentation file at build time, which Hot Chocolate can read at runtime. ```xml true $(NoWarn);1591 ``` -------------------------------- ### Persisted Operation GET Request with Variables Source: https://chillicream.com/docs/hotchocolate/v16/server/cache-control Demonstrates a persisted operation GET request where variables are passed as query parameters. ```http GET /graphql/persisted/GetProducts/123456789?variables={"first":5} ``` -------------------------------- ### Persisted Operation GET Request Source: https://chillicream.com/docs/hotchocolate/v16/server/cache-control Illustrates a GET request using a persisted operation identifier for a stable and short query string. ```http GET /graphql/persisted/GetProducts/123456789 ``` -------------------------------- ### SSE Wire Format Example Source: https://chillicream.com/docs/hotchocolate/v16/server/http-transport Illustrates the SSE wire format for delivering GraphQL results, including 'next' events for data and a 'complete' event to signal the end of the stream. ```text event: next data: {"data":{"onMessageReceived":{"body":"Hello"}}} event: next data: {"data":{"onMessageReceived":{"body":"World"}}} event: complete data: ``` -------------------------------- ### Minimal API Setup with GraphQL Commands Source: https://chillicream.com/docs/hotchocolate/v16/server/command-line Integrates the HotChocolate.AspNetCore.CommandLine package into a minimal API application. Ensure the exit code from `RunWithGraphQLCommandsAsync` is returned to signal command failures. ```csharp var builder = WebApplication.CreateBuilder(args); builder.AddGraphQL().AddQueryType(); var app = builder.Build(); app.MapGraphQL(); return await app.RunWithGraphQLCommandsAsync(args); ``` -------------------------------- ### HTTP GET Request URL Source: https://chillicream.com/docs/hotchocolate/v16/guides/private-api For HTTP GET requests with persisted operations, parameters like variables are included in the URL query string. ```http GET /graphql/persisted/0c95d31ca29272475bf837f944f4e513/GetProducts?variables={"first":10} ``` -------------------------------- ### Batched Collection DataLoader with QueryContext and Pagination Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/projections Example of a batched collection DataLoader for loading products by brand. It combines `QueryContext` with pagination arguments using `.With(query, s => s.AddAscending(t => t.Id))` and `.ToBatchPageAsync`. ```csharp [DataLoader] public static async Task>> GetProductsByBrandAsync( IReadOnlyList brandIds, PagingArguments pagingArgs, QueryContext query, CatalogContext context, CancellationToken cancellationToken) { brandIds = brandIds.EnsureOrdered(); return await context.Products .Where(t => brandIds.Contains(t.BrandId)) .With(query, s => s.AddAscending(t => t.Id)) .ToBatchPageAsync( t => t.BrandId, pagingArgs, cancellationToken); } ``` -------------------------------- ### GET User by ID Source: https://chillicream.com/docs/hotchocolate/v16/guides/openapi-adapter Retrieves a user by their ID using a GET request. The userId route parameter is mapped to the $userId GraphQL variable. ```APIDOC ## GET /users/{userId} ### Description Retrieves a user by their ID. ### Method GET ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (ID!) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **id** (ID) - The ID of the user. - **name** (string) - The name of the user. ``` -------------------------------- ### GET Requests Source: https://chillicream.com/docs/hotchocolate/v16/server/http-transport GraphQL requests can also be performed using the GET verb. Query parameters are used to send the query and variables, which can be beneficial for caching. ```APIDOC ## GET /graphql ### Description Handles GraphQL requests using the HTTP GET method. Query parameters are used for the query and variables, enabling request caching. ### Method GET ### Endpoint /graphql ### Parameters #### Query Parameters - **query** (string) - Required - The GraphQL query string. - **variables** (string) - Optional - A JSON string representing the variables for the query. - **operationName** (string) - Optional - The name of the operation to execute. ### Request Example ```http GET /graphql?query=query(%24id%3A%20ID!)%7Buser(id%3A%24id)%7Bname%7D%7D&variables=%7B%22id%22%3A%22QVBJcy5ndXJ1%22%7D HOST: foo.example ``` ### Response #### Success Response (200) - **data** (object) - The result of the GraphQL query execution. #### Response Example ```json { "data": { "user": { "name": "Jon Doe" } } } ``` ``` -------------------------------- ### Execute Test Queries and Get Result Source: https://chillicream.com/docs/hotchocolate/v16/guides/testing Use executor.ExecuteAsync() to run a GraphQL operation and get an IExecutionResult. Call ExpectOperationResult() for type-safe access to the result. ```csharp [Fact] public async Task Get_Product_Returns_Expected_Data() { // arrange var executor = await new ServiceCollection() .AddSingleton(new FakeCatalogService()) .AddGraphQL() .AddQueryType() .BuildRequestExecutorAsync(); // act var result = await executor.ExecuteAsync("{ product { name price } }"); // assert var operationResult = result.ExpectOperationResult(); Assert.Null(operationResult.Errors); } ``` -------------------------------- ### Configure AddGraphQL with Default Parameters Source: https://chillicream.com/docs/hotchocolate/v16/server/endpoints This snippet shows how to initialize AddGraphQL with default settings for request size and security. ```csharp builder.AddGraphQL( maxAllowedRequestSize: 20 * 1000 * 1024, // ~20 MB (default) disableDefaultSecurity: false); // default ``` -------------------------------- ### Allow Mutations via GET Requests Source: https://chillicream.com/docs/hotchocolate/v16/server/endpoints If GET requests are enabled, control allowed operations using AllowedGetOperations. By default, only queries are accepted. Set to QueryAndMutation to allow both. ```csharp endpoints.MapGraphQL().WithOptions(o => o.AllowedGetOperations = AllowedGetOperations.Query); ``` -------------------------------- ### Custom Naming Conventions: v11 vs v12 Source: https://chillicream.com/docs/hotchocolate/v16/migrating/migrate-from-11-to-12 The setup for custom naming conventions differs between v11 and v12, especially when XML documentation is enabled. V12 requires passing an IDocumentationProvider to the base class constructor. ```csharp public class CustomNamingConventions : DefaultNamingConventions { public CustomNamingConventions() : base() { } } services .AddGraphQLServer() .AddConvention(sp => new CustomNamingConventions()) // or .AddConvention(); ``` ```csharp public class CustomNamingConventions : DefaultNamingConventions { public CustomNamingConventions(IDocumentationProvider documentationProvider) : base(documentationProvider) { } } IReadOnlySchemaOptions capturedSchemaOptions; services .AddGraphQLServer() .ModifyOptions(opt => capturedSchemaOptions = opt) .AddConvention(sp => new CustomNamingConventions( new XmlDocumentationProvider( new XmlDocumentationFileResolver( capturedSchemaOptions.ResolveXmlDocumentationFileName), sp.GetApplicationService>() ?? new NoOpStringBuilderPool()))); ``` -------------------------------- ### Load Single Product with QueryContext Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/projections Load a single product by ID using a DataLoader that accepts a `QueryContext`. The `QueryContext` is applied to the DataLoader using `.With(query)`. ```csharp public class ProductService( CatalogContext context, IProductBatchingContext batchingContext) { public async Task GetProductByIdAsync( int id, QueryContext? query = null, CancellationToken cancellationToken = default) => await batchingContext.ProductById .With(query) .LoadAsync(id, cancellationToken); } ``` -------------------------------- ### GET User Details with Query Parameter Source: https://chillicream.com/docs/hotchocolate/v16/guides/openapi-adapter Retrieves user details, optionally including address information, using a GET request. The includeAddress variable is exposed as a query parameter. ```APIDOC ## GET /users/{userId}/details ### Description Retrieves user details, optionally including address information. The includeAddress variable is exposed as a query parameter. ### Method GET ### Endpoint /users/{userId}/details ### Parameters #### Path Parameters - **userId** (ID!) - Required - The ID of the user. #### Query Parameters - **includeAddress** (Boolean!) - Required - Whether to include address details. ### Response #### Success Response (200) - **id** (ID) - The ID of the user. - **name** (string) - The name of the user. - **address** (object) - The address of the user (conditionally included). - **street** (string) - The street name. ``` -------------------------------- ### Disable GET Requests for GraphQL Operations Source: https://chillicream.com/docs/hotchocolate/v16/server/endpoints Control whether the GraphQL server handles operations sent via the query string in an HTTP GET request. Set EnableGetRequests to false to disable. ```csharp endpoints.MapGraphQL().WithOptions(o => o.EnableGetRequests = false); ``` -------------------------------- ### Handling Nested Connections with Paging, Filtering, and Sorting Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/projections Shows how to combine `QueryContext` with `[UseConnection]`, `[UseFiltering]`, and `[UseSorting]` for nested connection fields, enabling pagination, filtering, and sorting on the returned products. ```csharp using HotChocolate.Data; using HotChocolate.Resolvers; using HotChocolate.Types; using System.Threading; using System.Threading.Tasks; [ObjectType] public static partial class BrandNode { [UseConnection(EnableRelativeCursors = true)] [UseFiltering] [UseSorting] public static async Task> GetProductsAsync( [Parent(requires: nameof(Brand.Id))] Brand brand, PagingArguments pagingArgs, QueryContext query, ProductService productService, CancellationToken cancellationToken) { var page = await productService.GetProductsByBrandAsync( brand.Id, pagingArgs, query, cancellationToken); return new PageConnection(page); } } ``` -------------------------------- ### Define a GET Endpoint with OpenAPI Adapter Source: https://chillicream.com/docs/hotchocolate/v16/guides/openapi-adapter Use the @http directive with method GET and a route that includes a parameter to fetch a user by ID. The route parameter {userId} maps to the GraphQL variable $userId. ```graphql "Fetches a user by their id" query GetUserById($userId: ID!) @http(method: GET, route: "/users/{userId}") { userById(id: $userId) { id name email } } ``` -------------------------------- ### C# Class for Implementation-First Product Type Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/object-types A C# class representing a Product, demonstrating how public properties are automatically mapped to GraphQL fields. ```csharp public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public bool InStock { get; set; } } ``` -------------------------------- ### Instantiating Page with Page.Create Source: https://chillicream.com/docs/hotchocolate/v16/migrating/migrate-from-15-to-16 Use the static `Page.Create` factory method instead of the constructor to create a new page instance. ```csharp -return new Page( - items, - hasNextPage: hasNext, - hasPreviousPage: false, - createCursor: product => CreateCursor(product), - totalCount: totalCount); +return Page.Create( + items, + hasNextPage: hasNext, + hasPreviousPage: false, + createCursor: product => CreateCursor(product), + totalCount: totalCount); ``` -------------------------------- ### Implement Custom OpenAPI Storage Source: https://chillicream.com/docs/hotchocolate/v16/guides/openapi-adapter Implement the IOpenApiDefinitionStorage interface to provide endpoint and fragment definitions to the adapter. This example shows parsing a GraphQL query and adding it as an OpenAPI definition. ```csharp using HotChocolate.Adapters.OpenApi; using HotChocolate.Adapters.OpenApi.Storage; using HotChocolate.Language; public class MyOpenApiStorage : IOpenApiDefinitionStorage { public ValueTask> GetDefinitionsAsync( CancellationToken cancellationToken = default) { var documents = new List(); var getUserDoc = Utf8GraphQLParser.Parse( """ query GetUser($userId: ID!) @http(method: GET, route: \"/users/{userId}\") { userById(id: $userId) { id name } } """); documents.Add(OpenApiDefinitionParser.Parse(getUserDoc)); return ValueTask.FromResult>( documents); } // IOpenApiDefinitionStorage also extends IObservable, enabling // hot-reload when definitions change. public IDisposable Subscribe( IObserver observer) => /* your subscription logic */; } ``` -------------------------------- ### Run Server with Developer Commands Source: https://chillicream.com/docs/hotchocolate/v16/get-started-with-graphql-in-net-core Configures the application to run with GraphQL developer commands, such as schema export. ```csharp app.RunWithGraphQLCommands(args) ``` -------------------------------- ### GraphQL Query Example Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/projections A GraphQL query specifying the fields 'email' and 'address.street' for user data. ```graphql { users { email address { street } } } ``` -------------------------------- ### Registering Intermediate Interfaces Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/interfaces Example of registering intermediate interfaces explicitly when they are not directly returned by a resolver. ```C# builder .AddGraphQL() .AddType() .AddType(); ``` -------------------------------- ### Implement Custom ConnectionBase Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/pagination Inherit directly from `ConnectionBase` for full control over edge and page info construction. This requires defining custom logic for edges and page info. ```csharp public class ProductConnection : ConnectionBase { private readonly Page _page; private ConnectionPageInfo? _pageInfo; private ProductsEdge[]? _edges; public ProductConnection(Page page) { _page = page; } public override IReadOnlyList? Edges { get { if (_edges is null) { var entries = _page.Entries; var edges = new ProductsEdge[entries.Length]; for (var i = 0; i < entries.Length; i++) { edges[i] = new ProductsEdge(_page, entries[i]); } _edges = edges; } return _edges; } } public IReadOnlyList? Nodes => _page; public override ConnectionPageInfo PageInfo { get { if (_pageInfo is null) { var startCursor = _page.CreateStartCursor(); var endCursor = _page.CreateEndCursor(); _pageInfo = new ConnectionPageInfo( _page.HasNextPage, _page.HasPreviousPage, startCursor, endCursor); } return _pageInfo; } } public int TotalCount => _page.TotalCount ?? 0; } ``` -------------------------------- ### MapGraphQL Source: https://chillicream.com/docs/hotchocolate/v16/server/endpoints Configures the default GraphQL endpoint with specific options, disabling GET requests and the GraphQL tool. ```APIDOC ## MapGraphQL ### Description Configures the default GraphQL endpoint with specific options, disabling GET requests and the GraphQL tool. ### Method POST (Implicit, as MapGraphQL typically handles POST requests for GraphQL operations) ### Endpoint /graphql ### Parameters #### Request Body (Not explicitly defined in the example, but typically a GraphQL query) ### Request Example ```csharp app.MapGraphQL().WithOptions(o => { o.EnableGetRequests = false; o.AllowedGetOperations = AllowedGetOperations.Query; o.Tool.Enable = false; }); ``` ### Response (Not explicitly defined in the example, but typically a GraphQL response) ``` -------------------------------- ### MapGraphQLHttp Source: https://chillicream.com/docs/hotchocolate/v16/server/endpoints Configures the GraphQL server to be available via HTTP. Supports GET and POST requests by default. ```APIDOC ## MapGraphQLHttp ### Description Exposes your GraphQL server via an HTTP endpoint. You can issue HTTP GET/POST requests against this endpoint. ### Method `MapGraphQLHttp(string path)` ### Endpoint `/graphql/http` (configurable) ### Parameters #### Path Parameters - **path** (string) - Required - The URL path for the GraphQL HTTP endpoint. ### Request Example ```csharp app.UseEndpoints(endpoints => { endpoints.MapGraphQLHttp("/graphql/http"); }); ``` ### Response #### Success Response (200) - **GraphQL Response** (object) - The result of the GraphQL query. ### Options #### WithOptions Allows per-endpoint overrides using `WithOptions`. ```csharp endpoints.MapGraphQLHttp("/graphql/http").WithOptions(o => o.EnableGetRequests = false); ``` **Note**: `Tool` and `EnableSchemaRequests` options are not applicable here. ``` -------------------------------- ### ModifyServerOptions Source: https://chillicream.com/docs/hotchocolate/v16/server/options Control HTTP-level behavior, including GET requests, batching, multipart requests, and schema retrieval. ```APIDOC ## ModifyServerOptions ### Description Controls HTTP-level behavior such as GET requests, batching, multipart requests, and schema retrieval. ### Method `ModifyServerOptions` ### Parameters #### Server Options - **AllowedGetOperations** (`AllowedGetOperations`) - Optional - Controls which operation types are allowed via HTTP GET. Values: `None`, `Query`, `Mutation`, `Subscription`, `QueryAndMutation`, `All`. - **EnableGetRequests** (`bool`) - Optional - Allows GraphQL queries over HTTP GET. - **EnableMultipartRequests** (`bool`) - Optional - Allows multipart HTTP requests (file uploads). - **EnableSchemaRequests** (`bool`) - Optional - Allows schema SDL downloads. - **EnableSchemaFileSupport** (`bool`) - Optional - Allows the schema SDL to be served as a file download. - **EnforceGetRequestsPreflightHeader** (`bool`) - Optional - Requires a preflight header on GET requests for CSRF protection. - **EnforceMultipartRequestsPreflightHeader** (`bool`) - Optional - Requires a preflight header on multipart requests for CSRF protection. - **Batching** (`AllowedBatching`) - Optional - Controls which batching modes are allowed. Use `AllowedBatching.All` to enable. - **MaxBatchSize** (`int`) - Optional - Maximum number of operations in a single batch. Set to `0` for unlimited. - **Sockets** (`GraphQLSocketOptions`) - Optional - WebSocket transport options. - **Tool** (`NitroAppOptions`) - Optional - Nitro IDE tool options. ### Request Example ```csharp builder .AddGraphQL() .ModifyServerOptions(o => { o.EnableGetRequests = true; o.EnableMultipartRequests = true; o.Batching = AllowedBatching.All; o.MaxBatchSize = 50; o.EnableSchemaRequests = true; }); ``` ### Per-Endpoint Overrides Per-endpoint overrides are still supported through `WithOptions` on the endpoint builder: ### Request Example ```csharp app.MapGraphQL().WithOptions(o => o.EnableGetRequests = false); ``` ``` -------------------------------- ### After: QueryContext-based Projection Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/projections Demonstrates the new approach using `QueryContext` for projections, including explicit data pipeline control. ```csharp [QueryType] public static partial class ProductQueries { [UseConnection] [UseFiltering] [UseSorting] public static async Task GetProductsAsync( PagingArguments pagingArgs, QueryContext query, CatalogContext db, CancellationToken cancellationToken) { var page = await db.Products .With(query) .ToPageAsync(pagingArgs, cancellationToken); return new ProductConnection(page); } } ``` -------------------------------- ### Print Method Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/integrations Returns a string representation of the executable in its current state, useful for debugging. ```csharp string Print(); ``` -------------------------------- ### Before: Attribute-based Projection Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/projections Illustrates the previous approach using the `[UseProjection]` attribute for defining query projections. ```csharp [QueryType] public static partial class ProductQueries { [UsePaging] [UseProjection] [UseFiltering] [UseSorting] public static IQueryable GetProducts(CatalogContext db) => db.Products; } ``` -------------------------------- ### Install Hot Chocolate Diagnostics Package Source: https://chillicream.com/docs/hotchocolate/v16/server/instrumentation Add the HotChocolate.Diagnostics NuGet package to your project to enable DataLoader instrumentation. ```bash dotnet add package HotChocolate.Diagnostics ``` -------------------------------- ### C# Query with Returns and Errors XML Documentation Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/documentation Demonstrates advanced XML documentation with and tags for detailed field descriptions in the GraphQL schema. ```csharp [QueryType] public static partial class UserQueries { /// /// Finds a user by their unique username. /// /// The username to search for. /// The matching user, or null if not found. /// /// The caller does not have permission to search users. /// public static User? GetUser(string username, UserService users) => users.FindByName(username); ``` -------------------------------- ### Add HotChocolate.Data Package Source: https://chillicream.com/docs/hotchocolate/v16/fetching-data/filtering Install the necessary package for filtering functionality. Ensure all HotChocolate packages share the same version. ```bash dotnet add package HotChocolate.Data ``` -------------------------------- ### ConfigureServices: New HttpRequestInterceptor Registration Source: https://chillicream.com/docs/hotchocolate/v16/migrating/migrate-from-10-to-11 Demonstrates registering the new `IHttpRequestInterceptor` within the `AddGraphQLServer` chain. ```csharp services.AddGraphQLServer() ... .AddHttpRequestInterceptor( (context, executor, builder, ct) => { // your code }); ``` -------------------------------- ### Implement Custom Warmup Task Source: https://chillicream.com/docs/hotchocolate/v16/server/warmup Implement the `IRequestExecutorWarmupTask` interface for more control over warmup behavior. The `ApplyOnlyOnStartup` property determines if the task runs only at startup or also on runtime schema rebuilds. ```csharp builder .AddGraphQL() .AddWarmupTask(); public class MyWarmupTask : IRequestExecutorWarmupTask { public bool ApplyOnlyOnStartup => false; public async Task WarmupAsync( IRequestExecutor executor, CancellationToken cancellationToken) { // Your warmup logic here await executor.ExecuteAsync("{ __typename }", cancellationToken); } } ``` -------------------------------- ### MapGraphQLHttp Source: https://chillicream.com/docs/hotchocolate/v16/server/endpoints Configures a specific HTTP GraphQL endpoint, disabling multipart requests and enforcing a preflight header for GET requests. ```APIDOC ## MapGraphQLHttp ### Description Configures a specific HTTP GraphQL endpoint, disabling multipart requests and enforcing a preflight header for GET requests. ### Method POST (Implicit, as MapGraphQLHttp typically handles POST requests for GraphQL operations) ### Endpoint /graphql/http ### Parameters #### Request Body (Not explicitly defined in the example, but typically a GraphQL query) ### Request Example ```csharp app.MapGraphQLHttp("/graphql/http").WithOptions(o => { o.EnableMultipartRequests = false; o.EnforceGetRequestsPreflightHeader = true; }); ``` ### Response (Not explicitly defined in the example, but typically a GraphQL response) ``` -------------------------------- ### GetUserById Source: https://chillicream.com/docs/hotchocolate/v16/guides/openapi-adapter Defines a GET endpoint to fetch a user by their ID. The route parameter {userId} maps to the $userId GraphQL variable. ```APIDOC ## GET /users/{userId} ### Description Fetches a user by their id. ### Method GET ### Endpoint /users/{userId} ### Parameters #### Path Parameters - **userId** (ID!) - Required - The ID of the user to fetch. ### Response #### Success Response (200) - **id** (ID) - The user's ID. - **name** (string) - The user's name. - **email** (string) - The user's email. ``` -------------------------------- ### Configure NitroAppOptions: Enable Source: https://chillicream.com/docs/hotchocolate/v16/server/endpoints Use `NitroAppOptions` to configure Nitro. Setting `o.Enable = false` controls whether Nitro is served. ```csharp endpoints.MapNitroApp("/ui").WithOptions(o => o.Enable = false); ``` -------------------------------- ### Implementing Custom Error Type Source: https://chillicream.com/docs/hotchocolate/v16/guides/error-handling Provides an example of a C# class that implements the properties required by the custom error interface. ```csharp public class UserNameTakenError { public UserNameTakenError(UserNameTakenException ex) { Message = $"The username '{ex.Username}' is already taken."; Code = "USERNAME_TAKEN"; } public string Message { get; } public string Code { get; } } ``` -------------------------------- ### GraphQL query example for Any input type Source: https://chillicream.com/docs/hotchocolate/v16/migrating/migrate-from-15-to-16 This GraphQL query demonstrates calling a field that accepts an `Any`-typed input. The comment indicates the expected return type change from v15 to v16. ```graphql query { foo(input: { key: "value" }) # Now returns: "JsonElement" # Previously (v15): "Dictionary`2" } ``` -------------------------------- ### Client Query for a Union Type Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/unions Example of a client query selecting fields from a union type using inline fragments. ```graphql { content { ... on TextContent { text } ... on ImageContent { imageUrl } } } ``` -------------------------------- ### Registering Application Services for Schema Components Source: https://chillicream.com/docs/hotchocolate/v16/migrating/migrate-from-15-to-16 Use `AddApplicationService()` to make application services available to schema services like diagnostic event listeners. This ensures proper resolution during schema initialization. ```csharp builder.Services.AddSingleton(); builder.AddGraphQL() .AddApplicationService() // either .AddDiagnosticEventListener(); // or .AddDiagnosticEventListener(sp => new MyDiagnosticEventListener(sp.GetRequiredService())); public class MyDiagnosticEventListener(MyService service) : ExecutionDiagnosticEventListener; ``` ```csharp builder.Services.AddLogging(); builder.AddGraphQL() .AddApplicationService>() // either .AddDiagnosticEventListener(); // or .AddDiagnosticEventListener(sp => new MyLoggingDiagnosticEventListener(sp.GetRequiredService>())); public class MyLoggingDiagnosticEventListener(ILogger logger) : ExecutionDiagnosticEventListener; ``` -------------------------------- ### Add NodaTime Scalars Package Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/scalars Install the HotChocolate.Types.NodaTime package using the .NET CLI. Ensure all HotChocolate packages share the same version. ```bash dotnet add package HotChocolate.Types.NodaTime ``` -------------------------------- ### Add Additional Scalars Package Source: https://chillicream.com/docs/hotchocolate/v16/defining-a-schema/scalars Install the HotChocolate.Types.Scalars package using the .NET CLI. Ensure all HotChocolate packages share the same version. ```bash dotnet add package HotChocolate.Types.Scalars ``` -------------------------------- ### Register Warmup Tasks Source: https://chillicream.com/docs/hotchocolate/v16/guides/performance Register warmup tasks to pre-populate in-memory caches before the server starts accepting traffic. Use `MarkAsWarmupRequest()` to populate caches without executing the operation, avoiding side effects during startup. Include the operation name as it's part of the cache key. ```csharp builder .AddGraphQL() .AddWarmupTask(async (executor, cancellationToken) => { var request = OperationRequestBuilder.New() .SetDocument("query GetProducts { products(first: 10) { nodes { id name } } }") .SetOperationName("GetProducts") .MarkAsWarmupRequest() .Build(); await executor.ExecuteAsync(request, cancellationToken); }); ``` -------------------------------- ### Configure MapGraphQLHttp Endpoint Options Source: https://chillicream.com/docs/hotchocolate/v16/server/endpoints Customize `MapGraphQLHttp` options, such as disabling multipart requests or enforcing preflight headers for GET requests. ```csharp app.MapGraphQLHttp("/graphql/http").WithOptions(o => { o.EnableMultipartRequests = false; o.EnforceGetRequestsPreflightHeader = true; }); ```