GraphQlClientGenerator 0.9.31

dotnet add package GraphQlClientGenerator --version 0.9.31
 
NuGet\Install-Package GraphQlClientGenerator -Version 0.9.31
 
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="GraphQlClientGenerator" Version="0.9.31" />
 
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GraphQlClientGenerator" Version="0.9.31" />
 
Directory.Packages.props
<PackageReference Include="GraphQlClientGenerator" />
 
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add GraphQlClientGenerator --version 0.9.31
 
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: GraphQlClientGenerator, 0.9.31"
 
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package GraphQlClientGenerator@0.9.31
 
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=GraphQlClientGenerator&version=0.9.31
 
Install as a Cake Addin
#tool nuget:?package=GraphQlClientGenerator&version=0.9.31
 
Install as a Cake Tool
The NuGet Team does not provide support for this client. Please contact its maintainers for support.

GraphQL C# client generator

Build NuGet Badge

This simple console app generates C# GraphQL query builder and data classes for simple, compiler checked, usage of a GraphQL API.


Generator app usage

GraphQlClientGenerator.Console --serviceUrl <GraphQlServiceUrl> --outputPath <TargetPath> --namespace <TargetNamespace> [--header <header value>]

Nuget package

Installation:

Install-Package GraphQlClientGenerator

dotnet tool

dotnet tool install GraphQlClientGenerator.Tool --global
graphql-client-generator --serviceUrl <GraphQlServiceUrl> --outputPath <TargetPath> --namespace <TargetNamespace> [--header <header value>]

Code

Code example for class generation:

var schema = await GraphQlHttpUtilities.RetrieveSchema("https://my-graphql-api/gql");
var generator = new GraphQlGenerator();
var generatedClasses = generator.GenerateFullClientCSharpFile(schema);

or using full blown setup:

var schema = await GraphQlHttpUtilities.RetrieveSchema("https://my-graphql-api/gql");
var configuration = new GraphQlGeneratorConfiguration { TargetNamespace = "MyGqlApiClient", ... };
var generator = new GraphQlGenerator(configuration);
var builder = new StringBuilder();
using var writer = new StringWriter(builder);
var generationContext = new SingleFileGenerationContext(schema, writer) { LogMessage = Console.WriteLine };
generator.Generate(generationContext);
var csharpCode = builder.ToString();

C# 9 source generator

C# 9 introduced source generators that can be attached to compilation process. Generated classes will be automatically included in project.

Project file example:

<PropertyGroup>
 <OutputType>Exe</OutputType>
 <TargetFramework>net9.0</TargetFramework>
 
 <GraphQlClientGenerator_ServiceUrl>https://api.tibber.com/v1-beta/gql</GraphQlClientGenerator_ServiceUrl>
 
 <GraphQlClientGenerator_Namespace>$(RootNamespace)</GraphQlClientGenerator_Namespace>
 <GraphQlClientGenerator_CustomClassMapping>Consumption:ConsumptionEntry|Production:ProductionEntry|RootMutation:TibberMutation|Query:Tibber</GraphQlClientGenerator_CustomClassMapping>
 
 
 
</PropertyGroup>
<ItemGroup>
 <PackageReference Include="GraphQlClientGenerator" Version="0.9.*" IncludeAssets="analyzers" />
 
 
 
 
 <CompilerVisibleProperty Include="GraphQlClientGenerator_ServiceUrl" />
 <CompilerVisibleProperty Include="GraphQlClientGenerator_Namespace" />
 
 
</ItemGroup>

Query builder usage

var builder =
 new QueryQueryBuilder()
 .WithMe(
 new MeQueryBuilder()
 .WithAllScalarFields()
 .WithHome(
 new HomeQueryBuilder()
 .WithAllScalarFields()
 .WithSubscription(
 new SubscriptionQueryBuilder()
 .WithStatus()
 .WithValidFrom())
 .WithSignupStatus(
 new SignupStatusQueryBuilder().WithAllFields())
 .WithDisaggregation(
 new DisaggregationQueryBuilder().WithAllFields()),
 "b420001d-189b-44c0-a3d5-d62452bfdd42")
 .WithEnergyStatements ("2016-06", "2016-10"));
var query = builder.Build(Formatting.Indented);

results into

query {
 me {
 id
 firstName
 lastName
 fullName
 ssn
 email
 language
 tone
 home (id: "b420001d-189b-44c0-a3d5-d62452bfdd42") {
 id
 avatar
 timeZone
 subscription {
 status
 validFrom
 }
 signupStatus {
 registrationStartedTimestamp
 registrationCompleted
 registrationCompletedTimestamp
 checkCurrentSupplierPassed
 supplierSwitchConfirmationPassed
 startDatePassed
 firstReadingReceived
 firstBillingDone
 firstBillingTimestamp
 }
 disaggregation {
 year
 month
 fixedConsumptionKwh
 fixedConsumptionKwhPercent
 heatingConsumptionKwh
 heatingConsumptionKwhPercent
 behaviorConsumptionKwh
 behaviorConsumptionKwhPercent
 }
 }
 energyStatements(from: "2016-06", to: "2016-10") 
 }
}

