How do I perform a DELETE request using Requests?

Performing a DELETE request using the Requests library in Python is very straightforward. The Requests library allows you to send HTTP/1.1 requests extremely easily. To send a DELETE request, you will use the requests.delete() method, which sends a DELETE request to the specified URL.

Here's a basic example of how to perform a DELETE request using Requests:

import requests

# The URL you want to send the DELETE request to
url = 'https://your.api/endpoint'

# Additional headers if required (e.g., for authentication)
headers = {
    'Authorization': 'Bearer your-access-token',
    'Content-Type': 'application/json'
}

# Send the DELETE request
response = requests.delete(url, headers=headers)

# Check the response
if response.status_code == 200:
    print('Successfully deleted the resource')
else:
    print('Failed to delete the resource')
    print('Status code:', response.status_code)
    print('Response body:', response.text)

Important Points:

  • The url should be the endpoint you're targeting with your DELETE request.
  • The headers dictionary is optional and is used to pass additional HTTP headers. For instance, you may need to include an Authorization header for authenticated requests.
  • The requests.delete() function sends the DELETE request and returns a response object.
  • The response.status_code gives you the HTTP status code that indicates whether the request was successful.
  • The response.text provides the response body as text, which can be useful for debugging or handling specific server responses.

Handling Query Parameters:

If you need to include query parameters in the DELETE request, you can pass them as a dictionary to the params argument:

# Query parameters as a dictionary
params = {
    'param1': 'value1',
    'param2': 'value2'
}

# Send the DELETE request with query parameters
response = requests.delete(url, headers=headers, params=params)

Handling JSON Data:

While it's less common to send a payload with a DELETE request, if you need to send JSON data in the body of the DELETE request, you can use the json argument:

# JSON payload
json_data = {
    'key1': 'value1',
    'key2': 'value2'
}

# Send the DELETE request with a JSON payload
response = requests.delete(url, headers=headers, json=json_data)

Error Handling:

It's good practice to include error handling when working with HTTP requests. You can handle exceptions such as ConnectionError, Timeout, and RequestException to make your code more robust:

try:
    response = requests.delete(url, headers=headers)
    response.raise_for_status()  # Raises a HTTPError if the HTTP request returned an unsuccessful status code
except requests.exceptions.HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
except requests.exceptions.ConnectionError as conn_err:
    print(f'Connection error occurred: {conn_err}')
except requests.exceptions.Timeout as timeout_err:
    print(f'Timeout error occurred: {timeout_err}')
except requests.exceptions.RequestException as req_err:
    print(f'Error occurred: {req_err}')

Remember to install the Requests library if you haven't already by using pip:

pip install requests

This is how you perform a DELETE request using the Requests library in Python. Always ensure that you have the permission to perform such requests on the target endpoint and that you're complying with the API's terms of service.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon