python requests url parameters

Python Requests URL Parameters

When making HTTP requests using Python's requests library, it is often necessary to include URL parameters to customize the request. These parameters can be used to filter data, sort data, and more. Here's how to add URL parameters to a request using Python's requests library:

Using the params parameter in the requests.get() method

The easiest way to add URL parameters to a request is by using the params parameter in the requests.get() method. This parameter takes a dictionary of key-value pairs, where the keys are the parameter names and the values are the parameter values.


import requests

url = 'https://example.com/api/data'
params = {'filter': 'status', 'sort': 'asc'}

response = requests.get(url, params=params)

print(response.json())

In this example, we're making a GET request to https://example.com/api/data with two URL parameters: filter=status and sort=asc. The response from the server is then printed as JSON.

Using string concatenation to build the URL

Another way to add URL parameters is by manually building the URL using string concatenation. This method is useful when you need to add only a single parameter or when you need more control over the parameter value formatting.


import requests

url = 'https://example.com/api/data?filter=status&sort=asc'

response = requests.get(url)

print(response.json())

In this example, we're manually building the URL with two URL parameters: filter=status and sort=asc. The response from the server is then printed as JSON.