DEV Community

Cover image for Call Github GraphQL API using c#
Mauro Petrini πŸ‘¨β€πŸ’»
Mauro Petrini πŸ‘¨β€πŸ’»

Posted on β€’ Edited on

2 1

Call Github GraphQL API using c#


Welcome! Spanish articles on LinkedIn. You can follow me on Twitter for news.


GraphQL API V4

You can perform a request to any Github resource through the REST API (v3) or the new GraphQL API (V4). The advantage of using the last one is you can replace multiple REST requests with a single call to fetch the data you specify.

Through a Youtube video, I'll show how to call Github GraphQL API using c# without dying while trying.

The sample covers the basis the get the login username (our account)

Endpoint

The REST API (v3) has numerous endpoints but the GraphQL API has a single endpoint:

https://api.github.com/graphql

This endpoint remains constant no matter what operation you perform

Authentication

To communicate with Github, you will need an OAuth token with the right scopes.

To create a personal token you can follow the steps in this page:

https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

Basic Authentication

We need to send the personal token and the username as basic authentication header in our request

string basicValue = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Configs.GithubAccount}:{Configs.PersonalToken}"));

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basicValue);

User-Agent header

All API requests must include a valid User-Agent. Request with no User-Agent header will be rejected so we need to add:

httpClient.DefaultRequestHeaders.Add("User-Agent", "MyConsoleApp");

HTTP Method

In GraphQL, you will provide a JSON-encoded body whether you are performing a query or mutation, so the HTTP verb is POST

Youtube video

Github GIST

class Program
{
static async Task Main(string[] args)
{
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://api.github.com/graphql")
};
httpClient.DefaultRequestHeaders.Add("User-Agent", "MyConsoleApp");
string basicValue = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Configs.GithubAccount}:{Configs.PersonalToken}"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", basicValue);
var queryObject = new
{
query = @"query {
viewer {
login
}
}",
variables = new { }
};
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = new StringContent(JsonConvert.SerializeObject(queryObject), Encoding.UTF8, "application/json")
};
dynamic responseObj;
using (var response = await httpClient.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
responseObj = JsonConvert.DeserializeObject<dynamic>(responseString);
}
Console.WriteLine(responseObj.data.viewer.login);
Console.ReadLine();
}
}
view raw Program.cs hosted with ❀ by GitHub

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
findrobbrodie profile image
Rob Brodie β€’

Thank you for writing this article! The User-Agent header tip got me unstuck.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay