Dev Utilities·6 min read·By the developer of StackUtils

cURL Command Guide: The Developer's Swiss Army Knife

cURL is installed on virtually every developer machine, yet most only use it for basic GET requests. This guide covers authentication, custom headers, POST bodies, file uploads, cookies, and how to convert cURL commands to code.

How curl Decides the Method and Body

Most curl confusion comes from flags that change more than their name suggests. The rules: without a body curl sends GET; -d switches to POST and adds Content-Type: application/x-www-form-urlencoded; -I sends HEAD, not a GET that prints headers. Sending a form to httpbin.org shows exactly what goes out:

$ curl -s https://httpbin.org/anything -d 'a=1&b=2'
{
  "headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    ...
  },
  "method": "POST",
  "form": { "a": "1", "b": "2" }
}

So curl -X POST -d '...' is redundant, and curl -d '{"name":"Alice"}' without a Content-Type header sends JSON labelled as a form — many frameworks then see an empty body. Since curl 7.82, --json fixes both at once:

# Old way
curl https://api.example.com/users \
  -H 'Content-Type: application/json' -H 'Accept: application/json' \
  -d '{"name":"Alice"}'

# curl 7.82+
curl https://api.example.com/users --json '{"name":"Alice"}'
curl https://api.example.com/users --json @user.json

# PUT / PATCH / DELETE still need -X
curl -X PATCH https://api.example.com/users/42 --json '{"name":"Alice Smith"}'
curl -X DELETE https://api.example.com/users/42

Check your version with curl --version; older distributions and Windows builds may predate --json.

Query Strings Without Hand-Encoding

Typing ?q=a b&c into a URL breaks: the space is invalid and the ampersand starts a new parameter. Let curl encode it with -G and --data-urlencode:

$ curl -G https://httpbin.org/get --data-urlencode 'q=a b&c'
# request URL sent: https://httpbin.org/get?q=a+b%26c
# server sees:      "q": "a b&c"

Always quote URLs containing & or ?: unquoted, the shell treats & as “run in background”. Percent-encoding rules are explained in the URL encoding guide.

Authentication

# Basic auth: curl builds the header for you
curl -u alice:s3cr3t https://api.example.com/admin
# → Authorization: Basic YWxpY2U6czNjcjN0   (Base64 of "alice:s3cr3t")
curl -u alice https://api.example.com/admin   # prompts for the password

# Bearer token (JWT or OAuth access token)
curl https://api.example.com/me -H "Authorization: Bearer $TOKEN"

# API key header
curl https://api.example.com/data -H "X-API-Key: $API_KEY"

The Basic header is only Base64 — decode YWxpY2U6czNjcjN0 in the Base64 tool and you get the password back — so only send it over HTTPS. When a bearer token is rejected, paste it into the JWT decoder and check exp and aud before blaming the server.

Secrets typed on the command line end up in shell history and are visible to other users through the process list. Use environment variables as above, read headers from a file with -H @headers.txt, or keep credentials in a ~/.netrc file and pass --netrc.

Debugging a Request

# Response headers and body
curl -i https://api.example.com/users/42

# Everything: DNS, TLS handshake, request headers (>), response headers (<)
curl -v https://api.example.com/users/42

# Status code and timing only
curl -s -o /dev/null -w '%{http_code} %{time_total}s\n' https://httpbin.org/status/404
# → 404 0.361646s

# Follow redirects and show each hop
curl -sIL http://example.com

# Test a new server before switching DNS
curl --resolve example.com:443:203.0.113.10 https://example.com/

Inspecting headers this way pairs well with the HTTP headers guide. Typical surprises:

  • Empty output, exit code 0. The server answered a 3xx redirect. Add -L.
  • Method changes after a redirect. On 301, 302 and 303, curl (like browsers) turns a POST into a GET. Combining -X POST with -L forces POST on every hop, which is usually wrong; use --post301 / --post302 if you need the body resent.
  • File body arrives on one line. -d @file strips CR and LF characters. Use --data-binary @file for anything where line breaks matter.
  • TLS errors. -k disables certificate checks; use it only to diagnose, never in scripts. Fix the chain or pass --cacert.

curl in Scripts and CI

By default curl exits with 0 even when the server returns 500, so a deploy script will happily continue. Make HTTP errors fail the script and set time limits:

