python requests variable in url

Python Requests Variable in URL

When working with web applications, it is often necessary to send data through the URL. One way to achieve this is by adding variables to the URL. Python's requests library provides an easy way to do this.

Method 1: Using Query Parameters

The most common way to pass variables in the URL is by using query parameters. These are added to the end of the URL after a ? character and separated by & characters.


import requests

payload = {'key1': 'value1', 'key2': 'value2'}
url = 'https://example.com/path/to/endpoint'

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

print(response.url)

In this example, we are adding two query parameters, key1 and key2, with their respective values, value1 and value2, to the URL. The resulting URL will be:

  • https://example.com/path/to/endpoint?key1=value1&key2=value2

Method 2: Using Path Variables

Another way to pass variables in the URL is by using path variables. These are added to the URL as placeholders for values that will be substituted later.


import requests

url = 'https://example.com/path/to/endpoint/{variable}'

response = requests.get(url.format(variable='value'))

print(response.url)

In this example, we are adding a path variable, {variable}, to the URL. We then use the format() method to substitute the value of the variable. The resulting URL will be:

  • https://example.com/path/to/endpoint/value

Method 3: Using a Combination of Query Parameters and Path Variables

It is also possible to use a combination of query parameters and path variables to pass variables in the URL.


import requests

payload = {'key1': 'value1', 'key2': 'value2'}
url = 'https://example.com/path/to/endpoint/{variable}'

response = requests.get(url.format(variable='value'), params=payload)

print(response.url)

In this example, we are using a path variable, {variable}, and adding two query parameters, key1 and key2, with their respective values, value1 and value2, to the URL. The resulting URL will be:

  • https://example.com/path/to/endpoint/value?key1=value1&key2=value2

By using the requests library, it is easy to pass variables in the URL using query parameters, path variables, or a combination of both.