brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: curl --variable and --expand-data fill a request from variables

Curl
~/tips/tip-curl-variable-expand-data

curl --variable [email protected] \

Lets curl hold variables and insert them, correctly escaped, into the URL or request body.

Building a JSON body for curl in the shell always ends in a pile of quotes. Since curl 8.3.0 it can keep variables itself and escape them correctly.

You set a variable with --variable name=text, or --variable name@file to read it from a file. You use it in a later option by prefixing that option with --expand- and writing {{name}}. So --expand-data is --data with variables, and --expand-url does the same for the URL. The manual also lists functions you can add after a colon: trim, json, url, b64 and 64dec.

Here I send a note from a text file as a properly quoted JSON string:

curl --variable [email protected] \
  --expand-data '{"text": {{note:trim:json}}}' \
  -H 'Content-Type: application/json' \
  https://example.com/api/notes

trim removes whitespace at both ends and json turns the content into a JSON quoted string, quotes and escapes included. That is the part that is painful to quote by hand in the shell.

Environment variables are also supported. --variable %TOKEN imports the variable TOKEN and makes curl exit with an error if it is not set. Give it a default with --variable %TOKEN=fallback if you want it to continue:

curl --variable %HOST --expand-url 'https://{{HOST}}/api/status' -sS

The caveat is easy to trip over: according to the manual, a name that does not exist as a variable expands to a blank, without an error. A typo in {{note}} therefore sends an empty value. The %name form for environment variables is the one that fails loudly, so I prefer it for anything that must be set. Variables only exist in curl 8.3.0 and newer, so check curl --version on the machine that will run the script.

Further reading: curl man page: –variable and –expand-

More Curl tips curl --trace-ascii – https://example.com/ Retry-After: 120 curl -fsS --fail-early \ url = "https://example.com/data/latest.json" curl -4 -s -o /dev/null -w '%{remote_ip} %{http_code}\n' https://example.com/ All Curl tips (71) All topics

Link