Skip to lesson

curl recipes for daily use

You are on a server over SSH, or inside a build script, with no Postman. You still need to log in, send JSON and see only the status, in a command short enough to paste into a chat.

JSON writes: --json, -d @body.json, and headers

--json is the curl option that sends a JSON body. It sets the method to POST and adds the headers Content-Type: application/json and Accept: application/json.

Send JSON from a file with --json @product.json. The examples show three ways to send the same body.

Example 1 · Three ways to send the same JSON

Terminal
cat product.jsoncurl -i --json @product.json -u admin@shoplite.test:admin123 http://localhost:8080/api/v1/productscurl -d @product.json -H "Content-Type: application/json" -u admin@shoplite.test:admin123 http://localhost:8080/api/v1/productscurl -d @product.json -u admin@shoplite.test:admin123 http://localhost:8080/api/v1/products
Sample output (your Date differs)
$ cat product.json
{
  "sku": "BK-WINGS",
  "name": "Wings of Fire",
  "categoryId": 5,
  "price": 349.00,
  "stock": 40
}
$ curl -i --json @product.json -u admin@shoplite.test:admin123 http://localhost:8080/api/v1/products
HTTP/1.1 201 Created
Location: http://localhost:8080/api/v1/products/16
Content-Type: application/json
Content-Length: 104
Date: Fri, 16 Oct 2026 04:56:15 GMT
Connection: keep-alive
Keep-Alive: timeout=5

{"id":16,"sku":"BK-WINGS","name":"Wings of Fire","categoryId":5,"categoryName":"Books","price":349.00,"stock":40,"isActive":true}
$ curl -d @product.json -H "Content-Type: application/json" -u admin@shoplite.test:admin123 http://localhost:8080/api/v1/products
{"type":"https://shoplite.example/problems/already-exists","title":"Resource already exists","status":409,"detail":"A product with SKU BK-WINGS already exists.","instance":"/api/v1/products"}
$ curl -d @product.json -u admin@shoplite.test:admin123 http://localhost:8080/api/v1/products
{"type":"https://shoplite.example/problems/unsupported-media-type","title":"Unsupported media type","status":415,"detail":"Content-Type application/x-www-form-urlencoded is not supported. Send application/json.","instance":"/api/v1/products"}

What this code does

  • --json @product.json created product 16: 201 Created with a Location header. -u is the Basic login from the next section.
  • The second command sent the same file with -d and an explicit Content-Type; it reached the API, which answered 409 because BK-WINGS now exists. The third forgot the header, so curl sent the form type and got 415.

--json @product.json reads the body from a file (the @ means "from this file"). It needs curl 7.82 or newer; check with curl --version. The older way is -d @product.json -H "Content-Type: application/json": -d alone sends application/x-www-form-urlencoded, so a JSON API answers 415, the same trap as Postman's form-data. Add -X PATCH or -X PUT to change the method, and -H "Name: value" to add any header.

Keep request bodies in files: long JSON on one command line is hard to read, and quotes inside it break differently in every shell. In Windows PowerShell 5.1 type curl.exe, because curl is an alias for a different command, and pass the body as a file (--json "@product.json"), since that shell strips the double quotes inside inline JSON. In macOS Terminal (zsh), inline JSON works inside single quotes: --json '{"stock": 25}'.

Fix the error

Fix the 415

Read the error, then pick the line that fixes it.

The JSON body reaches the server as a form.

curl -s http://localhost:8080/api/v1/products \
-d @product.json

Error

HTTP/1.1 415 Unsupported Media Type

Auth: -u for Basic, -H for Bearer, tokens from environment variables

An environment variable is a named value kept by your terminal session, such as TOKEN, that commands read as $TOKEN. Secrets live there instead of inside commands or scripts.

Send Basic auth with -u, a Bearer token with -H, and read the secret from a variable. The example logs in and reuses the token.

Example 2 · A token from the login, kept in a variable

