Basic Programming: Sending GET Parameters using Python-Requests

Recently I had a need to look up something in the requests documentation, and I realized I had been doing something incredibly basic wrong for literally years.

I had been using string manipulation of the URL to construct GET parameters, while I should have been using the “params” argument. Turns out, doing it via the “params” argument is far simpler than the stupidity I was doing, and results in far cleaner code.

Below, the code block outlines the incorrect way of doing it, which I had been doing for years. In order to alter values or parameters being sent in the URL, I would have to take the URL as a string and manipulate it.

import requests
url = "http://127.0.0.1:9000/lol.php?param=value"
r = requests.get(url=url)

Instead, we can use the handy “params” dictionary, which has been there since the beginning, and allows us to construct URL parameters in a much more sensible fashion. It also entirely removes the need for horrendous string manipulation hacks, when we can just change the value in the dictionary.

The below code block outlines this.

import requests
url = "http://127.0.0.1:9000/lol.php"
params = {"param": "value"}
r = requests.get(url=url, params=params)

Much cleaner, and much simpler to update the parameters later. No more string fuckery going on.

I’ve decided that every time I come across a small mistake or useful thing, I’ll add a note about it here. Probably so I can come find it again later.

%d bloggers like this: