Sobes.tech
Junior — Middle

How can data parameters be included in a URL request using the GET method?

sobes.tech AI

Answer from AI

To include data parameters in a URL request using the GET method in Python, you typically construct a query string by adding parameters to the URL after the ? symbol in the format key=value, separating pairs with &.

Here's an example using the standard urllib.parse module for proper encoding of parameters:

from urllib.parse import urlencode

params = {'search': 'python', 'page': 2, 'sort': 'asc'}
base_url = 'https://example.com/api'

query_string = urlencode(params)
full_url = f'{base_url}?{query_string}'

print(full_url)
# Output: https://example.com/api?search=python&page=2&sort=asc

If you're using the requests library, it automatically constructs the URL with parameters when you pass a dictionary to the params argument:

import requests

params = {'search': 'python', 'page': 2}
response = requests.get('https://example.com/api', params=params)
print(response.url)
# Output: https://example.com/api?search=python&page=2

Thus, parameters are passed in the URL after ? as key-value pairs, properly encoded.