Working with Query Parameters in Requests
Query parameters allow you to pass data to a URL to retrieve specific information from a server. The Requests library in Python makes handling query parameters simple and efficient.
Sending Data Using URL Parameters
To send query parameters, you can include them as a dictionary in the params
argument of a requests.get()
call. The library automatically encodes the parameters and appends them to the URL.
Example: Basic Query Parameters
import requests
# Define URL and parameters
url = "https://jsonplaceholder.typicode.com/posts"
params = {"userId": 1}
# Send GET request with query parameters
response = requests.get(url, params=params)
# Print the URL and response
print("URL:", response.url)
print("Response JSON:", response.json())
Output
URL: https://jsonplaceholder.typicode.com/posts?userId=1
Response JSON: [
{
"userId": 1,
"id": 1,
"title": "Sample Title",
"body": "Sample Body"
},
...
]
Encoding Parameters
If your query parameters include special characters, the Requests library automatically encodes them to ensure proper formatting of the URL.
Example: Encoding Parameters
# Define parameters with special characters
params = {"search": "Python@requests", "type": "tutorial"}
# Send GET request with encoded parameters
response = requests.get("https://example.com/search", params=params)
# Print the URL
print("Encoded URL:", response.url)
Output
Encoded URL: https://example.com/search?search=Python%40requests&type=tutorial
Passing Multiple Parameters
You can pass multiple parameters in the params
dictionary to refine your request further.
Example: Multiple Query Parameters
params = {"userId": 1, "completed": True}
response = requests.get("https://jsonplaceholder.typicode.com/todos", params=params)
print("URL:", response.url)
print("Response JSON:", response.json())
Try It Yourself
Problem 1: Fetch Specific Users
Send a GET request to https://jsonplaceholder.typicode.com/users
to fetch users from a specific city (e.g., “Lebsackbury”).
Show Solution
import requests
# Define parameters
params = {"address.city": "Lebsackbury"}
# Send GET request
response = requests.get("https://jsonplaceholder.typicode.com/users", params=params)
# Print response
print("URL:", response.url)
print("Response JSON:", response.json())
Problem 2: Search with Special Characters
Send a GET request to https://example.com/search
with query parameters containing special characters (e.g., “Python@2024”).
Show Solution
import requests
# Define parameters
params = {"query": "Python@2024", "category": "programming"}
# Send GET request
response = requests.get("https://example.com/search", params=params)
# Print encoded URL
print("Encoded URL:", response.url)
Query parameters are a powerful way to customize API requests and retrieve targeted data. Practice encoding parameters and passing multiple values to master their usage!