Last modified: Nov 12, 2024 By Alexander Williams

Python requests.DELETE(): Guide to Making HTTP DELETE Requests

The requests.delete() method in Python is used to send HTTP DELETE requests to remove resources from a server. It's a crucial part of RESTful API interactions alongside GET, POST, and PUT methods.

Basic DELETE Request Syntax

Here's a simple example of how to make a DELETE request:


import requests

url = "https://api.example.com/items/123"
response = requests.delete(url)

print(response.status_code)


204

DELETE Request with Headers

You can include custom headers in your DELETE request for authentication or additional information. Here's how to add headers to your request:


headers = {
    'Authorization': 'Bearer your-token',
    'Content-Type': 'application/json'
}

response = requests.delete(url, headers=headers)
print(response.status_code)

Handling Response Status

It's important to check the status code of your DELETE request to ensure it was successful. Common status codes for DELETE requests are:

200 (OK) - Resource successfully deleted 204 (No Content) - Resource deleted, no content to return 404 (Not Found) - Resource not found 403 (Forbidden) - Not authorized to delete

DELETE Request with Authentication


auth = ('username', 'password')
response = requests.delete(url, auth=auth)

if response.status_code == 204:
    print("Resource successfully deleted")
else:
    print(f"Failed to delete resource: {response.status_code}")

Using Proxy with DELETE Requests

When needed, you can use a proxy with your DELETE requests:


proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'https://proxy.example.com:8080'
}

response = requests.delete(url, proxies=proxies)

Error Handling

Always implement proper error handling in your DELETE requests:


try:
    response = requests.delete(url)
    response.raise_for_status()
    print("Delete successful")
except requests.exceptions.RequestException as e:
    print(f"Delete failed: {e}")

Conclusion

The requests.delete() method is a powerful tool for removing resources through HTTP requests. Remember to handle responses appropriately and implement proper error checking in your applications.