How to Perform a DELETE Request Using Requests
The Python Requests library makes performing DELETE requests simple and straightforward. Use the requests.delete()
method to send DELETE requests to remove resources from APIs or web services.
Basic DELETE Request
Here's a simple example of performing a DELETE request:
import requests
# Basic DELETE request
url = 'https://api.example.com/users/123'
response = requests.delete(url)
# Check if the request was successful
if response.status_code == 204: # 204 No Content is common for successful DELETE
print('Resource deleted successfully')
elif response.status_code == 404:
print('Resource not found')
else:
print(f'Delete failed with status code: {response.status_code}')
DELETE Request with Authentication
Most APIs require authentication for DELETE operations:
import requests
url = 'https://api.example.com/posts/456'
# Using Bearer token authentication
headers = {
'Authorization': 'Bearer your-access-token',
'Content-Type': 'application/json'
}
response = requests.delete(url, headers=headers)
# Handle the response
if response.status_code in [200, 204]:
print('Successfully deleted the resource')
if response.text: # Some APIs return confirmation data
print('Response data:', response.json())
else:
print(f'Failed to delete resource: {response.status_code}')
print('Error message:', response.text)
DELETE Request with Query Parameters
Add query parameters when the API requires additional context:
import requests
url = 'https://api.example.com/comments'
# Query parameters to specify which resource to delete
params = {
'user_id': '123',
'post_id': '456',
'force': 'true' # Force delete even if resource has dependencies
}
headers = {'Authorization': 'Bearer your-token'}
response = requests.delete(url, headers=headers, params=params)
# The final URL will be: https://api.example.com/comments?user_id=123&post_id=456&force=true
DELETE Request with JSON Body
Some APIs accept a JSON payload with DELETE requests for additional context:
import requests
url = 'https://api.example.com/batch-delete'
headers = {
'Authorization': 'Bearer your-token',
'Content-Type': 'application/json'
}
# JSON data specifying what to delete
delete_data = {
'resource_ids': [123, 456, 789],
'reason': 'User requested deletion',
'permanent': True
}
response = requests.delete(url, headers=headers, json=delete_data)
if response.status_code == 200:
print('Batch delete completed')
print('Deleted items:', response.json())
Comprehensive Error Handling
Implement robust error handling for production code:
import requests
from requests.exceptions import ConnectionError, Timeout, RequestException
def delete_resource(resource_id, api_token):
url = f'https://api.example.com/resources/{resource_id}'
headers = {'Authorization': f'Bearer {api_token}'}
try:
response = requests.delete(url, headers=headers, timeout=10)
# Check for HTTP errors
response.raise_for_status()
# Handle successful deletion
if response.status_code == 204:
return {'success': True, 'message': 'Resource deleted successfully'}
elif response.status_code == 200:
return {'success': True, 'data': response.json()}
except requests.exceptions.HTTPError as e:
if response.status_code == 404:
return {'success': False, 'error': 'Resource not found'}
elif response.status_code == 403:
return {'success': False, 'error': 'Permission denied'}
else:
return {'success': False, 'error': f'HTTP error: {e}'}
except ConnectionError:
return {'success': False, 'error': 'Connection failed'}
except Timeout:
return {'success': False, 'error': 'Request timed out'}
except RequestException as e:
return {'success': False, 'error': f'Request failed: {e}'}
# Usage example
result = delete_resource('123', 'your-api-token')
print(result)
Common HTTP Status Codes for DELETE
- 200 OK: Successful deletion with response body
- 204 No Content: Successful deletion without response body
- 404 Not Found: Resource doesn't exist
- 403 Forbidden: Insufficient permissions
- 409 Conflict: Resource cannot be deleted due to dependencies
- 422 Unprocessable Entity: Invalid request data
Real-World Example: GitHub API
Here's a practical example using the GitHub API to delete a repository:
import requests
def delete_github_repo(owner, repo, token):
url = f'https://api.github.com/repos/{owner}/{repo}'
headers = {
'Authorization': f'token {token}',
'Accept': 'application/vnd.github.v3+json'
}
response = requests.delete(url, headers=headers)
if response.status_code == 204:
print(f'Repository {owner}/{repo} deleted successfully')
return True
else:
print(f'Failed to delete repository: {response.status_code}')
print('Error:', response.json().get('message', 'Unknown error'))
return False
# Usage (be careful with this!)
# delete_github_repo('username', 'repo-name', 'your-github-token')
Installation
Install the Requests library if you haven't already:
pip install requests
Best Practices
- Always check status codes - Don't assume the request succeeded
- Use appropriate timeouts - Prevent hanging requests
- Handle authentication properly - Never hardcode tokens in production
- Implement retry logic - For handling temporary failures
- Log DELETE operations - For audit trails and debugging
- Confirm permissions - Ensure you have the right to delete resources
Remember that DELETE operations are typically irreversible, so always verify you're targeting the correct resource before executing the request.