Skip to content

Commit 508ab4d

Browse files
authored
Merge pull request #141 from realpython/consuming-apis-python
Materials for Consuming APIs article
2 parents 113fe97 + 85e01b9 commit 508ab4d

File tree

5 files changed

+201
-0
lines changed

5 files changed

+201
-0
lines changed

consuming-apis-python/covid.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import requests
2+
3+
# The datetime package is useful to manipulate dates.
4+
from datetime import date, timedelta
5+
6+
# To fetch the latest total confirmed cases number you need to pass a 24h
7+
# window to the API. That's why you need to pass both yesterday's date
8+
# and today's.
9+
today = date.today()
10+
yesterday = today - timedelta(days=1)
11+
12+
# Pick a country slug from the list: https://api.covid19api.com/countries
13+
country = "germany"
14+
15+
endpoint = f"https://api.covid19api.com/country/{country}/status/confirmed"
16+
params = {"from": str(yesterday), "to": str(today)}
17+
18+
# The response will be a list of results per day, in your case only 1 result.
19+
response = requests.get(endpoint, params=params).json()
20+
21+
# Finally, you need to traverse through the response and increment the
22+
# `total_confirmed` variable with the total number of confirmed cases
23+
# available that day, which is in the field `Cases`.
24+
total_confirmed = 0
25+
for day in response:
26+
cases = day.get("Cases", 0)
27+
total_confirmed += cases
28+
29+
print(f"Total Confirmed Covid-19 cases in {country}: {total_confirmed}")
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import requests
2+
3+
# REPLACE the following with the API key you generated.
4+
API_KEY = "REPLACE_DEMO_API_KEY"
5+
6+
endpoint = "https://api.giphy.com/v1/gifs/search"
7+
8+
# Define the search term you want to use.
9+
search_term = "shrug"
10+
11+
# In the query parameters you can define:
12+
# 1. The number of GIFs to return using the `limit` parameter.
13+
# 2. The query term to search for using the `q` parameter.
14+
# 3. The accepted rating of the GIFs returned using the `rating` parameter
15+
# https://developers.giphy.com/docs/optional-settings#rating
16+
params = {"api_key": API_KEY, "limit": 3, "q": search_term, "rating": "g"}
17+
18+
# The response will contain a list with all the GIFs that match your query.
19+
# For each of those, you want to get the `title` and `url` fields.
20+
response = requests.get(endpoint, params=params).json()
21+
for gif in response["data"]:
22+
title = gif["title"]
23+
url = gif["url"]
24+
print("%s | %s" % (title, url))
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import requests
2+
3+
# REPLACE the following with the API key you generated.
4+
API_KEY = "REPLACE_DEMO_API_KEY"
5+
6+
endpoint = "https://api.giphy.com/v1/gifs/trending"
7+
8+
# In the query parameters you can define:
9+
# 1. The number of GIFs to return using the `limit` parameter.
10+
# 2. The accepted rating of the GIFs returned using the `rating` parameter
11+
# https://developers.giphy.com/docs/optional-settings#rating
12+
params = {"api_key": API_KEY, "limit": 3, "rating": "g"}
13+
14+
# The response will contain a list with all the GIFs that match your query.
15+
# For each of those, you want to get the `title`, `url` and the
16+
# `trending_datetime` fields.
17+
response = requests.get(endpoint, params=params).json()
18+
for gif in response["data"]:
19+
title = gif["title"]
20+
trending_date = gif["trending_datetime"]
21+
url = gif["url"]
22+
print("%s | %s | %s" % (title, trending_date, url))

