DEV Community

Cover image for Call Github GraphQL API using c#
Mauro Petrini 👨‍💻
Mauro Petrini 👨‍💻

Posted on • Updated on

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

Top comments (1)

Collapse
 
findrobbrodie profile image
Rob Brodie

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