How do I make a PATCH request in Python?
21,582
Solution 1
With Requests, making PATCH requests is very simple:
import requests
r = requests.patch('http://httpbin.org/patch')
Solution 2
Seems to work in 2.7.1 as well.
>>> import urllib2
>>> request = urllib2.Request('http://google.com')
>>> request.get_method = lambda: 'PATCH'
>>> resp = urllib2.urlopen(request)
Traceback (most recent call last):
...
urllib2.HTTPError: HTTP Error 405: Method Not Allowed
Solution 3
I tried this in Python 3, and it seemed to work (but I don't have a server handy that supports the PATCH
request type):
>>> import http.client
>>> c = http.client.HTTPConnection("www.google.com")
>>> r = c.request("PATCH", "/index.html")
>>> print(r.status, r.reason)
405 Method Not Allowed
I'm assuming that the HTTP 405
is coming from the server and that it is "not allowed".
By the way, thanks for showing me the cool PATCH method in HTTP.
Solution 4
It is incredibly simple with httplib2:
import httplib2
http = httplib2.Http()
http.request("http://www.google.com", "PATCH", <patch content>)
I've used the httplib2 library myself in a professional REST framework that includes PATCH support. It supports Python 2.3 or later (including 3.x) and works beautifully!
Author by
Ricardo Augusto
Updated on July 12, 2020Comments
-
Ricardo Augusto almost 4 years
Is there a way to make a request using the
PATCH
HTTP method in Python?I tried using httplib, but it doesn't accept PATCH as method param.
-
Ricardo Augusto over 12 yearsThanks for the answer, I will try that later and mark as accepted. GitHub API accepted POST instead of PATCH, but I will give that a try and keep this for future.
-
Corey O. over 11 yearsGreat information. This is a simple little hack to make urllib2 use PATCH instead of POST. I don't know why PATCH hasn't been implemented as an option yet.
-
Hussain over 9 yearsHow do I log
r
. Should I just doself.log.info('Response: %s' % r)
? -
Ace McCloud about 8 yearshow can i pass string json data into this ?
-
No Sssweat about 8 years@PrasaanthNeelakandan over here are better answers Post JSON using Python Requests