Making HTTP requests is a common task in web development and programming, allowing applications to communicate with servers and retrieve or send data. In Python, the requests
library provides a convenient and flexible way to make HTTP requests. Below are examples of making common types of HTTP requests using the requests
library.
1. Installing the requests
Library:
Before using the requests
library, you need to install it. Open your terminal or command prompt and run:
pip install requests
2. Making a GET Request:
A GET request is used to retrieve data from a specified resource.
import requests
url = 'https://api.example.com/data'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print(data)
else:
print('Error:', response.status_code)
3. Making a POST Request:
A POST request is used to submit data to be processed to a specified resource.
import requests
url = 'https://api.example.com/create'
data = {'name': 'John', 'age': 25}
response = requests.post(url, json=data)
if response.status_code == 201:
print('Data created successfully!')
else:
print('Error:', response.status_code)
4. Making a PUT Request:
A PUT request is used to update a resource or create a new resource if it does not exist.
import requests
url = 'https://api.example.com/update/1'
data = {'name': 'Updated Name', 'age': 26}
response = requests.put(url, json=data)
if response.status_code == 200:
print('Data updated successfully!')
else:
print('Error:', response.status_code)
5. Making a DELETE Request:
A DELETE request is used to request that a resource be removed.
import requests
url = 'https://api.example.com/delete/1'
response = requests.delete(url)
if response.status_code == 204:
print('Data deleted successfully!')
else:
print('Error:', response.status_code)
6. Handling Query Parameters:
You can include query parameters in your requests.
import requests
url = 'https://api.example.com/search'
params = {'query': 'python', 'limit': 10}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
print(data)
else:
print('Error:', response.status_code)
7. Handling Headers:
You can include custom headers in your requests.
import requests
url = 'https://api.example.com/data'
headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
print(data)
else:
print('Error:', response.status_code)
These examples cover the basics of making HTTP requests using the requests
library in Python. Always refer to the documentation of the API you are working with for specific details on authentication, endpoints, and request parameters.