APIS (Python-Intermediate)

Mahedi Hasan Jisan
4 min readDec 31, 2020
API

I am back to writing about programming after a long time. I have started programming on hackerrank a few days back, you know to make my profile a little heavy 😉. I have encountered a problem with APIs. I thought why not share it!

What is API?

An application programming interface, which established a connection between different software platforms. A call can be made, data can be fetched. It is a useful technique in different cases.

Let’s say, you want to know about soccer statistics in English Premier League in a given year. Well, you can do that from multiple websites by searching for each team. Time-consuming, right? Too much work, right? Yes, absolutely it is too much work and time consuming. However, there is a solution for that. You can create or write APIs to do your tasks in python. You just write a few lines of code of API, the code will gather every information you require.

I am going to use python in this talk! In python, there is a library called requests. And we are going to use JSON to load the data. Hackerank provided an API link, which I am going to use. First of all, we need to load the following lines to make APIs work:

import requests
import json

In order to work with API, we need an URL, which we will use to call and fetch the desire data. The URLs are:

https://jsonmock.hackerrank.com/api/football_competitions?name=English Premier League&year=2014https://jsonmock.hackerrank.com/api/football_matches?competition=English Premier League&year=2014&team1=Chelsea

Using these URLs, we are going to find out the winner of the English Premier League in 2014 and the total goals they have scored in both home and away matches. Let’s do that!! 😆

Step 1: We need to find the winner, therefore, the code would be:

URL = "https://jsonmock.hackerrank.com/api/football_competitions?name=" + competition + "&year=" + str(year)
getData = requests.get(URL)
getJson = json.loads(getData.content)
Fetched Data:
{"page":1,"per_page":10,"total":1,"total_pages":1,"data":[{"name":"English Premier League","country":"England","year":2014,"winner":"Chelsea","runnerup":"Manchester City"}]}
team = ""
for i in getJson['data']:
team = i["winner"]
break

In the above code, first, we have set the URL with competitions name which is EPL(English Premier League) and year (2014). Then, we have used the requests library to fetch the data using the URL. After that, we have decoded the data into JSON format. Then, we have stored the winner team name from the fetched data.

Now, there can be multiple pages on a website. In order to fetch all the scored goals by the winning team, we have to iterate through every page for the winning team.

url1 = "https://jsonmock.hackerrank.com/api/football_matches?competition=" + competition + "&year=" + str(
year) + "&team1=" + team
url2 = "https://jsonmock.hackerrank.com/api/football_matches?competition=" + competition + "&year=" + str(
year) + "&team2=" + team

# first team
res1 = requests.get(url1)
res1Json = json.loads(res1.content)

# second team
res2 = requests.get(url2)
res2Json = json.loads(res2.content)

# getting the total pages from the JSON
itr1 = 1
itr2 = 1

page1 = res1Json['total_pages']
page2 = res2Json['total_pages']

Now, the above code has two URLs. Two has been used to find every home and away match for the winning team. To make it more clear, let’s look at the fetched data by the above API call:

{"page":1,"per_page":10,"total":1,"total_pages":1,"data":[{"name":"English Premier League","country":"England","year":2014,"winner":"Chelsea","runnerup":"Manchester City"}]}

You can see that, page numbers from the fetched. In particular, it is only 1 page but there can be multiple pages. It’s better to write code while considering every option.

Now, we just have to find total goals on each page for the winning team in a home and away games. let's do that.

# counting how many goals
total = 0
while itr1 <= page1:
url1Update = "https://jsonmock.hackerrank.com/api/football_matches?competition={0}&year={1}&team1={2}&page={3}".format(
competition, year, team, itr1)
res1Update = requests.get(url1Update)
res1JsonUpdate = json.loads(res1Update.content)
for i in res1JsonUpdate['data']:
if i['team1'].upper() == team.upper():
total += int(i['team1goals'])
itr1 += 1

while itr2 <= page2:
url2Update = "https://jsonmock.hackerrank.com/api/football_matches?competition={0}&year={1}&team2={2}&page={3}".format(
competition, year, team, itr2)
res2Update = requests.get(url2Update)
res2JsonUpdate = json.loads(res2Update.content)
for i in res2JsonUpdate['data']:
if i['team2'].upper() == team.upper():
total += int(i['team2goals'])
itr2 += 1

Using, the above code, we can fetch the total goal count for the winning team easily. If we put together the whole code together, then it will look like this:

import requests
import json


def getWinnerTotalGoals(competition, year):
# Write your code here
URL = "https://jsonmock.hackerrank.com/api/football_competitions?name=" + competition + "&year=" + str(year)
getData = requests.get(URL)
getJson = json.loads(getData.content)
team = ""
for i in getJson['data']:
team = i["winner"]
break
# re-trace
url1 = "https://jsonmock.hackerrank.com/api/football_matches?competition=" + competition + "&year=" + str(
year) + "&team1=" + team
url2 = "https://jsonmock.hackerrank.com/api/football_matches?competition=" + competition + "&year=" + str(
year) + "&team2=" + team

# first team
res1 = requests.get(url1)
res1Json = json.loads(res1.content)

# second team
res2 = requests.get(url2)
res2Json = json.loads(res2.content)

# getting the total pages from the JSON
itr1 = 1
itr2 = 1

page1 = res1Json['total_pages']
page2 = res2Json['total_pages']

# counting how many goals
total = 0
while itr1 <= page1:
url1Update = "https://jsonmock.hackerrank.com/api/football_matches?competition={0}&year={1}&team1={2}&page={3}".format(
competition, year, team, itr1)
res1Update = requests.get(url1Update)
res1JsonUpdate = json.loads(res1Update.content)
for i in res1JsonUpdate['data']:
if i['team1'].upper() == team.upper():
total += int(i['team1goals'])
itr1 += 1

while itr2 <= page2:
url2Update = "https://jsonmock.hackerrank.com/api/football_matches?competition={0}&year={1}&team2={2}&page={3}".format(
competition, year, team, itr2)
res2Update = requests.get(url2Update)
res2JsonUpdate = json.loads(res2Update.content)
for i in res2JsonUpdate['data']:
if i['team2'].upper() == team.upper():
total += int(i['team2goals'])
itr2 += 1

return total


if __name__ == '__main__':
competition = "English Premier League"

year = 2014

result = getWinnerTotalGoals(competition, year)

print(result)

If you run this code, it will fetch you the information that you want, which is pretty cool, right? Yes, this is what APIs do. It is simple and straightforward. 👊

Hopefully, this will help beginners. Practice will make it clearer. Have fun and cheers! 👌

--

--