cURL by Example: Query Parameters
Send data in the URL. This example shows GET with params.
Code
# Passing parameters directly in the URL
# Note: Quotes are important to prevent shell from interpreting &
curl "https://api.example.com/search?q=laptop&sort=price_asc"
# Using -G and -d to let curl encode parameters
curl -G https://api.example.com/search \
-d "q=laptop" \
-d "sort=price_asc" \
-d "page=1"
# URL encoding specific characters
curl -G https://api.example.com/search \
--data-urlencode "q=hello world"Explanation
Query parameters are key-value pairs appended to the URL after a question mark (?), with multiple parameters separated by ampersands (&). When running cURL from a shell, it's critical to quote the URL if it contains special characters like &, as the shell interprets ampersands as background job indicators, which could cause the command to execute incorrectly or be sent to the background.
The -G flag (or --get) instructs cURL to perform a GET request. More importantly, when used in conjunction with data-related options like -d, --data-raw, or --data-urlencode, the -G flag causes cURL to append the provided data to the URL as query parameters instead of sending it in the request body. By default, using -d without -G would trigger a POST request. The -G flag transforms this behavior, making GET requests with complex query parameters much cleaner and more maintainable in scripts.
URL encoding (also known as percent-encoding) is a mechanism to convert reserved and unsafe characters in a URL into a format transmittable over the internet. Special characters like spaces, ampersands (&), question marks (?), and others have specific meanings in URLs and must be encoded to prevent misinterpretation by servers. The --data-urlencode option automatically URL-encodes the data you provide. For example, spaces are encoded as %20 and ampersands as %26. This option supports several syntaxes: content (encodes content directly), =content (encodes with leading = not included), name=content (encodes only the content portion), @filename (loads and encodes data from a file), and name@filename (loads from file and sends as name=urlencoded-file-content). This ensures query parameters containing special characters are correctly understood by the server.
Code Breakdown
"..." quotes are essential when the URL contains &.-G forces a GET request, appending -d data to the URL.
