Basic Programming: Sending POST requests using Python-Requests

So because I earlier wrote an example of sending GET requests, I figure I’d also supply an example of sending POST requests, because there is a right way to do this, and a way that is usually wrong. Again, it comes down to the difference between doing this with string manipulation, and just using a dictionary.

First, lets show an example of doing it wrong.

import requests
url = "http://localhost:9000/lol.php"
data = "param=value"
r = requests.post(url=url, data=data)

So this will send a POST request, and it will send those parameters, however sometimes the receiving end won’t like them very much. It also means messing about with strings, which sucks. Sending raw POST data does have its uses, but most of the time it just won’t work out the way you hoped.

Instead, here is the proper way to do it, using a dictionary to prepare the POST data to be sent.

import requests
url = "http://localhost:9000/lol.php"
data = {"param": "value"}
r = requests.post(url=url, data=data)

This tends to work a lot better, and is the actual proper way to go about it. It also will automagically do the URL encoding and send it as form data, which is really quite useful.

You can also, of course, send both POST and GET parameters in a POST request without resorting to hacky string manipulation, like so.

import requests

url = "http://127.0.0.1:9000/lol.php"
params = {"get_param": "value"}
payload = {"post_param": "value"}

r = requests.post(url=url, params=params, data=payload)

Hopefully someone finds this useful, even if it seems glaringly obvious to most. It will be referred back to later when I’m writing about something else.

%d bloggers like this: