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
#Send a GET request to https://apilearn.tukas.dev/api/products/ and print the status code.
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
#Fetch GET /api/products/ and print the total number of products in the database. The count is in the JSON response, not the length of the results list on this page.
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
#Fetch the product list and print the name and sell_price of the first product in the results.
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
#Make a GET request to https://apilearn.tukas.dev/api/products/. Use response.ok to print 'Success' if the request worked, or 'Failed: {status_code}' if it did not.
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
#Fetch the product list and print the value of the Content-Type 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'])