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 requests.
If{'param1': 'value1', 'param2': 'value2'}
are the parameters, andhttps://somewebsite.com/
is the URL, then https://somewebsite.com/?param1=value1¶m2=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 a 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('https://pythonexamples.org/',
params=params)
print(response.url)
Explanation:
- The
params
dictionary contains the parameters you want to send in the URL. - The
requests.get()
method is used to send the GET request with the parameters appended to the URL. response.url
will print the final URL, including the parameters.
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('https://pythonexamples.org/',
params=params)
print(response.url)
Explanation:
- The request is sent to
https://pythonexamples.org/?p=943
with theparams
. - Since the resource at that URL redirects to another page, the final URL will be different from the original one.
- The
response.url
will give the final redirected URL.
Output
https://pythonexamples.org/python-requests-http-get/
3. Send Parameters with POST Request
You can also send parameters with a POST request. This can be useful when you need to send parameters in the body of the request.
Python Program
import requests
params = {'username': 'user123', 'password': 'securepassword'}
response = requests.post('https://pythonexamples.org/login', params=params)
print(response.url)
Explanation:
- Here, the parameters
username
andpassword
are included in the request URL. - When the request is processed, the
response.url
will show the URL with the parameters appended.
Output
https://pythonexamples.org/login?username=user123&password=securepassword
Summary
In this Python Tutorial, we learned how to send parameters in the URL using the requests module. We saw how to send parameters with GET requests, handle redirects, and even use them with POST requests.