Terminal
export SHOPLITE_PASSWORD=admin123curl -s -u "admin@shoplite.test:$SHOPLITE_PASSWORD" http://localhost:8080/api/v1/auth/meTOKEN=$(curl -s --json "{\"email\":\"admin@shoplite.test\",\"password\":\"$SHOPLITE_PASSWORD\"}" http://localhost:8080/api/v1/auth/login | jq -r .accessToken)echo "${TOKEN:0:6}..."curl -s -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/v1/auth/mecurl -s -H "Authorization: Bearer $TOKEN" -X DELETE http://localhost:8080/api/v1/products/14 -w "%{http_code}\n"curl -s -H "Authorization: Bearer" http://localhost:8080/api/v1/auth/me
Output
$ export SHOPLITE_PASSWORD=admin123
$ curl -s -u "admin@shoplite.test:$SHOPLITE_PASSWORD" http://localhost:8080/api/v1/auth/me
{"email":"admin@shoplite.test","name":"Store Admin","role":"ADMIN"}
$ TOKEN=$(curl -s --json "{\"email\":\"admin@shoplite.test\",\"password\":\"$SHOPLITE_PASSWORD\"}" http://localhost:8080/api/v1/auth/login | jq -r .accessToken)
$ echo "${TOKEN:0:6}..."
sl_at_...
$ curl -s -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/v1/auth/me
{"email":"admin@shoplite.test","name":"Store Admin","role":"ADMIN"}
$ curl -s -H "Authorization: Bearer $TOKEN" -X DELETE http://localhost:8080/api/v1/products/14 -w "%{http_code}\n"
204
$ curl -s -H "Authorization: Bearer" http://localhost:8080/api/v1/auth/me
{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"Sign in to use this endpoint.","instance":"/api/v1/auth/me"}

What this code does

  • -u "admin@shoplite.test:$SHOPLITE_PASSWORD" reads the password from the environment, so the command itself holds no secret.
  • $(...) captures the login output and jq -r .accessToken keeps only the token. Every later call sends Bearer $TOKEN; the last command shows the 401 an empty token gives.

-u user:password sends Basic auth; curl builds the Base64 header for you. With -u user alone, curl asks for the password, so it never appears in your shell history. For tokens, add the header yourself: -H "Authorization: Bearer $TOKEN". A token pasted into a command lands in your shell history, in screenshots and, inside a script, in Git; capture a fresh one from the login response with jq -r .accessToken (jq is in the last section).

Set a variable for the current window with export NAME=value in macOS Terminal and Git Bash, $env:NAME = "value" in PowerShell, or set NAME=value in Command Prompt, and read it as $NAME, $env:NAME or %NAME%. Watch for an empty variable: a typo such as $TOKN, or a failed login, sends Authorization: Bearer with no token and the API answers 401. Print the first few characters (echo "${TOKEN:0:6}...") to check it is set without showing the whole secret.

Printing only the status code and timing with -w, failing on errors with --fail

An exit code is the number a command returns when it ends: 0 means success and any other number means failure. Scripts and CI servers read it to decide what to do next.

-w prints chosen details after the response, and --fail turns HTTP errors into a failing exit code. The example prints the status, the time and the exit code.

Example 3 · Status codes, timing and --fail

Terminal
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/products/6curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/products/99curl -s -o /dev/null -w "%{http_code} in %{time_total}s, %{size_download} bytes\n" http://localhost:8080/api/v1/productscurl -s -o product-99.json http://localhost:8080/api/v1/products/99; echo "exit code $?"curl -sS --fail -o product-99.json http://localhost:8080/api/v1/products/99; echo "exit code $?"curl -sS --fail-with-body http://localhost:8080/api/v1/products/99; echo " (exit code $?)"
Sample output (your time and size differ)
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/products/6
200
$ curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/api/v1/products/99
404
$ curl -s -o /dev/null -w "%{http_code} in %{time_total}s, %{size_download} bytes\n" http://localhost:8080/api/v1/products
200 in 0.011255s, 1615 bytes
$ curl -s -o product-99.json http://localhost:8080/api/v1/products/99; echo "exit code $?"
exit code 0
$ curl -sS --fail -o product-99.json http://localhost:8080/api/v1/products/99; echo "exit code $?"
curl: (22) The requested URL returned error: 404
exit code 22
$ curl -sS --fail-with-body http://localhost:8080/api/v1/products/99; echo " (exit code $?)"
{"type":"https://shoplite.example/problems/not-found","title":"Resource not found","status":404,"detail":"Product 99 was not found.","instance":"/api/v1/products/99"}curl: (22) The requested URL returned error: 404
 (exit code 22)

What this code does

  • -s -o /dev/null -w "%{http_code}\n" prints only the status. The third command adds the total time and the body size.
  • Without --fail, a 404 still exits with code 0 and its error body is saved as if it were a product. --fail exits with 22 and saves nothing; --fail-with-body exits with 22 and shows the error body.

%{http_code} is the status, %{time_total} the total time in seconds and %{size_download} the body size. With -s (silent: no progress meter) and -o /dev/null (throw the body away; -o NUL on Windows), curl -s -o /dev/null -w "%{http_code}\n" URL prints just 200: the quickest health check there is.

By default curl treats any HTTP answer, even 404 or 500, as success: exit code 0, so a script carries on with an error body saved as data. --fail (-f) exits with code 22 on a status of 400 or more and does not save the body; --fail-with-body also exits with 22 but still prints the error body, which is usually what you want to read. Add -S (--show-error) to -s, so silent mode still prints real errors; -sS is the usual pair in scripts.

Predict the output

What does curl print?

Read each command and pick what you see.

Round 1 of 2

curl -s -o /dev/null -w "%{http_code}\n" \
http://localhost:8080/api/v1/products/99

Downloading files, following redirects, cookies and retries

A redirect is an answer such as 301 that tells the client to ask a different URL. curl stops at it unless you add -L, which follows redirects.

-o saves a file, -L follows redirects, -c and -b keep cookies, and --retry tries again. The examples show each one.

Example 4 · A download, and a redirect with and without -L

Terminal
curl -sS -O -J http://localhost:8080/api/v1/reports/stock.csvls *.csvhead -4 stock-report.csvcurl -sS -o report.csv http://localhost:8080/api/v1/reports/stock.csvwc -l report.csvcurl -i http://localhost:8080/api/products/6curl -sS -L http://localhost:8080/api/products/6
Sample output (your Date differs)
$ curl -sS -O -J http://localhost:8080/api/v1/reports/stock.csv
$ ls *.csv
stock-report.csv
$ head -4 stock-report.csv
sku,name,stock
MOB-RN13,Redmi Note 13 5G,40
MOB-GM35,Samsung Galaxy M35,25
MOB-IP15,iPhone 15 128GB,8
$ curl -sS -o report.csv http://localhost:8080/api/v1/reports/stock.csv
$ wc -l report.csv
15 report.csv
$ curl -i http://localhost:8080/api/products/6
HTTP/1.1 301 Moved Permanently
Location: /api/v1/products/6
Content-Length: 0
Date: Fri, 16 Oct 2026 04:58:35 GMT
Connection: keep-alive
Keep-Alive: timeout=5


$ curl -sS -L http://localhost:8080/api/products/6
{"id":6,"sku":"ACC-AD141","name":"boAt Airdopes 141","categoryId":4,"categoryName":"Accessories","price":1299.00,"stock":120,"isActive":true}

What this code does

  • -O -J saved the file as stock-report.csv, the name from the Content-Disposition header; -o report.csv chose the name yourself. The file has a header line plus 14 products.
  • The old URL /api/products/6 answers 301 with a Location and an empty body. -L follows it to /api/v1/products/6 and prints the product.

Example 5 · A cookie session, and retries on 503

Terminal
curl -sS -c cookies.txt --json "{\"email\":\"admin@shoplite.test\",\"password\":\"$SHOPLITE_PASSWORD\"}" http://localhost:8080/api/v1/auth/session -w "%{http_code}\n"grep SESSION cookies.txtcurl -sS -b cookies.txt http://localhost:8080/api/v1/auth/mecurl --fail --retry 3 -o status.json http://localhost:8080/actuator/healthcat status.json
Sample output (the progress meter is left out)
$ curl -sS -c cookies.txt --json "{\"email\":\"admin@shoplite.test\",\"password\":\"$SHOPLITE_PASSWORD\"}" http://localhost:8080/api/v1/auth/session -w "%{http_code}\n"
204
$ grep SESSION cookies.txt
#HttpOnly_localhost	FALSE	/api	FALSE	0	SESSION	s_admin_91fd4c
$ curl -sS -b cookies.txt http://localhost:8080/api/v1/auth/me
{"email":"admin@shoplite.test","name":"Store Admin","role":"ADMIN"}
$ curl --fail --retry 3 -o status.json http://localhost:8080/actuator/health
curl: (22) The requested URL returned error: 503
Warning: Problem : HTTP error. Will retry in 1 seconds. 3 retries left.
curl: (22) The requested URL returned error: 503
Warning: Problem : HTTP error. Will retry in 2 seconds. 2 retries left.
$ cat status.json
{"status":"UP"}

What this code does

  • The session login returns 204 and a SESSION cookie, which -c wrote to cookies.txt (the #HttpOnly_ prefix marks an HttpOnly cookie). -b cookies.txt sends it back, so /auth/me knows who you are.
  • The practice API's /status answers 503 twice, as a server that is still starting would. --retry 3 waited 1 second, then 2, and the third try got {"status":"UP"}.

-o name saves the body to a file you name; -O uses the last part of the URL, and -O -J uses the name the server suggests in its Content-Disposition header. Without -L, curl prints the 301 and stops; Postman follows redirects by default, so a request can work in Postman and "fail" in curl. -c cookies.txt saves cookies the server sets and -b cookies.txt sends them back, so a session login works across commands.

--retry 3 tries again up to three times on errors that may pass, such as 503 Service Unavailable or a timeout, waiting longer each time (1 second, then 2, then 4). Retry only requests that are safe to repeat: a GET can be retried freely, but a POST that timed out may have created the order already, and retrying it creates a second one.

Pretty-printing JSON output and saving reusable curl scripts per OS

A smoke test is a short script that hits an API's main endpoints and prints PASS or FAIL, so you can re-check everything in seconds after each change.

Pipe curl into jq to read JSON, then save your usual checks as a script. The example is a full smoke-test script.

Example 6 · jq, and a smoke-test script (smoke-test.sh)

Terminal
#!/usr/bin/env bash# Quick checks for the ShopLite API.  Usage: ./smoke-test.sh [base-url]BASE_URL="${1:-http://localhost:8080/api/v1}": "${SHOPLITE_PASSWORD:?Set SHOPLITE_PASSWORD first}"FAILED=0check() {  # check NAME EXPECTED-STATUS CURL-ARGUMENTS...  local name="$1" expected="$2"  shift 2  local status  status=$(curl -s -o /dev/null -w "%{http_code}" "$@")  if [ "$status" = "$expected" ]; then    echo "PASS  $name ($status)"  else    echo "FAIL  $name (expected $expected, got $status)"    FAILED=1  fi}TOKEN=$(curl -s --json "{\"email\":\"admin@shoplite.test\",\"password\":\"$SHOPLITE_PASSWORD\"}" \  "$BASE_URL/auth/login" | jq -r .accessToken)check "list products"       200 "$BASE_URL/products"check "missing product"     404 "$BASE_URL/products/99"check "who am I"            200 -H "Authorization: Bearer $TOKEN" "$BASE_URL/auth/me"check "write without login" 401 --json @product.json "$BASE_URL/products"echo "Accessories, cheapest first:"curl -s "$BASE_URL/products?categoryId=4&sort=price,asc" | jq -r '.content[] | "  \(.price)  \(.name)"'exit $FAILED
Output (macOS Terminal; Git Bash on Windows prints the same)
$ curl -s http://localhost:8080/api/v1/products/6 | jq .
{
  "id": 6,
  "sku": "ACC-AD141",
  "name": "boAt Airdopes 141",
  "categoryId": 4,
  "categoryName": "Accessories",
  "price": 1299.00,
  "stock": 120,
  "isActive": true
}
$ chmod +x smoke-test.sh
$ ./smoke-test.sh
PASS  list products (200)
PASS  missing product (404)
PASS  who am I (200)
PASS  write without login (401)
Accessories, cheapest first:
  849.00  Logitech M331 Silent Mouse
  1299.00  boAt Airdopes 141
  2199.00  Mi Power Bank 20000mAh
$ echo $?
0
$ unset SHOPLITE_PASSWORD
$ ./smoke-test.sh
./smoke-test.sh: line 4: SHOPLITE_PASSWORD: Set SHOPLITE_PASSWORD first

What this code does

  • jq . indents the product and keeps 1299.00 as sent. The script then checks four endpoints, prints the accessories with a jq filter and ends with exit code 0.
  • ${SHOPLITE_PASSWORD:?...} stops the script with a clear message when the variable is not set, instead of sending an empty password. The Windows version of this script is a practice task below.

curl -s URL | jq . prints the body indented, and jq -r '.content[].name' picks out fields as plain text (-r drops the quotes). Install jq with brew install jq on macOS or winget install jqlang.jq on Windows; jq 1.7 and newer keep numbers as sent, so 1299.00 stays 1299.00. Without jq, python -m json.tool also pretty-prints.

Use a Bash script (.sh) on macOS, Linux and Git Bash: run chmod +x smoke-test.sh once, then ./smoke-test.sh; its first line #!/usr/bin/env bash runs it with Bash even in zsh. On Windows use a PowerShell script (.ps1) run as .\smoke-test.ps1; if scripts are blocked, allow your own once with Set-ExecutionPolicy -Scope CurrentUser RemoteSigned. Read the base URL from an argument and secrets from environment variables, and end with exit code 0 or 1 so CI can use it too.

Next step

Check your understanding

12 quick questions