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
#Send a GET request to /api/echo/ and print the full JSON response. Notice which headers the server received from your default request.
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
#Send a GET to /api/echo/ with a custom header X-Client-Name set to "my-script". Verify it appears in the echo response by printing its value from the response.
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
#Send a request to /api/echo/ with User-Agent set to "DataCollector/2.0". Print the User-Agent value from the echo response to confirm it was received.
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
#Send a POST to /api/echo/ with a JSON body containing keys "name" and "value". Print the method and body fields from the echo response.
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
#Fetch GET /api/products/ and print the Content-Type and any header that contains "Allow" in its name. If "Allow" is not present, print "Not found".
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)