consuming-apis-python/github.py

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
import requests
2+
3+
# First, make sure to follow the steps to create your own GitHub application:
4+
# https://docs.github.com/en/free-pro-team@latest/developers/apps/creating-an-oauth-app
5+
6+
7+
# REPLACE the following variables with your Client ID and Client Secret
8+
CLIENT_ID = "<REPLACE_WITH_CLIENT_ID>"
9+
CLIENT_SECRET = "<REPLACE_WITH_CLIENT_SECRET>"
10+
11+
# REPLACE the following variable with what you added in the
12+
# "Authorization callback URL" field.
13+
REDIRECT_URI = "<REPLACE_WITH_REDIRECT_URI>"
14+
15+
16+
# In this method you'll ask the GitHub API for a URL to redirect the user
17+
# for authentication.
18+
def create_oauth_link():
19+
params = {
20+
"client_id": CLIENT_ID,
21+
"redirect_uri": REDIRECT_URI,
22+
"scope": "user",
23+
"response_type": "code",
24+
}
25+
26+
# This endpoint is defined in the GitHub documentation:
27+
# https://docs.github.com/en/free-pro-team@latest/developers/apps/authorizing-oauth-apps#1-request-a-users-github-identity
28+
endpoint = "https://github.com/login/oauth/authorize"
29+
30+
response = requests.get(endpoint, params=params)
31+
32+
# When you make the request above, GitHub will redirect you to their
33+
# website to input your credentials. Since you're doing this
34+
# programmatically, you need to get the `url` parameter and print it in
35+
# the console instead.
36+
url = response.url
37+
38+
return url
39+
40+
41+
# In this method you'll exchange the code you got from the GitHub API with
42+
# an access token.
43+
def exchange_code_for_access_token(code=None):
44+
params = {
45+
"client_id": CLIENT_ID,
46+
"client_secret": CLIENT_SECRET,
47+
"redirect_uri": REDIRECT_URI,
48+
"code": code,
49+
}
50+
51+
# Here you define the content type you're expecting to get.
52+
# In this case – JSON.
53+
headers = {"Accept": "application/json"}
54+
55+
# This endpoint is defined in the GitHub documentation:
56+
# https://docs.github.com/en/free-pro-team@latest/developers/apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github
57+
endpoint = "https://github.com/login/oauth/access_token"
58+
59+
response = requests.post(endpoint, params=params, headers=headers).json()
60+
return response["access_token"]
61+
62+
63+
# Finally in this method you'll print the user information re. its name,
64+
# username and number of private repositories.
65+
def print_user_info(access_token=None):
66+
# Now you need to send the `access_token` in the headers
67+
# when calling the API.
68+
headers = {"Authorization": f"token {access_token}"}
69+
70+
# This endpoint is defined in the GitHub documentation:
71+
# https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user
72+
endpoint = "https://api.github.com/user"
73+
74+
response = requests.get(endpoint, headers=headers).json()
75+
76+
# The response will be a dictionary with multiple user-related field.
77+
# You can try `print(response)` to see all of them.
78+
name = response["name"]
79+
username = response["login"]
80+
private_repos_count = response["total_private_repos"]
81+
print(
82+
f"{name} ({username}) | "
83+
f"number of private repositories: {private_repos_count}"
84+
)
85+
86+
87+
# So, one last time, step by step:
88+
# 1. Create a link to redirect the user to for authentication:
89+
link = create_oauth_link()
90+
print(f"Follow the link to start the authentication with GitHub: {link}")
91+
92+
# 2. Paste the code you got from GitHub after authenticating
93+
code = input("GitHub code: ")
94+
95+
# 3. Exchange that code with an access token
96+
access_token = exchange_code_for_access_token(code)
97+
print(f"Exchanged code {code} with access token: {access_token}")
98+
99+
# 4. Fetch user information
100+
print_user_info(access_token=access_token)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import requests
2+
3+
endpoint = "https://www.googleapis.com/books/v1/volumes"
4+
5+
# Define the search term you want to use.
6+
query = "moby dick"
7+
8+
# In the query parameters you can define:
9+
# 1. The number of books to return using the `maxResults` parameter.
10+
# 2. The query term to search for using the `q` parameter.
11+
params = {"q": query, "maxResults": 3}
12+
13+
# The response will contain a list of books that match your query.
14+
response = requests.get(endpoint, params=params).json()
15+
for book in response["items"]:
16+
# In order to fetch the title, published date and description,
17+
# you first need to fetch the volume.
18+
volume = book["volumeInfo"]
19+
20+
# You can fetch these and other attributes from the book using
21+
# the specific volume
22+
title = volume["title"]
23+
published = volume["publishedDate"]
24+
description = volume["description"]
25+
26+
print("%s (%s) | %s" % (title, published, description))

0 commit comments

Comments
 (0)