Python Requests Library Delete
If you're working with APIs and want to delete data from a server, you can use Python Requests library. Requests is a simple, easy-to-use HTTP library that allows you to send HTTP/1.1 requests using Python.
Using requests.delete()
To delete data from a server, you can use the requests.delete()
method. This method sends an HTTP DELETE request to the specified URL.
Here's an example:
import requests
url = 'https://api.example.com/data/123'
response = requests.delete(url)
In this example, we're sending a DELETE request to the URL https://api.example.com/data/123
. The requests.delete()
method returns a Response
object that contains the server's response to the request.
You can also add parameters to the DELETE request using the params
parameter:
import requests
url = 'https://api.example.com/data'
params = {'id': '123'}
response = requests.delete(url, params=params)
This sends a DELETE request to the URL https://api.example.com/data
, with the parameter id=123
.
Passing headers and authentication
You can pass headers or authentication information to the requests.delete()
method using the headers
and auth
parameters respectively.
import requests
url = 'https://api.example.com/data/123'
headers = {'Authorization': 'Bearer my_access_token'}
response = requests.delete(url, headers=headers)
In this example, we're passing an access token in the Authorization
header.
Handling errors
If the server returns an error response (e.g. 404 Not Found), the requests.delete()
method will raise a HTTPError
exception. You can handle this exception using a try-except block:
import requests
url = 'https://api.example.com/data/123'
try:
response = requests.delete(url)
response.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error.response.status_code, error.response.text)
This code sends a DELETE request to the URL https://api.example.com/data/123
, and if the server returns an error response, it prints the status code and response text.