Authentication
Learn to get authenticated with the GitHub API.
We'll cover the following
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 headers, as shown below:
url = 'https://api.github.com/v3/zen'response = requests.get(url)print('Limit: '+response.headers['X-RateLimit-Limit'])
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.
headers = {'Authorization': 'token {{ACCESS_TOKEN}}'}url = 'https://api.github.com/v3/zen'response = requests.get(url, headers=headers)print('Limit: '+response.headers['X-RateLimit-Limit'])
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.
headers = {'Authorization': 'token {{ACCESS_TOKEN}}'}url = 'https://api.github.com/v3/zen'response = requests.get(url, headers=headers)if 'GitHub-Authentication-Token-Expiration' not in response.headers:print('No Expiration date')else:print('Expiration date: '+response.headers['GitHub-Authentication-Token-Expiration'])
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:
headers = {'Authorization': 'token {{ACCESS_TOKEN}}'}url = "https://api.github.com/user"response = requests.get(url, headers=headers)print(json.dumps(response.json(), indent=4))
HTTP responses
All the endpoints in this course return HTTP responses. The following table describes some HTTP response codes:
HTTP codes | Description |
| This means that the endpoint is successfully executed. |
| This means that the request is forbidden. |
| This means that validation has failed. |
| This means that everything is working fine. |
| This means temporary redirection. |
| This means that the resource is not found. |
| This means that the branch has been permanently moved. |
| This means that the response was already merged. |
| This indicates a merge conflict. |
| This means there is an internal error. |
| This means that the content has not been modified. |
| This means that the service is unavailable. |
| This means that a new invite for the collaboration invitation is created. |