Junior — Middle
Can you explain what a query string is, which is added to a URL when data is sent to a server?
sobes.tech AI
Answer from AI
A query string is the part of a URL that is added after the question mark ? and contains parameters sent to the server when data is submitted via a GET request.
It consists of key=value pairs separated by an ampersand &. For example:
https://example.com/search?query=python&sort=asc
Here, query=python and sort=asc are query string parameters.
The query string is used to transmit data that influences the request result, such as filters, search parameters, pagination, etc. In Python, it can be constructed using the urllib.parse module:
from urllib.parse import urlencode
params = {'query': 'python', 'sort': 'asc'}
query_string = urlencode(params)
url = f'https://example.com/search?{query_string}'
print(url)
# https://example.com/search?query=python&sort=asc
Thus, the query string is a convenient way to pass parameters to the server via URL.