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');34// Configure Environment5require('dotenv').config();67const app = express();8const port = 8080;910app.get('/', (req, res) => {11 res.send('Hello World!');12});1314app.use(cors());1516app.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:
- The request should be a POST request.
- All requests are handled by a single endpoint: https://api.github.com/graphql
- Authentication is required using bearer tokens
To make graphql requests in express, I recommend using a libary called graphql-request, to install the library:
1npm install graphql-request graphql23# if you use yarn4yarn 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');45// Configure Environment6require('dotenv').config();78const app = express();9const port = 8080;10const url = 'https://api.github.com/graphql';1112// Do not have your token in a string in your code, especially if you use source control13// https://medium.com/codait/environment-variables-or-keeping-your-secrets-secret-in-a-node-js-app-99019dfff71614const TOKEN = 'PUT_YOUR_TOKEN_HERE';15// Create the graphQL client16const graphQLClient = new g.GraphQLClient(url, {17 headers: {18 authorization: `Bearer ${TOKEN}`,19 },20});2122app.get('/', (req, res) => {23 res.send('Hello World!');24});2526app.use(cors());2728app.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');45const { GraphQLClient, gql } = g;67// Configure Environment8require('dotenv').config();910const app = express();11const port = 8080;12const url = 'https://api.github.com/graphql';1314// Do not have your token in a string in your code, especially if you use source control15// https://medium.com/codait/environment-variables-or-keeping-your-secrets-secret-in-a-node-js-app-99019dfff71616const TOKEN = 'PUT_YOUR_TOKEN_HERE';17// Create the graphQL client18const graphQLClient = new GraphQLClient(url, {19 headers: {20 authorization: `Bearer ${TOKEN}`,21 },22});2324app.use(cors());2526app.get('/', (req, res) => {27 res.send('Hello World!');28});2930app.get('/github-profile', async (req, res) => {31 // The query that gets profile information32 const query = gql`33 {34 viewer {35 login36 name37 company38 url39 bio40 }41 }42 `;43 // Make Graphql call44 const githubRes = await graphQLClient.request(query);45 // Respond with results46 res.json(githubRes);47});4849app.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!