Python · API · Beginner
Headers and the Echo Endpoint
Add custom HTTP headers to requests and use the echo endpoint to inspect what you send.
Quick topic start and explanations before exercises (exercises below):
Using the echo endpoint
#Headers and echo reference
#Exercises:
Inspect the echo response
#import requests BASE_URL = 'https://apilearn.tukas.dev' # Send GET to /api/echo/ and print the response JSON
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/echo/')
import json
print(json.dumps(response.json(), indent=2))
Send a custom header
#import requests BASE_URL = 'https://apilearn.tukas.dev' # Add X-Client-Name header and verify it in the echo response
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
headers = {'X-Client-Name': 'my-script'}
response = requests.get(f'{BASE_URL}/api/echo/', headers=headers)
data = response.json()
print(data['headers']['X-Client-Name'])
Change the User-Agent
#import requests BASE_URL = 'https://apilearn.tukas.dev' # Set User-Agent and verify in echo
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
headers = {'User-Agent': 'DataCollector/2.0'}
response = requests.get(f'{BASE_URL}/api/echo/', headers=headers)
print(response.json()['headers']['User-Agent'])
POST with a JSON body
#import requests
BASE_URL = 'https://apilearn.tukas.dev'
payload = {'name': 'test', 'value': 99}
# POST to /api/echo/ and print method and body from response
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
payload = {'name': 'test', 'value': 99}
response = requests.post(f'{BASE_URL}/api/echo/', json=payload)
data = response.json()
print(data['method'])
print(data['body'])
Read response headers
#import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
# Print Content-Type and look for an Allow header
Solution
import requests
BASE_URL = 'https://apilearn.tukas.dev'
response = requests.get(f'{BASE_URL}/api/products/')
print(response.headers['Content-Type'])
allow = response.headers.get('Allow', 'Not found')
print(allow)