SAHB.GraphQLClient 1.1.1

Suggested Alternatives

SAHB.GraphQL.Client

There is a newer version of this package available.
See the version list below for details.
dotnet add package SAHB.GraphQLClient --version 1.1.1
NuGet\Install-Package SAHB.GraphQLClient -Version 1.1.1
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="SAHB.GraphQLClient" Version="1.1.1" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add SAHB.GraphQLClient --version 1.1.1
#r "nuget: SAHB.GraphQLClient, 1.1.1"
#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.
// Install SAHB.GraphQLClient as a Cake Addin
#addin nuget:?package=SAHB.GraphQLClient&version=1.1.1

// Install SAHB.GraphQLClient as a Cake Tool
#tool nuget:?package=SAHB.GraphQLClient&version=1.1.1

SAHB.GraphQLClient

Query HTTP api using GraphQL. The client recieves a model as typeparameter and then queries the GraphQL api and deserilize the result.

Nuget

The library can be found on NuGet with the package name SAHB.GraphQLClient. For pre release builds the NuGet package feed from AppVeyor can be used.

It can be installed using the following command in the Package Manager Console.

Install-Package SAHB.GraphQLClient

Examples

An example for the Starwars API.

// TODO: Use dependency injection (services.AddGraphQLHttpClient()) (IServiceCollection)
// Initilize GraphQLClient
IGraphQLHttpClient client = GraphQLHttpClient.Default();

// Get response from url
var response = await client.Query<Query>("https://mpjk0plp9.lp.gql.zone/graphql");

// Get name etc.
Console.WriteLine(response.Hero.Name);

// The query class used is
public class Query
{
   public CharacterOrPerson Hero { get; set; }
}
        
public class CharacterOrPerson
{
   public string Name { get; set; }
   public IEnumerable<Friend> Friends { get; set; }
}

public class Friend
{
   public string Name { get; set; }
}

The following code requests the endpoint with the following query

{"query":"query{hero{name friends{name}}}"} 

The following using statements is required

using SAHB.GraphQLClient;
using SAHB.GraphQLClient.Extentions;

More examples can be found in Examples.md

Renaming of a field

To rename a field name use the attribute GraphQLFieldNameAttribute on the class or property which you want to remap. For example request the field Fullname on the property Name do the follwing.

public class Friend
{
   [GraphQLFieldName("fullname")
   public string Name { get; set; }
}

This will generate the query:

{"query":"query{hero{Name:fullname"}

Note: For generating this you need to remember to add a extra Query class

public class Query
{
   public Hero Hero { get; set; }
}

Ignoring a field

To ignore a field use the attribute GraphQLFieldIgnoreAttribute on the class or property which you want to ignore. For example:

public class Hero
{
   public string Name { get; set; }

   [GraphQLFieldIgnore]
   public string IgnoredField { get; set; }
}

Example for ignoring a class

public class Hero
{
   public string Name { get; set; }

