Send Parameters in URL using Python Requests


Python Requests - Send Parameters in URL

To send parameters in URL, write all parameter key:value pairs to a dictionary and send them as params argument to any of the GET, POST, PUT, HEAD, DELETE or OPTIONS request.

If
{'param1': 'value1', 'param2': 'value2'} are the parameters, and
https://somewebsite.com/ is the url
then https://somewebsite.com/?param1=value1&param2=value2 would be our final url.

Examples

1. Send Parameters in URL using Python Requests

In the following example, we are sending a parameter in the URL with GET request. To check if the URL is formatted correctly, you can print it from the response object using response.url as shown in the below program.

Python Program

import requests

params = {'p': '9431'}
response = requests.get('/',
            params=params)
print(response.url)

Output

https://pythonexamples.org/?p=9431

2. When the URL gets Redirected

In the following example, we will send a parameter, where the final URL gets redirected.

Python Program

import requests

params = {'p': '943'}
response = requests.get('/',
            params=params)
print(response.url)

There is a post published with the id 943. Hence when you request for the resource at /?p=943, it gets redirected to /python-requests-http-get/ and hence would be our final URL in the response.

Output

https://pythonexamples.org/python-requests-http-get/

Summary

In this Python Tutorial, we learned how to send parameters in URL using requests module.