Becoming a GitHub Ninja: Unleashing the Power of GitHub REST API
Tags: github, javascript, nextjs, tutorial
Published: 2023-08-12 05:20:00

---
title: "Becoming a GitHub Ninja: Unleashing the Power of GitHub REST API"
description: "Unlock the potential of GitHub for your projects using the REST API. Learn how to set up and utilize the GitHub API to supercharge your personal projects and portfolio. Explore step-by-step instructions and real-world examples."
---

Have you ever wondered how to use GitHub for your projects? Well, I used to and it seemed like a difficult task. 

Trust me it is not. With the `REST API` Github provides and some simple setup, you can easily use GitHub for your personal projects and portfolio. But why you ask? 

## Why to use GitHub API ❓❔
As a legend once said : 

<img src="https://media.giphy.com/media/X1kydJ111OQoF1dgMT/giphy.gif"/>

Few simple uses are : 
 - Listing your projects on your Portfolio and using the `README.md` file to showcase details.
 - Building a Blogging website by storing blogs in a repository.
 - Triggering builds using CI/CD pipelines.
 - Integrations with different apps like Slack, Trello, etc.

Now, that we know why - let's look at how.

## Step 0 : Creating a GitHub Account
Just kidding, I am gonna assume you already have a GitHub account. Right? 
<img src="https://media.giphy.com/media/l4hmWKVDDUpiq355K/giphy.gif"/>

## Step 1 : Generating an Access Token
You🙅‍♂️ are an intruder on GitHub. So how will you tell the GitHub server that you are not a Hacker??

Simple, create an access token using your credentials. For this, you need to head on to this link 👉 : [Access Token](https://github.com/settings/tokens).

You will see a `Generate new token` button here, like this : 

![Generate Github Access Token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6gwbnj9fxws44749na64.png).

On clicking the button you will see 2 options : 

![Generate Github Access Token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zuf0xrequ6n29elug9id.png)

The `classic` option works, and for now we will work with that. 

On selecting the classic option, you are taken to new page where you will have to `add a note` that will help you identify the specific token that you want to use from a list of tokens once you've become a `Github Ninja 🐱‍👤`.
<img src="https://media.giphy.com/media/4Ev0Ari2Nd9io/giphy.gif"/>

There are other options that help you select the scope of the token and also set the `expiration date` for the token. Make sure you select 7 days if you are just testing the API.

The following is the only option you need to check ✅ for simple tasks like reading data from and adding data to repositories: 

![Generate Github Access Token](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/835hfh5222040jxiwk2h.png)

Scroll down to the bottom and click on `generate token` button and voila, you can now access GitHub API.

> 🚨 NOTE : You need to copy the token generated and store it in a safe location because GitHub does not allow you to access the token again once you leave the page.

## Step 2 : Connecting to your project ⚡
Now, that you have the token, you simply have to use it in your project. For that you need to have the `Octokit` 🐙 library installed. 

I will discuss how to use it in a Javascript project, more specifically in `ReactJS / NodeJS / NextJS` since the usage is somewhat same in all of these. 

The first thing you need to do is to create a `.env` file in the root folder of your project and add your GitHub access token : 
```js
GITHUB_ACCESS_TOKEN=dsg34glajjwiqv93FaawR
```
And then import the environment variable into the file you want to use. You can read more about them here 🔗: [Medium Link](https://medium.com/chingu/an-introduction-to-environment-variables-and-how-to-use-them-f602f66d15fa).

Now install the `Octokit core` library using the following command in the terminal : 
```js
npm install @octokit/core
```
Now that the setup is done, we can move on to the final and the most simple part. 
<img src="https://media.giphy.com/media/3oKHWnGeVGBpC981DW/giphy.gif" />

## Step 3 : Using the API to Fetch Data
I am just gonna say it : 
`I use the FETCH  library and not Axios`

Will the community accept me? Am I alone? Let me know in the comments.

Now, to the fun part. 

Just import the Octokit core library in your `.js` or `.jsx` file : 

```js
const { Octokit } = require("@octokit/core");
```
Or in `.html` files : 
```html
<script type="module">
  import { Octokit } from "https://esm.sh/@octokit/core";
</script>
```
Then, bring in the environment variable. For NextJS, the code looks like : 
```js
const accessToken = process.env.GITHUB_ACCESS_TOKEN;
```
And there you have it, everything needed in one place. 

Now, simply create an asynchronous function like the following and use it to get the data you want from your repository : 
```js
const fetchPost = async (project) => {
    var myHeaders = new Headers();
    const owner = "thevinitgupta";
    const accessToken = process.env.GITHUB_ACCESS_TOKEN;
    try {

        const octokit = new Octokit({
            auth: accessToken
        })

        const resp = await octokit.request(`GET /repos/${owner}/${project}/contents/README.md`, {
            owner: 'OWNER',
            repo: 'REPO',
            path: 'PATH',
            headers: {
                'X-GitHub-Api-Version': '2022-11-28'
            }
        })
        const base64Content = resp.data.content;
        const decodedContent = Buffer.from(base64Content, 'base64').toString('utf-8');

        // I am using the following to serialize the Markdown text
        let mdxSource = "";
        mdxSource = await serialize(decodedContent);

        return mdxSource;
    }
    catch (error) {
        console.log('error', error)
        return error.message;
    }
}
```
And there you have it : Your beginners guide to becoming a `GitHub Ninja 🐱‍👤`.

For more information on the GitHub REST API and guides, head on to GitHub's official docs here : [DOCS 🔗](https://docs.github.com/en/rest?apiVersion=2022-11-28)

Also, check this challenge that I have recently taken up : [100 Days of Learning](https://thevinitgupta.netlify.app/100daysoflearning)