Mutation

var mutation =
 new MutationQueryBuilder()
 .WithUpdateHome(
 new HomeQueryBuilder().WithAllScalarFields(),
 new UpdateHomeInput { HomeId = Guid.Empty, AppNickname = "My nickname", Type = HomeType.House, NumberOfResidents = 4, Size = 160, AppAvatar = HomeAvatar.Floorhouse1, PrimaryHeatingSource = HeatingSource.Electricity }
 )
 .Build(Formatting.Indented, 2);

result:

mutation {
 updateHome (input: {
 homeId: "00000000-0000-0000-0000-000000000000"
 appNickname: "My nickname"
 appAvatar: FLOORHOUSE1
 size: 160
 type: HOUSE
 numberOfResidents: 4
 primaryHeatingSource: ELECTRICITY
 }) {
 id
 timeZone
 appNickname
 appAvatar
 size
 type
 numberOfResidents
 primaryHeatingSource
 hasVentilationSystem
 }
}

Field exclusion

Sometimes there is a need to select almost all fields of a queried object except few. In that case Except methods can be used often in conjunction with WithAllFields or WithAllScalarFields.

new ViewerQueryBuilder()
 .WithHomes(
 new HomeQueryBuilder()
 .WithAllScalarFields()
 .ExceptPrimaryHeatingSource()
 .ExceptMainFuseSize()
 )
 .Build(Formatting.Indented);

result:

query {
 homes {
 id
 timeZone
 appNickname
 appAvatar
 size
 type
 numberOfResidents
 hasVentilationSystem
 }
}

Aliases

Queried fields can be freely renamed to match target data classes using GraphQL aliases.

new ViewerQueryBuilder("MyQuery")
 .WithHome(
 new HomeQueryBuilder()
 .WithType()
 .WithSize()
 .WithAddress(new AddressQueryBuilder().WithAddress1("primaryAddressText").WithCountry(), "primaryAddress"),
 Guid.NewGuid(),
 "primaryHome")
 .WithHome(
 new HomeQueryBuilder()
 .WithType()
 .WithSize()
 .WithAddress(new AddressQueryBuilder().WithAddress1("secondaryAddressText").WithCountry(), "secondaryAddress"),
 Guid.NewGuid(),
 "secondaryHome")
 .Build(Formatting.Indented);

result:

query MyQuery {
 primaryHome: home (id: "120efe4a-6839-45fc-beed-27455d29212f") {
 type
 size
 primaryAddress: address {
 primaryAddressText: address1
 country
 }
 }
 secondaryHome: home (id: "0c735830-be56-4a3d-a8cb-d0189037f221") {
 type
 size
 secondaryAddress: address {
 secondaryAddressText: address1
 country
 }
 }
}

Query parameters

var homeIdParameter = new GraphQlQueryParameter<Guid>("homeId", "ID", homeId);
var builder =
 new TibberQueryBuilder()
 .WithViewer(
 new ViewerQueryBuilder()
 .WithHome(new HomeQueryBuilder().WithAllScalarFields(), homeIdParameter)
 )
 .WithParameter(homeIdParameter);

result:

query ($homeId: ID = "c70dcbe5-4485-4821-933d-a8a86452737b") {
 viewer{
 home(id: $homeId) {
 id
 timeZone
 appNickname
 appAvatar
 size
 type
 numberOfResidents
 primaryHeatingSource
 hasVentilationSystem
 mainFuseSize
 }
 }
}

Directives

var includeDirectParameter = new GraphQlQueryParameter<bool>("direct", "Boolean", true);
var includeDirective = new IncludeDirective(includeDirectParameter);
var skipDirective = new SkipDirective(true);
var builder =
 new TibberQueryBuilder()
 .WithViewer(
 new ViewerQueryBuilder()
 .WithName(include: includeDirective)
 .WithAccountType(skip: skipDirective)
 .WithHomes(new HomeQueryBuilder().WithId(), skip: skipDirective)
 )
 .WithParameter(includeDirectParameter);

result:

query (
 $direct: Boolean = true) {
 viewer {
 name @include(if: $direct)
 accountType @skip(if: true)
 homes @skip(if: true) {
 id
 }
 }
}

Inline fragments

var builder =
 new RootQueryBuilder("InlineFragments")
 .WithUnion(
 new UnionTypeQueryBuilder()
 .WithConcreteType1Fragment(new ConcreteType1QueryBuilder().WithAllFields())
 .WithConcreteType2Fragment(new ConcreteType2QueryBuilder().WithAllFields())
 .WithConcreteType3Fragment(
 new ConcreteType3QueryBuilder()
 .WithName()
 .WithConcreteType3Field("alias")
 .WithFunction("my value", "myResult1")
 )
 )
 .WithInterface(
 new NamedTypeQueryBuilder()
 .WithName()
 .WithConcreteType3Fragment(
 new ConcreteType3QueryBuilder()
 .WithName()
 .WithConcreteType3Field()
 .WithFunction("my value")
 ),
 Guid.Empty
 );

