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
'http://www.neo4j.com/?ref=mark-blog'
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
'https://www.youtube.com/watch?v=Y-Wqna-hC2Y&list=RDhlznpxNGFGQ&index=2&ref=mark-blog'
I’m sure I’ll be using this code snippet in future!
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.