Skip to the content.

GraphQL Client Extensions

logo

Extensions for GraphQL.Client to build graphQL queries from a C# model.

Build Status Azure DevOps coverage (branch) Nuget Downloads

Uses GraphQL.Query.Builder for query building.

Install

Run this command with dotnet CLI:

dotnet add package GraphQL.Client.Extensions

Usage

Create a query with GraphQL.Query.Builder

The query building is based on the object which returns.

Entities definition

In a first time, you need to create POCOs.

class Human
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Planet HomePlanet { get; set; }
    public IEnumerable<Human> Friends { get; set; }
}

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

Creation of the query

After that, you can write a query like this :

IQuery<Human> query = new Query<Human>("humans") // set the name of the query
    .AddArguments(new { id = "uE78f5hq" }) // add query arguments
    .AddField(h => h.FirstName) // add firstName field
    .AddField(h => h.LastName) // add lastName field
    .AddField( // add a sub-object field
        h => h.HomePlanet, // set the name of the field
        sq => sq /// build the sub-query
            .AddField(p => p.Name)
    )
    .AddField<human>( // add a sub-list field
        h => h.Friends,
        sq => sq
            .AddField(f => f.FirstName)
            .AddField(f => f.LastName)
    );

This corresponds to :

humans (id: "uE78f5hq") {
  FirstName
  LastName
  HomePlanet {
    Name
  }
  Friends {
    FirstName
    LastName
  }
}

By default, the AddField() method use the property name as field name. You can change this behavior by providing a custom formatter.

QueryOptions options = new()
{
    Formater = // Your custom formatter
};

IQuery<Human> query = new Query<Human>("human", options);

Formater’s type is Func<PropertyInfo, string>

There are built-in formatters :

Run the query

You can run the query using two GraphQLCLient extension methods:

Example:

using (GraphQLClient client = new("<url>"))
{
    Human human = await client.Get<Human>(query);
}

API documentation

See API documentation here