curl --fail-with-body -sS \
  --connect-timeout 5 --max-time 30 \
  --retry 3 --retry-delay 2 \
  https://api.example.com/health
# On HTTP 500: prints the error body, exits with code 22

--fail-with-body (curl 7.76+) keeps the error message, which -f discards. -sS hides the progress bar but still prints errors. --retry retries timeouts and 408, 429, 500, 502, 503 and 504 responses only.

Uploads, Downloads and Cookies

# multipart/form-data upload (what an HTML file input sends)
curl https://api.example.com/upload -F 'file=@report.pdf' -F 'title=Q3 report'
curl https://api.example.com/images -F 'image=@photo.jpg;type=image/jpeg'

# Raw binary body
curl -X PUT https://api.example.com/files/123 \
  -H 'Content-Type: application/octet-stream' --data-binary @file.bin

# Download, keep the remote file name, follow redirects
curl -OL https://example.com/archive.tar.gz

# Log in, store the session cookie, reuse it
curl -c cookies.txt -d 'user=alice&pass=secret' https://example.com/login
curl -b cookies.txt https://example.com/dashboard

Do not set the multipart Content-Type header yourself with -F: curl generates the boundary string and must put it in the header.

Quoting on Windows

Most examples online, including the ones above, use single quotes for a POSIX shell (bash, zsh, Git Bash, WSL). On Windows they fail in different ways:

  • cmd.exe does not understand single quotes. Use double quotes and escape inner ones: -d "{\"name\":\"Alice\"}". The caret ^ continues a line instead of the backslash.
  • Windows PowerShell 5.1 aliases curl to Invoke-WebRequest. Type curl.exe to run the real curl, which ships with Windows 10 and 11. Version 5.1 also mangles embedded double quotes when calling native programs; PowerShell 7.3+ passes them correctly. Backtick ` continues a line.

The quoting problem disappears if the body lives in a file: curl.exe --json @body.json URL works the same in every shell. Browser DevTools offer both “Copy as cURL (bash)” and “Copy as cURL (cmd)” for this reason.

From curl to Application Code

A common workflow is to reproduce a request with curl until it works, then port it. Each flag has a direct equivalent; this command and the fetch call send the same request:

curl https://api.example.com/users \
  -H 'Authorization: Bearer token123' \
  --json '{"name":"Alice"}'

const res = await fetch('https://api.example.com/users', {
  method: 'POST',                        // implied by the body in curl
  headers: {
    'Authorization': 'Bearer token123',
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  body: JSON.stringify({ name: 'Alice' }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`); // fetch, like curl, does not throw on 4xx/5xx

Differences to keep in mind: fetch follows redirects by default (curl does not), and in a browser it is subject to CORS, so a request that works in curl can still be blocked in the page. The cURL to code converter translates the method, headers and -d body into fetch, axios, Python requests, Go or PHP.

Flag Reference

FlagPurpose
-X METHODOverride the method string. Rarely needed: -d already implies POST, -I implies HEAD.
-H 'Name: value'Add a header. -H 'Name:' removes a default header; -H @file reads headers from a file.
-d / --dataSend a body as POST, form-encoded. @file reads a file but strips newlines.
--data-binary @fileSend a file byte for byte.
--data-urlencodePercent-encode the value before sending it.
--jsonBody + Content-Type and Accept set to application/json (curl 7.82+).
-GMove the -d / --data-urlencode data into the query string and send GET.
-F name=valuemultipart/form-data; name=@file uploads a file.
-u user:passHTTP Basic authentication.
-i / -I / -vShow response headers + body / HEAD request / full request and response trace.
-LFollow redirects (off by default).
-s -SSilent, but still print errors.
-f / --fail-with-bodyExit with code 22 on HTTP status ≥ 400 (the second keeps the body; 7.76+).
-o file / -OWrite the body to a file / to a file named after the URL.
-w '%{http_code}'Print variables after the transfer: status, timings, sizes.
-m SECS / --connect-timeoutTotal time limit / connection time limit.
-c / -bWrite cookies to a jar / send cookies from a jar or string.
--resolve host:443:IPSend a request for a hostname to a specific IP without editing /etc/hosts.

Turn a curl command into code

Paste a curl command — for example one copied from DevTools — and get the equivalent fetch, axios, Python, Go or PHP code.

Open cURL to Code →