Python · API · Beginner
Redirects
Understand HTTP redirects, inspect redirect chains, and control whether requests follows them.
Quick topic start and explanations before exercises (exercises below):
Working with redirects in practice
#Redirect reference
#Exercises:
Follow a redirect
#Send a GET request to /api/redirect/ (with default redirect following). Print the final status code and the URL you landed on.
import requests BASE_URL = 'https://apilearn.tukas.dev' # Follow the redirect and print status_code and final URL
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/redirect/')
print(response.status_code)
print(response.url)
See the raw redirect
#Send a GET to /api/redirect/ with allow_redirects=False. Print the status code and the Location header.
import requests BASE_URL = 'https://apilearn.tukas.dev' # Disable redirect following and inspect the redirect response
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/redirect/', allow_redirects=False)
print(response.status_code)
print(response.headers['Location'])
Inspect the redirect history
#Send a GET to /api/redirect/ and print all intermediate responses from response.history. For each, print the status code and URL. Then print the final status code and URL.
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/redirect/')
# Print each hop in response.history, then the final response
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/redirect/')
for hop in response.history:
print(hop.status_code, hop.url)
print(response.status_code, response.url)
Count hops in a chain
#Send a GET to /api/redirect/chain/5/ and print how many redirects occurred. Then print the URL of each hop in the chain.
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/redirect/chain/5/')
# Print number of hops and each URL in the chain
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/redirect/chain/5/')
print(f'Hops: {len(response.history)}')
for hop in response.history:
print(hop.url)
Compare redirect types
#Compare /api/redirect/ and /api/redirect/permanent/ side by side. For each, use allow_redirects=False and print the status code.
import requests BASE_URL = 'https://apilearn.tukas.dev' # Check status codes of both redirect types without following
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
r_temp = requests.get(f'{BASE_URL}/api/redirect/', allow_redirects=False)
r_perm = requests.get(f'{BASE_URL}/api/redirect/permanent/', allow_redirects=False)
print(f'/api/redirect/ → {r_temp.status_code}')
print(f'/api/redirect/permanent/ → {r_perm.status_code}')