DEV Community

Cover image for Becoming a GitHub Ninja: Unleashing the Power of GitHub REST API
Vinit Gupta
Vinit Gupta

Posted on

Becoming a GitHub Ninja: Unleashing the Power of GitHub REST API

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 :

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?

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.

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

Generate Github Access Token.

On clicking the button you will see 2 options :

Generate Github Access Token

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 πŸ±β€πŸ‘€.

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

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 :

GITHUB_ACCESS_TOKEN=dsg34glajjwiqv93FaawR
Enter fullscreen mode Exit fullscreen mode

And then import the environment variable into the file you want to use. You can read more about them here πŸ”—: Medium Link.

Now install the Octokit core library using the following command in the terminal :

npm install @octokit/core
Enter fullscreen mode Exit fullscreen mode

Now that the setup is done, we can move on to the final and the most simple part.

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 :

const { Octokit } = require("@octokit/core");
Enter fullscreen mode Exit fullscreen mode

Or in .html files :

<script type="module">
  import { Octokit } from "https://esm.sh/@octokit/core";
</script>
Enter fullscreen mode Exit fullscreen mode

Then, bring in the environment variable. For NextJS, the code looks like :

const accessToken = process.env.GITHUB_ACCESS_TOKEN;
Enter fullscreen mode Exit fullscreen mode

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 :

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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 πŸ”—

Also, check this challenge that I have recently taken up : 100 Days of Learning

Top comments (2)

Collapse
 
ednajimenez profile image
EdnaJimenez

This article describes how to quickly get started with the GitHub REST API using GitHub CLI, JavaScript, or curl . Good Work Done. I really like your blog. Silver Exchange ID

Collapse
 
thevinitgupta profile image
Vinit Gupta

Thanks, do share with people who will find it useful πŸ™