How to use urllib2.urlopen to make POST request without data argument

airfang picture airfang · Mar 2, 2012 · Viewed 27.7k times · Source

I am trying to use urllib2.urlopen to perform GET and POST requests via the Facebook Graph API. I noticed from here: https://stackoverflow.com/questions/2690723/facebook-graph-api-and-django that I can perform GET request fairly easily.

And from here: How to send a POST request using django? and the Python docs http://docs.python.org/library/urllib2.html it seems that it needs the data param to perform a POST request.

But looking at the Facebook's API: http://developers.facebook.com/docs/reference/api/event/#invited it says

You can invite users to an event by issuing an HTTP POST to /EVENT_ID/invited/USER_ID

I am not sure how I could do that with urlopen, since opening this url directly is going to only check if the user has been invited, as mentioned on the API page:

You can check whether a specific user has been invited to an event by issuing an HTTP GET to /EVENT_ID/invited/USER_ID:

Appreciate the input.

Answer

Christian picture Christian · Mar 3, 2012

It sounds like you want to send an empty POST request, even though urllib2.urlopen() only sends a post when you specify the data parameter.

It seems like it actually sends an empty POST if you set data="", and GET request only when data=None:

urllib2.urlopen("http://127.0.0.1:8000", data="")
"POST / HTTP/1.1" 501 - 

urllib2.urlopen("http://127.0.0.1:8000", data=None)
"GET / HTTP/1.1" 200 -

Hope that helps. I got the response printouts from the little HTTP server they have an example for here: http://docs.python.org/library/simplehttpserver.html