Python · API · Beginner
Pagination
Iterate through multi-page API responses to collect all results.
Quick topic start and explanations before exercises (exercises below):
Pagination patterns
#Pagination reference
#Exercises:
Fetch a specific page
#Fetch page 3 of the product list with page_size=10. Print the name of each product on that page.
import requests BASE_URL = 'https://apilearn.tukas.dev' # Fetch page 3 and print product names
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
params = {'page': 3, 'page_size': 10}
response = requests.get(f'{BASE_URL}/api/products/', params=params)
for product in response.json()['results']:
print(product['name'])
Calculate total pages
#Fetch the product list with page_size=20. Calculate and print the total number of pages needed to see all products.
import requests BASE_URL = 'https://apilearn.tukas.dev' # Calculate total pages for page_size=20
Solution
import requests
import math
BASE_URL = 'https://apilearn.tukas.dev'
PAGE_SIZE = 20
data = requests.get(f'{BASE_URL}/api/products/', params={'page_size': PAGE_SIZE}).json()
total_pages = math.ceil(data['count'] / PAGE_SIZE)
print(f'{data["count"]} products across {total_pages} pages')
Collect all products from a category
#Collect all products in the "kitchen" category into a list by following the next URL. Print the total number of products collected.
import requests
BASE_URL = 'https://apilearn.tukas.dev'
all_products = []
url = f'{BASE_URL}/api/products/'
params = {'category': 'kitchen'}
# Paginate through all kitchen products
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
all_products = []
url = f'{BASE_URL}/api/products/'
params = {'category': 'kitchen'}
while url:
data = requests.get(url, params=params).json()
all_products.extend(data['results'])
url = data['next']
params = {}
print(len(all_products))
Collect all product names
#Collect the names of all products in the entire catalog (all pages) into a list. Print the total count and the name of the last product in the list.
import requests BASE_URL = 'https://apilearn.tukas.dev' # Collect all product names across all pages
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
all_names = []
url = f'{BASE_URL}/api/products/'
while url:
data = requests.get(url).json()
for product in data['results']:
all_names.append(product['name'])
url = data['next']
print(len(all_names))
print(all_names[-1])
Find the most expensive product
#Find the most expensive product in the catalog without fetching all pages. Print its name and price.
import requests BASE_URL = 'https://apilearn.tukas.dev' # Find the most expensive product efficiently
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
params = {'ordering': '-price', 'page_size': 1}
data = requests.get(f'{BASE_URL}/api/products/', params=params).json()
product = data['results'][0]
print(product['name'])
print(product['price'])