The requests
module is one of the simplest and most popular ways to perform HTTP requests in Python. It is easy to use and allows you to interact with web APIs or download data from the Internet in just a few steps.
Installation
To install requests
, simply use pip
:
pip install requests
Making a GET Request
A GET request is used to retrieve data from a server. Here's a basic example:
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
print(response.text)
else:
print(f'Error: {response.status_code}')
Sending Data with a POST Request
If you need to send data to a server, you can use a POST request:
import requests
url = 'https://api.example.com/submit'
data = {'name': 'Mario', 'age': 30}
response = requests.post(url, data=data)
if response.ok:
print('Data sent successfully')
else:
print('Error sending data')
Handling Exceptions
It’s good practice to handle possible errors during requests, such as connection issues:
import requests
try:
response = requests.get('https://api.example.com/data', timeout=5)
response.raise_for_status()
print(response.json())
except requests.exceptions.HTTPError as errh:
print(f'HTTP Error: {errh}')
except requests.exceptions.ConnectionError as errc:
print(f'Connection Error: {errc}')
except requests.exceptions.Timeout as errt:
print(f'Request timed out: {errt}')
except requests.exceptions.RequestException as err:
print(f'General Error: {err}')
Conclusion
The requests
module makes it simple and straightforward to work with HTTP in Python. With just a few commands, you can make requests, send data, and handle errors, making your applications more robust and reliable.