Python Requests Library: Get Parameters
If you're working with APIs in Python, chances are you'll need to make HTTP requests to retrieve data. The Requests library is a popular HTTP client library that makes it easy to send HTTP requests in Python. One common use case is sending GET requests with parameters.
Using the Requests Library
To use the Requests library, you must first install it. You can install it by running the following command in your terminal:
pip install requests
Once you have the library installed, you can import it in your Python code:
import requests
Sending GET Requests
When you want to send a GET request with parameters, you can use the requests.get()
function. The function takes two arguments: the URL to send the request to and a dictionary of parameters.
import requests
url = 'https://example.com/api'
params = {'param1': 'value1', 'param2': 'value2'}
response = requests.get(url, params=params)
print(response.json())
In the example above, we're sending a GET request to https://example.com/api
with two parameters: param1
and param2
. The response is returned as JSON.
URL Encoding Parameters
Note that the parameters are automatically URL encoded by the Requests library, so you don't need to worry about manually encoding them. If you want to see the URL that is being sent, you can print the response.url
attribute.
import requests
url = 'https://example.com/api'
params = {'param1': 'value1', 'param2': 'value2'}
response = requests.get(url, params=params)
print(response.url)
The output will be something like: https://example.com/api?param1=value1¶m2=value2
.
Multiple Ways to Send GET Requests
There are multiple ways to send GET requests with parameters using the Requests library. Another common way is to include the parameters directly in the URL:
import requests
url = 'https://example.com/api?param1=value1¶m2=value2'
response = requests.get(url)
print(response.json())
This approach can be handy when you have a simple URL and only a few parameters.