129. Accessing APIs with requests
1. Basic GET Request
import requests
# Make a GET request to an API
response = requests.get("https://api.github.com")
# Check if the request was successful
if response.status_code == 200:
print("Response Status Code:", response.status_code)
print("Response Body:", response.json()) # Get the response as JSON
else:
print(f"Failed to retrieve data. Status code: {response.status_code}")2. GET Request with Query Parameters
import requests
# Define the API endpoint and parameters
url = "https://api.openweathermap.org/data/2.5/weather"
params = {
'q': 'London',
'appid': 'your_api_key_here' # Replace with your actual API key
}
# Make a GET request with parameters
response = requests.get(url, params=params)
# Check if the request was successful
if response.status_code == 200:
print("Weather data:", response.json())
else:
print("Failed to retrieve weather data:", response.status_code)3. POST Request
4. Handling Response JSON
5. Error Handling in Requests
6. Sending Headers with Requests
7. Handling Cookies in Requests
8. Timeouts in Requests
9. File Upload with Requests
10. Session Object for Persistent Connections
Summary of Key Points:
Last updated