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

Neon image

Serverless Postgres in 300ms (!)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free β†’

Top comments (1)

Collapse
 
findrobbrodie profile image
Rob Brodie β€’

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

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup πŸš€

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay