9.3 - Making API Requests
9.3.1 - How to Make GET and POST Requests Using Python
To interact with APIs in Python, you can use the requests
library to send GET and POST requests. Here’s how you can do it:
-
GET Request:
import requests
response = requests.get('https://api.example.com/resource')
data = response.json() # Process the JSON data received -
POST Request:
import requests
payload = {'key': 'value'}
response = requests.post('https://api.example.com/resource', data=payload)
print(response.text)
9.3.2 - Handling Query Parameters and Headers
Modify your requests to include query parameters or custom headers as follows:
-
Query Parameters:
response = requests.get('https://api.example.com/search', params={'query': 'web'})
-
Headers:
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
response = requests.get('https://api.example.com/secure', headers=headers)
9.3.3 - Understanding and Handling API Responses
Handling API responses involves checking the status codes and parsing the data received:
-
Check Status Code:
if response.status_code == 200:
print("Success!")
elif response.status_code == 404:
print("Not Found.") -
Parse JSON Response:
data = response.json()
print(data)