Navigate back to the homepage
StoriesLeaderboard

How to use Github's GraphQL API with Express.js

Yong Lin Wang
August 21st, 2020 · 2 min read

GitHub offers a powerful REST based API for developers to get data and integrate with its platform, with API version 4, they also introduced the GitHub GraphQL API. This article will show how you can leverage the power of GitHub GraphQL API in your express application.

About GraphQL

GraphQL is a data querying language that is strongly typed, introspective, and hierarchal. It acts as an application layer as well as a specification. The Graph in GraphQL refers to a graph structure where nodes define objects (repositories, gists, users, etc.) and edges define relationship between objects. The API traverses and returns application data based on the schema definition, independent of how the data is stored.

This allows a much greater level of flexibility and more precise data fetching compared to REST based APIs. In one request you can get the name of all the repositories the user owns and their user profile. For more information about GraphQL and how GitHub uses it, visit their developer page.


Setting up the Server

I’m going to omit the basic set up like npm init and installing dependencies, and jump right into the code, the dependencies I use can be installed like.

1npm install express dotenv cors

To get started create a js file called server.js with the following content:

1const express = require('express');
2const cors = require('cors');
3
4// Configure Environment
5require('dotenv').config();
6
7const app = express();
8const port = 8080;
9
10app.get('/', (req, res) => {
11 res.send('Hello World!');
12});
13
14app.use(cors());
15
16app.listen(port, () => {
17 console.log(`[server]: Server is running at http://localhost:${port}`);
18});

Now run node server.js to start the server, you should see

[server]: Server is running at http://localhost:8080

in your terminal. Good job! We have a working express server now.

Forming GraphQL Calls

One thing you should note is that GraphQL requests are also sent using the HTTP protocol so any http-speaking libraries you use for REST APIs can be used to form GraphQL calls with a few things in mind:

To make graphql requests in express, I recommend using a libary called graphql-request, to install the library:

1npm install graphql-request graphql
2
3# if you use yarn
4yarn add graphql-request graphql

You can use the library inline, or you can create a separate reusable module for all of your GraphQL calls.

Authenticating with GitHub GraphQL

To access the API, you need to have a personal access token, you can obtain one by going to your settings page and developer settings. Make sure to copy your token before leaving the page because you cannot see the token anymore after.

When creating the token, you are prompted to select the permissions for the token, choose what is necessary for your application, see this page for more details.

Now we can add the GraphQL client to the server

1const g = require('graphql-request');
2const express = require('express');
3const cors = require('cors');
4
5// Configure Environment
6require('dotenv').config();
7
8const app = express();
9const port = 8080;
10const url = 'https://api.github.com/graphql';
11
12// Do not have your token in a string in your code, especially if you use source control
13// https://medium.com/codait/environment-variables-or-keeping-your-secrets-secret-in-a-node-js-app-99019dfff716
14const TOKEN = 'PUT_YOUR_TOKEN_HERE';
15// Create the graphQL client
16const graphQLClient = new g.GraphQLClient(url, {
17 headers: {
18 authorization: `Bearer ${TOKEN}`,
19 },
20});
21
22app.get('/', (req, res) => {
23 res.send('Hello World!');
24});
25
26app.use(cors());
27
28app.listen(port, () => {
29 console.log(`[server]: Server is running at http://localhost:${port}`);
30});

We are one step closer to getting graphQL working on our server, let’s test this out by creating an endpoint that gets your profile information from GitHub!

1const g = require('graphql-request');
2const express = require('express');
3const cors = require('cors');
4
5const { GraphQLClient, gql } = g;
6
7// Configure Environment
8require('dotenv').config();
9
10const app = express();
11const port = 8080;
12const url = 'https://api.github.com/graphql';
13
14// Do not have your token in a string in your code, especially if you use source control
15// https://medium.com/codait/environment-variables-or-keeping-your-secrets-secret-in-a-node-js-app-99019dfff716
16const TOKEN = 'PUT_YOUR_TOKEN_HERE';
17// Create the graphQL client
18const graphQLClient = new GraphQLClient(url, {
19 headers: {
20 authorization: `Bearer ${TOKEN}`,
21 },
22});
23
24app.use(cors());
25
26app.get('/', (req, res) => {
27 res.send('Hello World!');
28});
29
30app.get('/github-profile', async (req, res) => {
31 // The query that gets profile information
32 const query = gql`
33 {
34 viewer {
35 login
36 name
37 company
38 url
39 bio
40 }
41 }
42 `;
43 // Make Graphql call
44 const githubRes = await graphQLClient.request(query);
45 // Respond with results
46 res.json(githubRes);
47});
48
49app.listen(port, () => {
50 console.log(`[server]: Server is running at http://localhost:${port}`);
51});

If you visit http://localhost:8080/github-profile, you should be able to see a json with your user profile info!

Tada! We have integrated our application with GitHub! Now the possibility is limitless!

More articles from UOSC

Keep grinding until someone notices you.

Looking for jobs this summer has been rough for me. I applied to over 200+ SWE Intern positions and am currently 0/4 when giving me an interview. In each case, it seems like I have done well in the white-boarding interviews, with developers actually saying I did an excellent job in the interview.

February 13th, 2020 · 2 min read

An internship at Riot Games

In this post, I will be going through my internship experience, providing insight and tips for students that are interested in Riot Games!

August 31st, 2021 · 8 min read
Directory
General Enquiries
hello@uosc.io
Built with
❤️
by the front end team. Powered by ☕.
© 2022 UOSC.