   public IgnoredClass IgnoredField { get; set; }
}

[GraphQLFieldIgnore]
public class IgnoredClass
{
   public string SomeProperty { get; set; }
}

This will generate the query:

{"query":"query{hero{name}}"}

Note: For generating this you need to remember to add a extra Query class

public class Query
{
   public Hero Hero { get; set; }
}

Arguments

It's also possible to add arguments to queries. This can be done with the attribute GraphQLArgumentAttribute. This attribute takes 3 arguments where the first is argument name used on the GraphQL server. The second is the argument type, for example String. The third argument is the varible name which should be used when the query is requested.

public class Query
{
   [GraphQLArgumentAttribute("argumentName", "ArgumentType", "variableName")]
   public Hero Hero { get; set; }
}

The client is requested as shown here:

var response = await client.Query<Query>("https://mpjk0plp9.lp.gql.zone/graphql", 
   arguments: new GraphQLQueryArgument("variableName", "valueToBeSent"});

This will generate the query (Hero contains here only the Name property):

{"query":"query{hero(argumentName:\"valueToBeSent\"){name}}"}

Merging multiple queries (batching)

The client supports merging multiple queries into one single query and returning the result for each query separate. This could reduce the number of request needed to a single server.

// Create batch
var batch = client.CreateBatch("https://mpjk0plp9.lp.gql.zone/graphql");

// Create two requests in the batch
var queryId1000 = batch.Query<HumanQuery>(new GraphQLQueryArgument("humanID", "1000"));
var queryId1001 = batch.Query<HumanQuery>(new GraphQLQueryArgument("humanID", "1001"));

// Execute the batch
var queryId1000Result = await queryId1000.Execute();
var queryId1001Result = await queryId1001.Execute();

// Get result
Console.WriteLine(queryId1000Result.Human.Name);
Console.WriteLine(queryId1001Result.Human.Name);

// Class used
public class HumanQuery
{
	[GraphQLArguments("id", "ID!", "humanID")]
	public CharacterOrPerson Human { get; set; }
}

The following methods will generate the query:

{"query":"query{batch0_Human:human(id:\"1000\"){Name:name Friends:friends{Name:name}} batch1_Human:human(id:\"1001\"){Name:name Friends:friends{Name:name}}}"}

Note: when Execute is called on one result the batch does not support adding more request to it and will therefore throw if you try to add more requests to it. For example:

// Create a requests in a batch and execute it
var batch = client.CreateBatch("https://mpjk0plp9.lp.gql.zone/graphql");
var queryId1000 = batch.Query<HumanQuery>(new GraphQLQueryArgument("humanID", "1000"));
var queryId1000Result = await queryId1000.Execute();

// Get another request
// This will throw a GraphQLBatchAlreadyExecutedException
var queryId1001 = batch.Query<HumanQuery>(new GraphQLQueryArgument("humanID", "1001"));

Generate GraphQL query without using C# model

It's also possible to generate a GraphQL query without using a C# model. The following example shows how to generate the query from the first example for the Starwars api (without the aliases).

// Get response from url using a generated object
var query = client.CreateQuery(builder => 
	builder.Field("hero", 
		hero => 
			hero
				.Field("name")
				.Field("friends", 
					friends => 
						friends.Field("name"))),
	"https://mpjk0plp9.lp.gql.zone/graphql");
var builderResponse = await query.Execute();
Console.WriteLine(builderResponse["hero"]["name"].Value);

The generated query is the following.

{"query":"query{hero{name friends{name}}}"}

To include the aliases the following code can be used.

var query = client.CreateQuery(builder => 
	builder.Field("hero", 
		hero => 
			hero
				.Field("name")
				.Field("friends", 
					friends => 
						friends.Alias("MyFriends").Field("name"))),
	"https://mpjk0plp9.lp.gql.zone/graphql");
var builderResponse = await query.Execute();
Console.WriteLine(builderResponse["Hero"]["Name"].Value);

The query generated is the following which is equal to the query generated in the first example:

{"query":"query{hero{name MyFriends:friends{name}}}"}

The builder supports fields, subfields, alias and arguments.

Note: If the alias and field name is case insensitive equal the alias is ignored

Execute custom GraphQL query

If a custom GraphQL query is required to be executed it's also possible using the IGraphQLHttpExecutor. An example is shown here:

IGraphQLHttpExecutor executor = new GraphQLHttpExecutor();
var result = await executor.ExecuteQuery<HeroQuery>(@"{""query"":""query{Hero:hero{Name:name Friends:friends{Name:name}}}""}",
	"https://mpjk0plp9.lp.gql.zone/graphql", HttpMethod.Post);
Console.WriteLine(result.Data.Hero.Name);

Benchmarks

Some benchmarks has been developed to see how much impact the GraphQL client has on the performance when generating queries. Theese are located under benchmarks.

Example project

An example project can be found in the path examples

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. 
.NET Core netcoreapp1.0 was computed.  netcoreapp1.1 was computed.  netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard1.2 is compatible.  netstandard1.3 was computed.  netstandard1.4 was computed.  netstandard1.5 was computed.  netstandard1.6 was computed.  netstandard2.0 was computed.  netstandard2.1 was computed. 
.NET Framework net451 was computed.  net452 is compatible.  net46 was computed.  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 tizen30 was computed.  tizen40 was computed.  tizen60 was computed. 
Universal Windows Platform uap was computed.  uap10.0 was computed. 
Windows Phone wpa81 was computed. 
Windows Store netcore451 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

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.1.3 2,613 3/27/2018
1.1.2 2,614 3/1/2018
1.1.1 1,211 2/14/2018
1.1.0 1,216 2/13/2018
1.0.3 1,256 1/30/2018
1.0.2 1,237 1/30/2018
1.0.1 1,183 1/12/2018
0.2.0 1,215 12/22/2017
0.1.0 1,023 10/26/2017