Send request data

Build a query string safely

Encode query values with curl instead of manually replacing spaces and reserved characters.

10 minute lesson

~~~

Query values can contain spaces, ampersands, Unicode, and other characters with URL meaning. A URL cannot carry those characters raw. A space must become %20, an & inside a value must become %26, and so on. Doing that by hand is tedious and easy to get wrong. One missed character and the server parses your query differently than you intended.

Let curl encode each value from its original form instead.

Ask curl to create the query string

curl --get --data-urlencode 'q=network tools' https://httpbin.org/get

--data-urlencode takes a name=value pair and percent-encodes the value. --get moves the encoded data to the query string instead of sending a request body. Without --get, the data options would turn this into a POST.

Inspect the returned URL and arguments. httpbin echoes what it received:

{
  "args": {
    "q": "network tools"
  },
  "url": "https://httpbin.org/get?q=network+tools"
}

The value arrived intact. curl turned the space into a safe form on the wire, and the server decoded it back to network tools. You wrote the value once, in its natural form.

Multiple parameters

Repeat the option for each pair:

curl --get \
  --data-urlencode 'q=curl & friends' \
  --data-urlencode 'page=2' \
  https://httpbin.org/get

curl joins the pairs with & in the final URL. The & inside the first value gets encoded as %26, so it stays part of the value instead of splitting the query.

The mistake to avoid

Quote each value so the shell cannot split it or interpret & as a background operator. This command looks close but breaks twice:

curl --get --data-urlencode q=network tools https://httpbin.org/get

The shell splits on the space, so tools becomes a separate argument that curl tries to use as a URL. You’ll see an error like Could not resolve host: tools. That message is your signal: the shell carved up your command before curl ever saw it. Put the whole name=value pair in single quotes and the problem disappears.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →