· python

Python: Add query parameters to a URL

I was recently trying to automate adding a query parameter to a bunch of URLS and came across a neat approach a long way down this StackOverflow answer, that uses the PreparedRequest class from the requests library.

Let’s first get the class imported:

from requests.models import PreparedRequest
req = PreparedRequest()

And now let’s use use this class to add a query parameter to a URL. We can do this with the following code:

url = "http://www.neo4j.com"
params = {'ref':"mark-blog"}
req.prepare_url(url, params)

And then we need to access the url attribute to see our new URL:

>>> req.url

Neat! We can also use this approach to add parameters to URLs that already have existing ones. For example, we could update this YouTube URL:

url = "https://www.youtube.com/watch?v=Y-Wqna-hC2Y&list=RDhlznpxNGFGQ&index=2"
params = {'ref':"mark-blog"}
req.prepare_url(url, params)

And let’s see what the updated URL looks like:

>>> req.url

I’m sure I’ll be using this code snippet in future!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket