API filters and pagination
Filtering or paginating an API response without manually assembling a URL.
Requests · Const
params supplies query-string data to Requests calls. Provide a dictionary, tuple list, or bytes; Requests encodes it into the URL and returns a Response.
Pass query-string data through the params argument when creating a request. Requests accepts mappings, tuple lists, or bytes, encodes the values into the URL, and returns the resulting Response; list values produce repeated query keys.
requests.request(method, url, **kwargs)
requests.get(url, params=None, **kwargs)| Name | Type | Description |
|---|---|---|
params | _t.ParamsType = None | Dictionary, list of tuples, or bytes to send in the query string for the request. |
Response object
params accepts a dictionary, a list of key-value tuples, or raw bytes for query-string data.params keyword to attach query arguments without manually concatenating them to the URL.url attribute.None values are omitted rather than serialized into the query string.import requests
response = requests.get(
"https://httpbin.org/get",
params={"page": 2, "tag": ["python", "http"]},
)
print(response.url)Sends query parameters and prints the resulting URL.
Filtering or paginating an API response without manually assembling a URL.
Sending repeated query keys such as tags or identifiers.
Adding optional parameters while omitting unset values.
params?params supplies data for the request URL's query string. The API accepts a dictionary, a list of tuples, or bytes, and the request methods return a Response.
Follow-up: How would you encode repeated query keys? Use a list value in a dictionary, such as {"tag": ["python", "http"]}, which produces multiple tag entries.
requests.get?For a GET request, pass params as a keyword argument, for example requests.get(url, params=payload). Requests incorporates the supplied values into the URL rather than placing them in the request body.
Follow-up: How can you inspect the encoded result? Read the returned response's url attribute.
None-valued dictionary entries?A dictionary key whose value is None is excluded from the URL's query string. This lets optional filters remain absent without manually rebuilding the parameter mapping.
Follow-up: What happens when a value is a list? Requests emits the same query key once for each list element.
requests.requestrequests.getrequests.postrequests.Session.paramsrequests.Request.preparerequests.PreparedRequest.prepare_url