Getting Started with Github API
REST API v3 using Python🐍
I was recently introduced to “Github API” after I attended a webinar. I found it really difficult to read the documentation as it was my first time and figure out how things work. Many of you might also be newbies finding a platform to learn or searching for a solution to problem like how to close an issue using Github API.
If you landed on this page while asking Google something like
How to create a repository using Github API
How to delete a repository using Github API
How to create an issue …..and so on
Congratulations👏 ! You are on the right path.
In this article I will walk you through all the essential steps required for working with Github API (REST) using python. From generating token to understanding the documentation to understanding when to make GET, POST, DELETE requests and also work with it, all will be covered here. I will try my level best to put all these in the simplest way possible.
We will be using Github API to :-
- Create a repository
- List repositories of a user
- Delete a repository
- Create an issue
- Comment on an issue
- Close an issue
- Create Pull request …….for more you may reach out to my Github repository mentioned in the end.
Lets make the tough job look easy. So lets begin …
What is an API ?
Lets have a role play to understand it better (I will be using words like Github, server, application…all these refer to the service provider on the other side of API to whom we make request)
Place : Restaurant
Characters : We as Customer, API as waiter, and Github as Chef providing services
(Conversation between customer and waiter)
Customer : (Raises hand) — We call the API
Waiter : What would you like to have, sir? — API asks what we want it to perform
Customer : Bring me a medium bowl of hot and sour soup, please. — We instruct the API about what we want and how we want it to be done.
Waiter : Sure sir. — The API understands and leaves to get what we want. In case of any confusion API would throw an error
(Conversation between waiter and chef)
Waiter : The customer wants a medium bowl of hot and sour soup. — The API conveys the need to the Github(server)
Chef : (handing over the bowl) Here it is — Server sends out the data required
Waiter : (Takes the bowl and serves it to the customer) — API takes the data and then serves it to US.
As you can see we cannot talk to the chef directly so we need a person who can deliver our request to the chef and bring the response back. This waiter acting in between is the API when it comes to web. API has the same job. It carries our request to the application(service provider) and brings back the response.
I hope that it is clear what exactly the API is and how it works on backend.
Can anybody use the API ?
No.
Nowadays almost every API comes with an API key. Consider there is a private party. You cannot go inside and enjoy the services if you don’t have the invitation. The invitation is the key which allows you to passthrough the guards. Similarly API key allows you to use the API to retrieve information or make some changes to the other side of the API (i.e. server or some application). The API keys or tokens are confidential information and should not be shared with anyone.
Enough with the API talk. Now lets login to our Github account and generate a token so that we can call the API.
How to generate a token on Github ?
Why do we need a token ?
Without token you cannot perform many requests such as creating a repository, deleting it. There are some requests which can be made without a token like List Repositories for a User. Token is somewhat similar to API key.
Lets begin …
- Login to your Github account.
- Go to Settings -> Developer Settings ->Personal Access Tokens
- Click on Generate new token. Confirm your password to continue.
- Give any description to your token.
- Under scopes check all you want the API to have access to in your account. I checked all the boxes.
- Click Generate new token.
Hurray! Your token has been generated. Copy the token and save it somewhere as it won’t be visible to you after this time.
How to read Github API documentation ?
Here I will be talking about 3 types of requests
- GET request — This request is made when you want to retrieve some information from the application (here it is Github). For eg.- list of repositories, list of repository topics, repository language, etc.
- POST request — This request is used when you want to make some changes in the application connected to API on other side. For eg.- create repository, create pull request, create an issue, etc.
- DELETE request — This request is made when you want to perform any deletion. For eg.- delete a repository, delete reaction from an issue, etc.
After we figure out what type of request do we need to make, we construct the API url.
The base url is https://api.github.com. We improve it further according to what we need.
You will find the above type of instructions in the documentation. Now lets learn how to read it. The first word tells you what type of request you need to make, whether it is POST, GET or DELETE. The leftover part is the relative path which you need to add to the base url.
Request type : POST
URL : https://api.github.com/users/repos
Now you know what request you need to make and how to construct the URL. But what you want is still not conveyed to the API. It’s similar to deciding where to go and what you want but you still haven’t provided the specifications that how you want the work to be done. You want a pizza🍕 but you didn’t tell what flavour, size, with or without toppings, etc. You want to create a Repository but you didn’t convey its name. Now, lets welcome🥳 JSON who would be helping us with this. JSON is the way you transfer information over web. You provide the data to the API in form of a JSON string. JSON is same as dictionary in python.
Wherever you find Parameters, you need to send a JSON file with these parameters included when making a request.
Example JSON → data = {“name” : “Hello-repo”}
NOTE : — Be careful while constructing a URL and with the type of request. These were mostly the areas where the API threw an error to me.
Enough of theory. Now it’s practical time. If you have reached till here then trust me you have understood a concept which took me 2 days and a lot of sites. You definitely took less.
Lets START with the CODING part now.
Lets do some Coding and make API calls 😎🐍
We will be using Python to make the API calls .
1. Create a Repository
Replace the token with your own generated token in line 1 to create a repository in your account. After executing the above code with a response of 201 go and check out your account for the newly created repository. If you find it congratulate yourself, you made your first call🥰👍.
Any data that is needed to be sent along with the request needs to be in JSON format. The token is to be included inside headers.
json.dumps() function transforms the json file(or dictionary in python) to a json string.
Click Here to view documentation.
2. Delete a Repository
Here we make a delete request as we want to make a deletion and the process requires Authorization so we need to pass a token. The process of construction of url is the same as I explained before.
Click Here for documentation.
3. Create an Issue
Here data is a JSON containing ‘Parameters’ as I explained before. Parameters are the specifications.
Click Here for documentation.
4. Comment on an Issue
Issue number can be found out under Issues tab in your repository prefixed with a hashtag #.
5. Close an Issue
This was particularly the one which caused me a lot of trouble. I couldn’t find any documentation for it on web. But after analyzing the JSON response I found the solution. You can print the JSON reponse file by writing following 2 lines :-
output = requests.post(url,data=json.dumps(data),headers=headers )
output.json() #This line will print the response in JSON format
To close an issue change the state to close and send it with post request.
6. Create Pull Request
For creating a pull request ->
- Create a branch — provide master with a friend to communicate
- Create a file in the newly created branch which can be pulled into master.
The setup is ready. Now you just need to run the code.
Parameters — I guess title and body must be clear from the name itself.
The file needs to be pulled from head branch(Newly created branch) to base branch(Master branch). I created a branch named pull-request.
Now what you need to focus on is the Accept key/object in headers. Without this the request will not be made and you will be thrown an error. While making some API requests you need to mention it along with the token inside headers. You will find it mentioned in the documentation.
7. List Repositories for a user
This API call doesn’t require any token. Therefore, you can access repository list of any user across Github. The output variable contains the string file sent as a response by the Github. You can print it(command — output.text) and check for the single quotes around the whole file. I presume that you know how to read data from a list and dictionary in python. Output is a list containing dictionaries as its elements so i iterates through each item(dictionary) within the list and we print the value of key “name” inside it.
Click Here for documentation.
So,here we come to an end. I guess I explained most of the things and I hope you had a good understanding of it. This is my very first blog so I don’t know if my performance is good or not or whether I was able to live up to the Medium’s standard. My only motive was to pass on what I learnt but in a much simpler way. Hope this helps.
You can access code for these as well as a few other API calls from my Github repository — https://github.com/GaganpreetKaurKalsi/Github-APIs-Python
Connect with me :- https://www.linkedin.com/in/gaganpreet-kaur-kalsi-2a6650191/
Thankyou!