Python · API · Beginner
Your First Request
Make your first HTTP request with the requests library and read the response.
Quick topic start and explanations before exercises (exercises below):
Reading the response
#Response object quick reference
#Exercises:
Make your first request
#import requests BASE_URL = 'https://apilearn.tukas.dev' # Your code here
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
print(response.status_code)
Count the products
#import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
data = response.json()
# Print the total product count
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
data = response.json()
print(data['count'])
Read the first product
#import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
data = response.json()
# Print name and sell_price of the first product
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
data = response.json()
first = data['results'][0]
print(first['name'])
print(first['sell_price'])
Check for success
#import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
# Check response.ok and print the appropriate message
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
if response.ok:
print('Success')
else:
print(f'Failed: {response.status_code}')
Read a response header
#import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
# Print the Content-Type header
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
print(response.headers['Content-Type'])