result:

query InlineFragments {
 union {
 __typename
 ... on ConcreteType1 {
 name
 concreteType1Field
 }
 ... on ConcreteType2 {
 name
 concreteType2Field
 }
 ... on ConcreteType3 {
 __typename
 name
 alias: concreteType3Field
 myResult1: function(value: "my value")
 }
 }
 interface(parameter: "00000000-0000-0000-0000-000000000000") {
 name
 ... on ConcreteType3 {
 __typename
 name
 concreteType3Field
 function(value: "my value")
 }
 }
}

Custom scalar types

GraphQL supports custom scalar types. By default these are mapped to object type. To ensure appropriate .NET types are generated for data class properties custom mapping interface can be used:

var configuration = new GraphQlGeneratorConfiguration();
configuration.ScalarFieldTypeMappingProvider = new MyCustomScalarFieldTypeMappingProvider();
public class MyCustomScalarFieldTypeMappingProvider : IScalarFieldTypeMappingProvider
{
 public ScalarFieldTypeDescription GetCustomScalarFieldType(ScalarFieldTypeProviderContext context)
 {
 var unwrappedType = context.FieldType.UnwrapIfNonNull();
 return
 unwrappedType.Name switch
 {
 "Byte" => new ScalarFieldTypeDescription { NetTypeName = GenerationContext.GetNullableNetTypeName(context, "byte", false), FormatMask = null },
 "DateTime" => new ScalarFieldTypeDescription { NetTypeName = GenerationContext.GetNullableNetTypeName(context, "DateTime", false), FormatMask = null },
 _ => DefaultScalarFieldTypeMappingProvider.GetFallbackFieldType(context)
 };
 }
}

Generated class example:

public class OrderType
{
 public DateTime? CreatedDateTimeUtc { get; set; }
 public byte? SomeSmallNumber { get; set; }
}

vs.

public class OrderType
{
 public object CreatedDateTimeUtc { get; set; }
 public object SomeSmallNumber { get; set; }
}

C# 9 source generator custom types

Source generator supports RegexScalarFieldTypeMappingProvider rules using JSON configuration file. Example:

[
 {
 "patternBaseType": ".+",
 "patternValueType": ".+",
 "patternValueName": "^((timestamp)|(.*(f|F)rom)|(.*(t|T)o))$",
 "netTypeName": "DateTimeOffset",
 "isReferenceType": false,
 "formatMask": "O"
 }
]

All pattern values must be specified. Null values are not accepted.

The file must be named RegexScalarFieldTypeMappingProvider.gql.config.json and included as additional file.

<ItemGroup>
 <AdditionalFiles Include="RegexScalarFieldTypeMappingProvider.gql.config.json" CacheObjects="true" />
</ItemGroup>
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed.
.NET Core netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed.
.NET Standard netstandard2.0 is compatible. netstandard2.1 was computed.
.NET Framework net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed.
MonoAndroid monoandroid was computed.
MonoMac monomac was computed.
MonoTouch monotouch was computed.
Tizen tizen40 was computed. tizen60 was computed.
Xamarin.iOS xamarinios was computed.
Xamarin.Mac xamarinmac was computed.
Xamarin.TVOS xamarintvos was computed.
Xamarin.WatchOS xamarinwatchos was computed.
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on GraphQlClientGenerator:

Package Downloads
Distancify.Migrations.Litium

This project contains a fluid API to aid in generating data in Litium together with Distancify.Migrations.

Blauhaus.Graphql.Generator

Package Description

Distancify.LitiumAddOns.Foundation

Base class library for Distancify Litium Add-ons

XRay.ClientV2

Package for testing and using XRay KYC/B services

WaveApps.GraphQLBuilder

A C# GraphQL query builder for waveapps.com.

GitHub repositories (1)

Showing the top 1 popular GitHub repositories that depend on GraphQlClientGenerator:

Repository Stars
RatScanner/RatScanner
Rat Scanner a helpful tool for Escape from Tarkov.
Version Downloads Last Updated
0.9.31 6,273 1/16/2026
0.9.30 5,426 10/19/2025
0.9.29 20,173 4/24/2025
0.9.27 6,490 1/25/2025
0.9.26 349 1/25/2025
0.9.25 2,159 1/1/2025
0.9.24 22,666 10/20/2024
0.9.23 23,588 9/1/2024
0.9.22 7,176 8/4/2024
0.9.21 6,883 7/8/2024
0.9.20 1,531 5/29/2024
0.9.19 6,197 3/30/2024
0.9.18 17,482 1/20/2024
0.9.17 1,055 1/1/2024
0.9.15 12,323 7/29/2023
Loading failed

include "IsDeprecated" into GraphQlFieldMetadata
include GraphQl.NET default scalars into default scalar field type mapping provider
improve generation customizations