Skip to main content

Using GitHub REST API to display your repositories with Angular

This post covers the authentication to GitHub REST API with fine-grained personal access token, sending the request to GitHub server with Octokit library, and displaying the list of your repositories in Angular component. Instructions on how to create the token can be found in GitHub documentation and will not be covered in this post. 

Photo by Douglas Lopes on Unsplash 

 

Handling your token in Angular app

Before moving any application or a page that uses sensitive information such as passwords or tokens into a production, you need to be aware that sensitive data cannot be hidden from a client (user) if it is stored in the application. The best way for production use is to serve the token from a back-end or a proxy server. There are plenty of examples on how to do that, for now we will store the token in the app, so that we can focus on authentication and pulling the data from the GitHub server.

Store the token in a config file

Once you have created your GitHub token, go to your Angular project and add the token value as a constant in a gitconfig.ts file:

export const config = {
    API_KEY:
        "github_pat_q35q9e40938450345v039403",
};

Install the Octokit.js

Octokit is a JavaScript library that can be used to authenticate and send requests to GitHub API from JavaScript based applications. It is a recommendation from GitHub to use Octokit if you want to interact with GitHub REST API via JavaScript. More information about Octokit can be found in Octokit official documentation and GitHub guide .

To install octokit.js in your angular app, run the npm command:

npm i octokit

Now that you've installed the package, you are ready for the next part of this tutorial, and that is authentication.

Authenticate to GitHub API using PAT (personal access token)

Next, we want to create a config.js or environment  file where we will store our authentication logic:

import { Octokit } from 'octokit';
import { config } from 'config';
const GIT_KEY = config.API_KEY;
export const octokit = new Octokit({
    auth: GIT_KEY,
});

Here we are importing the Octokit from the octokit package, and our previously stored API token. We create new const GIT_KEY and assign it a value of the API_KEY from config.js. And finally,  we create an instance of Octokit and pass the GIT_KEY to auth option. Auth option can either be a string or an object, depending on your needs, and there are other options (such as baseUrl) to be used here, but for this example we don't need them. You can read more about them here https://www.npmjs.com/package/octokit

Create a service for handling the request

To follow the Angular best practice, let's create a service that will be responsible for sending the request. In our case, we are using GET request because we want to get data about our repositories.

Octokit requests are asynchronous, so you need to make your function async:

async getRepositories() {
        const repo = await octokit.request('GET /users/{username}/repos', {
            username: 'your_github_username',
        });
        return repo;
    }

Call the service in your component

In your component, you will call the service which will fire the request to the GitHub and return the repositories data. You can save this data in a repositories array.

displayRepoList() {
        this.workService.getRepositories().then(
            (res) => {
                this.repositories = res.data;
            },
            (err) => {
                console.log('failed', err);
            }
        );
    }

The response object that is returned has data array with information about repositories.

The data property holds value that is a list of repository objects. This was our main goal to achieve. From here on, you are free to choose which repositories you want to display, and what values.

Displaying a list of repositories on a page

Now that your component has a list of repositories, you can easily display that list with Angular *ngFor directive in component's  html file. 

 <div id="gh-repo-list" class="projects">
    <div class="item" *ngFor="let item of repositories">
      <p>{{item.name}}</p>
      <p>{{item.description}}</p>
      <a href={{item.html_url}} target="_blank">
        {{item.html_url}}
      </a>
    </div>
  </div>

You can add some styling to make the appearance more visual:

#gh-repo-list {
    padding: 2em;
    .item {
        border: 1px solid black;
    }
}
.projects {
    display: grid;
    gap: 0.7rem;
    grid-template-columns: repeat(2, 1fr);
    img {
        width: 100%;
        border: 3px #fff solid;

        &:hover {
            opacity: 0.5;
            border-color: #000;
        }
    }
}


And with that, we have a page displaying our GitHub repositories:

Troubleshooting

It is possible that during build time application caught some warnings about commonJS dependencies. They may look like this:

"C:\ \ \node_modules\@octokit\request-error\dist-web\index.js depends on 'once'. CommonJS or AMD dependencies can cause optimization bailouts. For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies"

Angular documentation suggest to add a property allowedCommonJsDependencies to angular.json configuration:

"allowedCommonJsDependencies": [

                            "@octokit",

                            "@octokit/app",

                            "@octokit/oauth-app"

                        ],

 

This should remove the warnings.

CONCLUSION

The idea behind this post is to learn how to integrate GitHub API in Angular application. The example is fairly simple with only the basic configuration to get access to the API. As an author, I hope this post will intrigue you to practice integrating APIs, because this is something that is used in a real world on a daily basis. I think it's important to learn it and fun to use it. 

Leave your comments and questions down below. 

Comments