Requests get python parameters
When using the Python Requests module, it is common to use the GET
method to retrieve data from a web server. The GET
method allows you to specify parameters in the URL, which the server can use to filter the results it returns.
Passing Parameters
There are two ways to pass parameters to a GET
request using Requests:
- Passing parameters as a dictionary using the
params
keyword argument. - Embedding parameters into the URL itself.
The params
keyword argument is the preferred way of passing parameters, as it automatically handles escaping and encoding for you. Here's an example:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)
This will send a GET
request to http://httpbin.org/get?key1=value1&key2=value2
, which will return a JSON response containing the parameters you passed in.
You can also embed parameters into the URL itself, like this:
import requests
r = requests.get('http://httpbin.org/get?key1=value1&key2=value2')
print(r.url)
This will send a GET
request to http://httpbin.org/get?key1=value1&key2=value2
, which will return a JSON response containing the parameters you passed in.
Retrieving Parameters
To retrieve parameters from a GET
request using Requests, you can use the args
attribute of the Response
object. Here's an example:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.json()['args'])
This will send a GET
request to http://httpbin.org/get?key1=value1&key2=value2
, and print out the parameters that were received by the server.
In summary, passing parameters in a GET
request using Python Requests is simple and straightforward, and can be done either by passing a dictionary to the params
keyword argument or by embedding the parameters into the URL itself.