Explain Codes LogoExplain Codes Logo

Is there any way to do HTTP PUT request in Python?

python
requests
http-put
http-client
Anton ShumikhinbyAnton Shumikhin·Feb 25, 2025
TLDR

To execute an HTTP PUT request in Python with requests, use:

import requests response = requests.put('http://example.com/api/resource', json={'key': 'value'}) print(response.status_code) # Not 200? Start panicking!

Ensure requests is installed via pip install requests.

Accessorizing your request: Headers and authentication

Sending custom headers

To send custom headers such as Content-Type with your PUT request:

headers = {'Content-Type': 'application/json'} response = requests.put('http://example.com/api/resource', json={'key': 'value'}, headers=headers) # Tip: While headers are accessories for your request, it may not work without them. Like leaving home without your keys!

Pulling the keys out: Authentication

If you need to access a resource with authentication, requests has got you covered:

from requests.auth import HTTPBasicAuth response = requests.put( 'http://example.com/api/resource', json={'key': 'value'}, auth=HTTPBasicAuth('username', 'password') # Tip: Remember, carelessly exposing authentication tokens is like leaving your keys under the doormat. )

Tailoring the PUT request: Timeouts and error handling

Setting timeouts

For a more fine-grained control over your request, you can specify a timeout:

response = requests.put('http://example.com/api/resource', json={'key': 'value'}, timeout=5) # 5 seconds? That's 5 years in computer time!

Exception handling: Don't let errors sneak up on you!

Enclose your request in a try-except block to handle possible exceptions:

try: response = requests.put('http://example.com/api/resource', json={'key': 'value'}) except requests.exceptions.RequestException as e: print(e) # If you don't catch this exception, it will catch you!

Alternative HTTP PUT techniques

HTTP PUT with http.client

Sometimes, you need more control or don't want to use external libraries, use Python's http.client:

import http.client conn = http.client.HTTPConnection('example.com') headers = {'Content-Type': 'application/json'} # Don't forget your accessories! conn.request('PUT', '/api/resource', body='{"key": "value"}', headers=headers) # The body-parser at the server's end is a picky eater, feed it JSON response = conn.getresponse() print(response.status) # Anything other than 200 is "Houston, we have a problem" conn.close() # Always nice to clean up after yourself

The urllib.request way

An alternative is to use urllib.request from the Python standard library:

import urllib.request req = urllib.request.Request('http://example.com/api/resource', method='PUT') req.add_header('Content-Type', 'application/json') # Dress the request for the occasion! response = urllib.request.urlopen(req, data=b'{"key": "value"}') # Remember to feed it bytes, not string print(response.status) # Same old, same old. Status not 200? The server is unhappy!

Applying the PUT request: real-world implications

Inspecting response content

Sometimes, you need more information than just a status code. To inspect the response body:

response = requests.put('http://example.com/api/resource', json={'key': 'value'}) print(response.content) # If you see a JSON you didn't send, it's not an invasion. Just the server talking back.

Idempotency and safety

Remember that PUT requests are idempotent. Sending the same request multiple times elicits the same outcome, meaning they build robust and error-resistant applications.

Look for potential pitfalls

Keep an eye out for potential issues such as network problems, Content-Type header mismatches, or unique API requirements. Always handle potential exceptions and validate responses to ensure successful communication.