curl (1/3)
curl sends a request to a URL and shows or saves the response; it is the standard tool for API testing and HTTP debugging. Part 1 covers help and config, URL globbing, output control, verbose tracing, methods/headers/redirects, HTTP versions, ranges, sending data and authentication.
163.1 Why is it used?
- Test an API from the terminal: any method, header, body, auth or HTTP version.
- See the exact request and response (-v, --trace-ascii) when a browser or app hides details.
- Download files, resume broken downloads, fetch many URLs with globbing.
- Script health checks using exit codes and -w '%{http_code}'.
- Windows 10/11 ship curl.exe (in PowerShell 5.1 curl is an alias, so type curl.exe); Linux: apt/dnf install curl; macOS: /usr/bin/curl built in.
163.2 How it works
- curl builds a request line (method + path), headers (Host, User-Agent, Accept) and an optional body.
- The server returns a status code, headers and a body; curl prints the body to stdout by default.
- Lab: client 192.168.183.20 (curl 8.7.1, HTTP2, no HTTP3) and an echo server api.lab = 192.168.183.10:80 that prints exactly what it received.
- curl's exit code is about the transfer, not the HTTP status: a 404 still exits 0 unless you use --fail.
- Step 1
1.client (curl) 192.168.183.20 builds GET /echo HTTP/1.1
- Step 2
2.Headers: Host: api.lab, User-Agent: curl/8.7.1, Accept: */*
- Step 3
3.Request travels to api.lab 192.168.183.10:80
- Step 4
4.Server replies HTTP/1.1 200 OK + headers + body
- Step 5
5.curl prints the body (or saves it with -o / -O)
- Step 6
6.Exit code 0 = transfer OK (check the status separately)
163.3 Help, version and config files
- curl -V: version, protocols and features (this build: HTTP2 yes, HTTP3 no).
- --help shows important options, --help category lists categories, --help http one category, --help all = 259 lines.
- -K file reads options (url, user-agent, header) from a config file; -q skips .curlrc.
- --next (-:) starts a second operation with fresh options in the same run.
- --libcurl c.c writes C code for the same request; --variable / --expand-url expand {{n}} variables.
curl -Vcurl --help all | wc -lcat opts.txtcurl -K opts.txtcurl http://api.lab/echo/one --next -d order=7 http://api.lab/echo/two$ curl -Vcurl 8.7.1 (x86_64-alpine-linux-musl) libcurl/8.7.1 OpenSSL/3.3.0 zlib/1.3.1 brotli/1.1.0 ... nghttp2/1.61.0Release-Date: 2024-03-27Protocols: dict file ftp ftps ... http https ... ws wssFeatures: alt-svc AsynchDNS brotli HSTS HTTP2 HTTPS-proxy IDN IPv6 Largefile libz NTLM PSL SSL ... zstd$ curl --help all | wc -l259$ cat opts.txturl = "http://api.lab/echo"user-agent = "lab-agent/1.0"header = "X-Course: networking"$ curl -K opts.txtGET /echo HTTP/1.1Host: api.labUser-Agent: lab-agent/1.0Accept: */*X-Course: networking-- body 0 bytes --$ curl http://api.lab/echo/one --next -d order=7 http://api.lab/echo/twoGET /echo/one HTTP/1.1POST /echo/two HTTP/1.1Content-Type: application/x-www-form-urlencoded-- body 7 bytes --order=7163.4 URL globbing
- [1-3] numeric range, [01-03] with leading zeros, [a-z] letters, [1-100:10] every 10th, {jan,feb} alternatives.
- In -o, #1 is replaced by the current value of the first glob.
- Literal brackets give "bad range" (exit 3); -g / --globoff turns globbing off.
- Always quote globbing URLs so the shell does not expand them.
curl -s 'http://api.lab/files/report-[1-3].txt'curl -s 'http://api.lab/files/{jan,feb}.csv' -o 'file_#1'curl -sS 'http://api.lab/echo/[x]'curl -s -g 'http://api.lab/echo/[x]'$ curl -s 'http://api.lab/files/report-[1-3].txt'this is report-1.txtthis is report-2.txtthis is report-3.txt$ curl -s 'http://api.lab/files/{jan,feb}.csv' -o 'file_#1'$ ls file_*file_febfile_jan$ curl -sS 'http://api.lab/echo/[x]'curl: (3) bad range in URL position 22:http://api.lab/echo/[x] ^(exit 3)$ curl -s -g 'http://api.lab/echo/[x]'GET /echo/[x] HTTP/1.1Host: api.lab163.5 Output control
- -o file names the output, -O uses the name from the URL, --output-dir + --create-dirs pick/create a folder.
- -s hides the progress meter and errors; -sS hides the meter but shows errors (best in scripts).
- -w '%{http_code} %{time_total}\n' prints status and time; -o /dev/null discards the body.
- -D file dumps headers, -i prints headers with the body.
- --fail turns HTTP errors into exit 22; --fail-with-body also shows the error body.
- A broken transfer exits 18 and leaves a partial file; --remove-on-error deletes it. --no-clobber never overwrites (adds .1).
curl http://api.lab:81/curl -s -o /dev/null -w '%{http_code} %{time_total}\n' http://api.lab/files/a.txtcurl -s http://api.lab/files/missingcurl -sS --fail http://api.lab/files/missingcurl -sS --fail-with-body http://api.lab/failcurl -sS -o b1.bin http://api.lab/broken$ curl http://api.lab:81/ % Total % Received % Xferd Average Speed Time 0 0 0 0 0 0 0 0 --:--:--curl: (7) Failed to connect to api.lab port 81 after 1 ms: Couldn't connect to server(exit 7)$ curl -s -o /dev/null -w '%{http_code} %{time_total}\n' http://api.lab/files/a.txt200 0.049541$ curl -s http://api.lab/files/missingNot found(exit 0)$ curl -sS --fail http://api.lab/files/missingcurl: (22) The requested URL returned error: 404(exit 22)$ curl -sS --fail-with-body http://api.lab/fail{"error":"database down"}curl: (22) The requested URL returned error: 500$ curl -sS -o b1.bin http://api.lab/brokencurl: (18) transfer closed with 900 bytes remaining to read163.6 Verbose and tracing
- -v: lines with * are curl info, > are request headers sent, < are response headers received.
- --trace-ascii file saves the whole conversation with byte offsets; --trace adds a hex dump.
- --trace-time adds a microsecond timestamp to every line; --trace-ids adds connection/transfer ids.
curl -v http://api.lab/files/a.txtcurl -s --trace-time -v -o /dev/null http://api.lab/files/a.txt$ curl -v http://api.lab/files/a.txt* IPv4: 192.168.183.10* Connected to api.lab (192.168.183.10) port 80> GET /files/a.txt HTTP/1.1> Host: api.lab> User-Agent: curl/8.7.1< HTTP/1.1 200 OK< Content-Length: 14this is a.txt$ curl -s --trace-time -v -o /dev/null http://api.lab/files/a.txt08:09:19.909527 * Trying 192.168.183.10:80...08:09:19.913460 * Connected to api.lab (192.168.183.10) port 8008:09:19.913625 > GET /files/a.txt HTTP/1.108:09:19.919416 < HTTP/1.1 200 OK08:09:19.919670 * Connection #0 to host api.lab left intact163.7 Method, headers, cookies and redirects
- -X changes the method; -H 'N: v' adds a header, -H 'Accept:' removes a default one; -A User-Agent, -e Referer.
- -c jar.txt saves Set-Cookie, -b jar.txt sends it back; -G moves -d data into the URL query; --compressed asks for gzip/br/zstd.
- -I fetches only headers; -L follows Location; --max-redirs N limits hops (default 50), exceeding gives exit 47.
- On 301/302 curl -L turns POST into GET; --post301 / --post302 keep POST.
- --location-trusted also sends the password to the redirect host: use carefully.
- Step 1
1.client sends GET /hop/3
- Step 2
2.api.lab replies 302 Found, Location: /hop/2
- Step 3
3.without -L curl stops here and prints the 302 body
- Step 4
4.with -L curl itself sends GET /hop/2, then the next hop
- Step 5
5.the chain ends at /echo with 200 OK
- Step 6
6.--max-redirs 1 stops early with exit 47
curl -s -X DELETE http://api.lab/echo/item/7curl -s -I http://api.lab/hop/3curl -sS -L --max-redirs 1 http://api.lab/hop/3curl -s -L -d x=1 http://api.lab/oldcurl -s -L --post301 -d x=1 http://api.lab/oldcurl -s -c jar.txt http://api.lab/logincurl -s -b jar.txt http://api.lab/mecurl -s -G -d q=curl -d page=2 http://api.lab/echo$ curl -s -X DELETE http://api.lab/echo/item/7DELETE /echo/item/7 HTTP/1.1Host: api.labUser-Agent: curl/8.7.1Accept: */*-- body 0 bytes --$ curl -s -I http://api.lab/hop/3HTTP/1.1 302 FoundServer: n163-apiContent-Length: 6Location: /hop/2$ curl -sS -L --max-redirs 1 http://api.lab/hop/3curl: (47) Maximum (1) redirects followed(exit 47)$ curl -s -L -d x=1 http://api.lab/old-- body 0 bytes --$ curl -s -L --post301 -d x=1 http://api.lab/oldPOST /echo HTTP/1.1Content-Type: application/x-www-form-urlencoded-- body 3 bytes --x=1$ curl -s -c jar.txt http://api.lab/loginlogged in$ curl -s -b jar.txt http://api.lab/mehello asha, session ok$ curl -s -G -d q=curl -d page=2 http://api.lab/echoGET /echo?q=curl&page=2 HTTP/1.1Host: api.lab-- body 0 bytes --163.8 HTTP version selection
- --http1.0 / --http1.1 set the request line version.
- --http2 on plain http sends Upgrade: h2c; this server did not upgrade, so the reply stayed HTTP/1.1. Over HTTPS --http2 uses TLS ALPN.
- --http2-prior-knowledge speaks HTTP/2 (h2c) directly: %{http_version} printed 2.
- --http3 fails on this build (exit 2): the libcurl has no HTTP/3.
curl -sv --http2 http://api.lab/echocurl -sv --http2-prior-knowledge http://api.lab/echocurl --http3 http://api.lab/echo$ curl -sv --http2 http://api.lab/echo> GET /echo HTTP/1.1> Connection: Upgrade, HTTP2-Settings> Upgrade: h2c> HTTP2-Settings: AAMAAABkAAQAoAAAAAIAAAAA< HTTP/1.1 200 OK< Server: n163-api$ curl -sv --http2-prior-knowledge http://api.lab/echo* [HTTP/2] [1] OPENED stream for http://api.lab/echo> GET /echo HTTP/2< HTTP/2 200hello from api.lab over HTTP/2 (h2c)$ curl --http3 http://api.lab/echocurl: option --http3: the installed libcurl version doesn't support this(exit 2)163.9 Ranges and resume
- -r 0-99 asks for bytes 0-99; the server answers 206 Partial Content with Content-Range: bytes 0-99/1000.
- -r -10 = last 10 bytes, -r 9500- = from offset to end, -r 0-0,-1 = first + last byte.
- -C - checks the local file size and asks only for the rest (400 bytes on disk -> downloaded 600).
curl -s -i -r 0-99 http://api.lab/big.bincurl -s -r 0-399 -o big.bin http://api.lab/big.bincurl -s -C - -o big.bin -w '%{http_code} %{size_download}\n' http://api.lab/big.bin$ curl -s -i -r 0-99 http://api.lab/big.binHTTP/1.1 206 Partial ContentContent-Length: 100Accept-Ranges: bytesContent-Range: bytes 0-99/1000$ curl -s -C - -o big.bin -w '%{http_code} %{size_download}\n' \ http://api.lab/big.bin206 600-rw-r--r-- 1 root root 1000 Nov 9 08:10 big.bin163.10 Sending data: -d, --json, -F, -T
- -d sends a form POST (application/x-www-form-urlencoded); several -d are joined with &.
- -d @file strips newlines; --data-binary @file sends bytes as-is; --data-urlencode encodes spaces and &.
- --json sets Content-Type and Accept to application/json.
- -F builds multipart/form-data (file=@report.txt sends the file with its filename).
- -T file uploads with PUT; a URL ending in / gets the file name appended (201 Created).
curl -s -d @notes.txt http://api.lab/echocurl -s --data-binary @notes.txt http://api.lab/echocurl -s --data-urlencode 'name=Asha Rao' --data-urlencode 'note=a&b' http://api.lab/echocurl -s --json @order.json http://api.lab/echocurl -s -T notes.txt http://api.lab/upload/$ curl -s -d @notes.txt http://api.lab/echo-- body 16 bytes --line oneline two$ curl -s --data-binary @notes.txt http://api.lab/echo-- body 18 bytes --line oneline two$ curl -s --data-urlencode 'name=Asha Rao' \ --data-urlencode 'note=a&b' http://api.lab/echo-- body 24 bytes --name=Asha+Rao¬e=a%26b$ curl -s --json @order.json http://api.lab/echoPOST /echo HTTP/1.1Content-Type: application/jsonAccept: application/json-- body 25 bytes --$ curl -s -T notes.txt http://api.lab/upload/stored notes.txt (18 bytes)| Option | Content-Type | Body |
|---|---|---|
| -d a=1 -d b=2 | application/x-www-form-urlencoded | a=1&b=2 (newlines stripped from @file) |
| --data-binary @f | application/x-www-form-urlencoded | File bytes exactly |
| --data-urlencode | application/x-www-form-urlencoded | URL-encoded values |
| --json @f | application/json (+ Accept) | JSON as given |
| -F n=v -F f=@file | multipart/form-data | Parts with filename and type |
| -T file | (PUT upload) | File, name added if URL ends with / |
163.11 Authentication
- No credentials: 401 Unauthorized with a WWW-Authenticate header.
- -u user:pw sends Basic (Base64, not encrypted): use only over HTTPS.
- --digest: first a 401 with a nonce, then curl sends a hash of the password.
- --anyauth lets curl pick the most secure offered method (it picked Digest).
- -n reads credentials from ~/.netrc (keeps them out of shell history); --oauth2-bearer TOKEN sends a Bearer token.
- --disallow-username-in-url refuses credentials in the URL (exit 67). Others: --ntlm, --negotiate -u : (Kerberos), --aws-sigv4.
curl -s -v -u asha:LabPass163 http://api.lab/basiccurl -s -v --anyauth -u asha:LabPass163 http://api.lab/securecurl -s --oauth2-bearer lab-token-163 http://api.lab/bearercurl -sS --disallow-username-in-url http://asha:LabPass163@api.lab/basic$ curl -s -v -u asha:LabPass163 http://api.lab/basic* Server auth using Basic with user 'asha'> Authorization: Basic YXNoYTpMYWJQYXNzMTYz$ curl -s -v --anyauth -u asha:LabPass163 http://api.lab/secure< WWW-Authenticate: Basic realm="api.lab"< WWW-Authenticate: Digest realm="api.lab", qop="auth", ...* Server auth using Digest with user 'asha'> Authorization: Digest username="asha", realm="api.lab", ...hello asha (Digest, picked by curl)$ curl -s --oauth2-bearer lab-token-163 http://api.lab/bearer{"user":"asha","scope":"read"}$ curl -sS --disallow-username-in-url \ http://asha:LabPass163@api.lab/basiccurl: (67) URL rejected: Credentials was passed in the URL when prohibited(exit 67)| Exit code | Meaning (seen in the lab) |
|---|---|
| 0 | Transfer OK (even for a 404 without --fail) |
| 2 | Option not supported by this build (--http3) |
| 3 | Bad URL (unquoted/literal brackets) |
| 7 | Failed to connect (closed port 81) |
| 18 | Transfer closed early (partial file) |
| 22 | HTTP error with --fail |
| 47 | Too many redirects (--max-redirs) |
| 67 | Credentials in URL rejected |
163.12 Common mistakes
- Treating exit 0 as success: a 404 still exits 0; use --fail or check -w '%{http_code}'.
- Expecting POST to survive a 301/302 with -L: it becomes GET unless --post301/--post302.
- Using -d @file for exact bytes: it strips newlines; use --data-binary.
- Typing curl in Windows PowerShell 5.1 (alias of Invoke-WebRequest): type curl.exe.
- Sending Basic auth over plain HTTP or passwords on the command line (history); use HTTPS and .netrc.
163.13 Interview tips
- Debugging an API: -v for request/response headers, -w '%{http_code} %{time_total}' for status and time.
- Then -L for redirects, -u / --oauth2-bearer for auth, --trace-ascii file for a full conversation dump.
- POST + 301 + -L = GET (curl follows browser behaviour); --post301 keeps POST.
- -d vs --data-binary vs --json vs -F: know which Content-Type each sends.