Making Web Requests in Python
Fringe Benefits :
web requests in Python, we need to have the following:
1. Python Installed: Download and install Python from python.org.
2. requests Library: Install the library using the command below if it’s not already installed.
Installation
Run this command in bash terminal or command prompt:
Code : pip install requests
How to Make Web Requests
1. Import the requests Library
Start by importing the library into your script:
code :import requests
2. Sending a GET Request
GET requests are used to fetch data from a server.
Example:
code : response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
Key Points:
- requests.get(url) sends a GET request to the specified URL.
- The response object holds the server’s response to the request.
Accessing Response Data:
code :
print(response.status_code) # Displays HTTP status code (e.g., 200 for success)
print(response.text) # Raw text response from the server
print(response.json( )) # Converts JSON data into a Python dictionary
Advanced Usage
1. Adding Headers
Headers are often required for authentication or providing additional information to the server.
Code : headers = {'Authorization': 'Bearer YOUR_TOKEN'}
response = requests.get('https://api.example.com/data', headers=headers)
Point to be noted while web requesting are:
1. Set Timeouts: Always set a timeout to avoid indefinitely hanging requests.
2. Validate Inputs: Ensure the URL and payload data are validated.
3. Handle Exceptions: Anticipate and handle network issues, timeouts, and server errors.
4. Respect Rate Limits: Be mindful of API rate limits specified in the documentation.
5. Secure API Keys: Avoid hardcoding sensitive credentials in your scripts.
6. Read API Documentation: Familiarize yourself with the API’s capabilities and limitations.
Example: Combining Everything
Here’s an example that combines headers, query parameters, and error handling:
code:
import requests
url = 'https://api.example.com/data'
params = {'key': 'value'}
headers = {'Authorization': 'Bearer YOUR_TOKEN'}
response = requests.get(url, headers=headers, params=params, timeout=10)
response.raise_for_status()
data = response.json()
print ('Data retrieved:', data)
except requests.exceptions.RequestException as e:
print(f'An error occurred: {e}')