Authentication

Learn to get authenticated with the GitHub API.

Overview

To fully utilize the GitHub API, we have to authenticate ourselves. Unauthenticated users can make only 60 requests per hour. However, authentication can increase this limit to 5000 requests per hour.

Use personal access tokens

First, let’s see the number of requests an unauthenticated user can make to the GitHub API. This limit is identified by x-ratelimit-limit in the JSON response, as shown below:

Press + to interact
const endpointUrl = 'https://api.github.com/rate_limit';
const options = {
method: 'GET',
};
async function GetRequestLimit() {
try {
const response = await fetch(endpointUrl, options);
printResponse(response);
} catch (error) {
printErrors(error);
}
};
GetRequestLimit();
async function printResponse(response) {
if (response.status === 200) {
console.log("x-ratelimit-limit: " + response.headers.get('x-ratelimit-limit'));
} else {
console.log(`Error Code: ${response.status}`);
console.log(`Error: ${response.statusText}`);
}
}
async function printErrors(error) {
console.log(error.message);
}

Let’s look at a brief explanation of the above code:

  • Line 1: We define the URL of the endpoint.
  • Lines 6–13: We define the async function that will call the defined endpoint.
    • Line 9: In case of a successful request, the response of the API call is printed by invoking the printResponse function.
    • Line 11: Otherwise, the error is printed by calling printErrors function.
  • Line 15: We call the async function.

The best way to authenticate with the GitHub API is via personal access tokens. Let’s run the same code again, but this time, we’ll try to authenticate using the personal access token.

Press + to interact
const endpointUrl = 'https://api.github.com/user';
const headers = {
Authorization: 'token {{ACCESS_TOKEN}}',
};
const options = {
method: 'GET',
headers,
};
async function GetRequestLimit() {
try {
const response = await fetch(endpointUrl, options);
printResponse(response);
} catch (error) {
printErrors(error);
}
};
GetRequestLimit();

Let’s look at a brief explanation of the above code:

  • Line 1: We define the URL of the endpoint.
  • Lines 12–19: We define the async function that will call the defined endpoint.
    • Line 15: In case of a successful request, the response of the API call is printed by invoking the printResponse function.
    • Line 17: Otherwise, the error is printed by calling printErrors function.
  • Line 21: We call the async function.

Note: The printResponse function is implemented on the backend and its purpose is to display the fetched JSON response.

The printErrors function is also implemented on the backend and its purpose is to display the error received against the failed HTTP request.

As we can see, the limit has increased to 5000 requests per hour. In addition to this, authentication also provides the ability to read and write private information using this API.

The personal access tokens usually have an expiration date. The API request using an expiring personal token returns the token’s expiration date. This can be accessed using the GitHub-Authentication-Token-Expiration header. This token can be used to inform the user that the token will expire soon.

Press + to interact
const endpointUrl = 'https://api.github.com/user';
const headers = {
Authorization: 'token {{ACCESS_TOKEN}}',
};
const options = {
method: 'GET',
headers,
};
async function CheckTokenExpiry() {
const response = await fetch(endpointUrl, options);
const expiry = response.headers.get('GitHub-Authentication-Token-Expiration');
if (expiry != null) {
console.log(`Expiration date: ${expiry}`);
} else {
console.log('No Expiration date');
}
};
CheckTokenExpiry();

Let’s look at a brief explanation of the above code:

  • Line 1: We define the URL of the endpoint.

  • Lines 12–20: We define the async function that will call the defined endpoint.

    • Line 14–19: We check if the access token has an expiry date or not.
  • Line 22: We call the async function.

Get your own profile

An authenticated user can fetch information from GitHub that’s associated with specific permissions. For example, we can fetch our own GitHub profile using the following code:

Press + to interact
const endpointUrl = 'https://api.github.com/user';
const headers = {
Authorization: 'token {{ACCESS_TOKEN}}',
};
const options = {
method: 'GET',
headers,
};
async function GetProfile() {
const response = await fetch(endpointUrl, options);
console.log(JSON.stringify(await response.json(), null, 2));
};
GetProfile();

Let’s look at a brief explanation of the above code:

  • Line 1: We define the URL of the endpoint.
  • Lines 12–15: We define the async function that will call the defined endpoint.
  • Line 17: We call the async function.

HTTP responses

All the endpoints in this course return HTTP responses. The following table describes some HTTP response codes:

HTTP codes

Description

201

The endpoint is successfully executed

403

The request is forbidden

422

The validation has failed

200

Everything is working fine

307

Temporary redirection

404

The resource is not found

301

The branch has been permanently moved

204

The response was already merged

409

A merge conflict

500

There is an internal error

304

The content has not been modified

503

The service is unavailable

201

A new invite for the collaboration invitation is created