GraphQL Client for .NET Standard

Santosh Kumar
4 min readMar 25, 2024

--

GraphQL is an API query language that empowers clients by allowing them to specify exactly what data they need, rather than leaving it to the server to determine the response.

It acts as an intermediary between clients and backend services, handling client queries and fulfilling them with the requested data. GraphQL has the capability to combine multiple resource requests into a single query, streamlining the data retrieval process.

Create a GraphQLHttpClient:

A GraphQL client library for .NET Standard, operating over HTTP, enables clients to incorporate the GraphQL query language into .NET applications. This facilitates making requests to a GraphQL service seamlessly within the .NET ecosystem.

Usage:

In this example, we’ll develop a .NET Console Application to retrieve data from Sitecore using the GraphQL Http Client.

Assuming the Sitecore GraphQL endpoint is already configured in your development environment. If you need assistance with configuration, please refer to this link.

Step 1: Create one .NET Console application and include the following NuGet packages reference in your project.

Step 2: Let’s assume we have to fetch the Campaign details by Campaign ID from Sitecore. This is the query in GraphQL Playground and we have to get the same result using .NET Console App.

Step 3: Create one GetCampaign.graphql file in your console app.

Step 4: Here is the sample GraphQL query for GetCampaign.graphql file. You can create your own query based on your template and data structure.

 query GetCampaign(
$id: String = "1DF27C19089C4778BB002A8760AADD9E"
$lang: String = "en"
) {
item(path: $id, language: $lang) {
... on Campaign_54034b979d664c8095ce1be2c61f5e72 {
Id: id
Title: title {
value
}

Description: description {
value
}
Image: image {
value
}
}
}
}

Step 5: Now create one method to read this GraphQL query from file.

 public class QueryManager
{
public static string GetCampaignQuery()
{
return File.ReadAllText("Queries/GetCampaign.graphql");
}

}

Step 6: Let’s implement the Program Main method to fetch the data from GraphQL endpoint.

using GraphQL;
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.SystemTextJson;
using GraphQLDemoConsoleApp.Queries;
using GraphQLDemoConsoleApp.Models;
using System.Text.Json;

namespace GraphQLDemoConsoleApp
{
internal class Program
{
private static string _endpoint = "YOUR_SITECORE_GRAPHQL_ENDPOINT";

static async Task Main(string[] args)
{
var client = new GraphQLHttpClient(_endpoint, new SystemTextJsonSerializer());
var request = new GraphQLRequest
{
Query = QueryManager.GetCampaignQuery(),
Variables = new
{
id = "1DF27C19089C4778BB002A8760AADD9E",
lang = "en"
}
};
var result = await client.SendQueryAsync<Data>(request);

var campaign = Converter.ConvertToCampaignModel(result.Data);
var options = new JsonSerializerOptions { WriteIndented = true };
var resultStr = JsonSerializer.Serialize(campaign, options);

File.WriteAllText("campaign.json", resultStr);
}
}
}

In the above code snippet we have taken the reference of GraphQL.Client library and created the GraphQL query request. If you notice we are also passing parameters “Id” and “Lang” to filter the result.

Step 7: In the above code we have also converted the raw response into model before writing the output in the “campaign.json” file. Let’s create one Model for this and converter method which is used in the main method.

public class CampaignModel
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Image { get; set; }
}
 public static class Converter
{
public static CampaignModel ConvertToCampaignModel(Data data)
{
var campaign = data.Item;
var result = new CampaignModel()
{
Id = campaign.Id,
Title = campaign.Title,
Description = campaign.Description.Value,
Image = campaign.Image.value
}

return result;
}
}

If everything is executed correctly, upon running this program, you should find the campaign.json file in the bin folder of your console application.

Note: If your Sitecore GraphQL endpoint requires authentication, you need to pass the API key (?sc_apikey=api-key-guid) in the query parameter.

You can also disable the authentication in local environment using the following settings. Navigate to your Sitecore\Services.GraphQL folder and open the Sitecore.Services.GraphQL.config file. Do the following changes.

 <requireAuthentication>false</requireAuthentication>

<requireApiKey>false</requireApiKey>

That’s it. You can find my other blogs here.

Thank you!

--

--

Santosh Kumar

Software Architect at EPAM Systems. Extensive expertise in Sitecore | XM Cloud | OrderCloud | Content Hub |.Net Core | Azure | AWS | Docker & MACH architecture.