Making Web Requests in Python
Making Web Requests in Python
Prerequisites:
with web requests in Python, we need to have the following:
Installation
Run this command in bash terminal or command prompt:
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.
Advanced Usage
1. Adding Headers
Headers are often required for authentication or providing additional information to the server.
import requests
url = 'https://api.example.com/data'
params = {'key': 'value'}
headers = {'Authorization': 'Bearer YOUR_TOKEN'}
try:
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}')