curl Cheat Sheet for API Debugging: Commands and Fixes
Last updated: 15 November 2026
Last updated: 15 November 2026. See the update log at the end.
When an API call fails, the browser and your application are the worst places to debug it: too many layers, too little detail. curl removes the layers.
You see the exact request, the exact response, which step failed (DNS, TCP, TLS, auth, the server itself) and how long each one took.
This is a working cheat sheet, grouped by the question you are asking. Every command below was run against a small local test server I wrote for the purpose, with curl 8.5.0 on Ubuntu 24.04.
The server returns JSON, 401s, 429s, 500s, redirects, cookies, gzip and a self-signed HTTPS certificate, so the outputs you see are real, not invented. Where a flag needs a newer curl than that, or I could not test something, the article says so.
The six flags you will use every day
-sSilent: no progress meter-SWith-s, still show errors. Use-sStogether-iInclude response headers in the output-vVerbose: request and response headers, connection details-o fileWrite the body to a file (-o /dev/nullto discard it)-w '...'Print selected values after the transfer (status code, timings)
1. Make a request and see what came back
curl -s http://localhost:8081/api/users/1
{"id": 1, "name": "Ann", "email": "a**@example.com"}
Add -i to see the status line and headers with the body:
curl -si http://localhost:8081/api/users/1
HTTP/1.1 200 OK
Content-Type: application/json
X-Request-Id: req-123
Content-Length: 52
{"id": 1, "name": "Ann", "email": "a**@example.com"}
Headers matter more than people expect. Request IDs, rate-limit headers, Retry-After, WWW-Authenticate and cache headers all live there.
-I sends a HEAD request and prints only the headers, but note that it is a different request: a server can answer HEAD differently from GET.
To pretty-print a JSON body, pipe it into jq (curl -s URL | jq .) if you have it installed.
Get only the status code:
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8081/api/error
500
This is the basis of health checks and scripts. -o /dev/null discards the body and -w prints the code.
2. See the whole conversation: -v
curl -sv -o /dev/null http://localhost:8081/api/users/1 2>&1 | grep -E '^[<>*]'
* Host localhost:8081 was resolved.
* IPv6: ::1
* IPv4: 127.0.0.1
* Trying 127.0.0.1:8081...
* Connected to localhost (127.0.0.1) port 8081
> GET /api/users/1 HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/8.5.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< X-Request-Id: req-123
< Content-Length: 52
<
* Connection #0 to host localhost left intact
Lines starting with * are curl's own notes (DNS, connecting, TLS), > is what you sent and < is what came back. The verbose output goes to stderr, hence 2>&1 before filtering.
Security warning: -v and --trace print your Authorization header in clear text. I confirmed that with a bearer token. Redact tokens before pasting output into a ticket or chat.
For the raw bytes of both directions, --trace-ascii - prints a hex-offset dump, useful when you suspect a body is not what you think:
=> Send header, 139 bytes (0x8b)
0000: POST /api/users HTTP/1.1
0055: Content-Type: application/json
0075: Content-Length: 14
=> Send data, 14 bytes (0xe)
0000: {"name":"Bob"}
3. Send JSON correctly
curl -s -X POST http://localhost:8081/api/users \
-H 'Content-Type: application/json' \
-d '{"name":"Bob","email":"b**@example.com"}'
{"id": 2, "name": "Bob", "email": "b**@example.com"}
Since curl 7.82 there is a shortcut: --json sets the Content-Type and Accept headers to JSON and sends the data as a POST. It returned the same result in my test:
curl -s http://localhost:8081/api/users --json '{"name":"Bob","email":"b**@example.com"}'
You don't need -X POST when you use -d; curl switches to POST by itself.
The two classic mistakes:
Forgetting the content type. curl defaults to a form encoding, and many APIs reject it:
curl -s http://localhost:8081/api/users -d '{"name":"Bob"}'
{"error": "unsupported_media_type", "got": "application/x-www-form-urlencoded"}
And invalid JSON, usually from shell quoting or a trailing comma:
curl -s http://localhost:8081/api/users --json '{"name":"Bob",}'
{"error": "invalid_json", "detail": "Illegal trailing comma before end of object: line 1 column 14 (char 13)"}
Use single quotes around JSON in Bash so the shell leaves the double quotes alone. That advice is for Bash, zsh and similar; quoting rules on Windows cmd and PowerShell differ and I did not test them.
Sending a body from a file:
There is a subtle difference between -d @file and --data-binary @file. For a 20-byte file containing three lines of JSON:
- size_upload with
-d @file: 17 - size_upload with
--data-binary @: 20
-d @file strips the newlines; --data-binary sends the file exactly as it is. That is harmless for JSON, but for anything where bytes matter (a signed payload, a CSV, a multi-line text) use --data-binary.
4. Authentication
curl -si http://localhost:8081/api/secure
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api"
{"error": "invalid_token", "message": "Token missing or expired"}
The WWW-Authenticate header tells you the scheme the server expects. Then:
# Bearer token
curl -s -H "Authorization: Bearer $TOKEN" http://localhost:8081/api/secure
# same thing with the built-in option
curl -s --oauth2-bearer "$TOKEN" http://localhost:8081/api/secure
# HTTP Basic
curl -s -u ann:s3cret http://localhost:8081/api/headers
With -u, curl sent Authorization: Basic YW5uOnMzY3JldA==, which is just ann:s3cret in base64. Base64 is encoding, not encryption, so use Basic auth over HTTPS only.
Keep secrets out of your shell history and process list:
A token typed on the command line lands in your history and is visible to other users through ps while the command runs. Two alternatives I tested:
# header read from a file
printf 'Authorization: Bearer %s\n' "$TOKEN" > hdr.txt
curl -s -H @hdr.txt http://localhost:8081/api/secure
# options read from standard input
printf 'header = "Authorization: Bearer %s"\nurl = "http://localhost:8081/api/secure"\n' "$TOKEN" | curl -s -K -
Both returned {"ok": true}. Protect hdr.txt with proper file permissions and delete it when done.
5. Is it a curl failure or an HTTP failure?
This distinction saves hours. By default curl treats a 404 or 500 as a successful transfer and exits with 0. Your script then keeps going. Compare:
curl -s --fail http://localhost:8081/api/error ; echo "exit=$?"
curl -s --fail-with-body http://localhost:8081/api/error ; echo " exit=$?"
exit=22
{"error": "internal", "trace_id": "abc-999"} exit=22
--fail makes curl exit with 22 on HTTP errors (400 and above) but hides the error body, which is often where the useful message is. --fail-with-body (curl 7.76 and newer) keeps the body and still returns 22. In scripts, use that one and read the body.
With -sS, curl also prints a one-line reason: curl: (22) The requested URL returned error: 500.
Exit codes I hit while testing:
- 3
(URL with a literal space)Meaning: URL is malformed - 6
Could not resolve host: no-such-host.invalidMeaning: DNS lookup failed - 7
Failed to connect to localhost port 9 ... Couldn't connect to serverMeaning: Nothing is listening, or something blocks the connection - 22
The requested URL returned error: 500Meaning: HTTP error with--fail - 28
Operation timed out after 1001 milliseconds with 0 bytes receivedMeaning: Timeout - 60
SSL certificate problem: self-signed certificateMeaning: TLS verification failed
The full list is in the curl manual. You can also get the code and message inside the output of -w, with %{exitcode} and %{errormsg} (both since curl 7.75.0):
curl -s -o /dev/null --max-time 1 -w 'exit=%{exitcode} msg=%{errormsg}\n' http://localhost:8081/api/slow
exit=28 msg=Operation timed out after 1002 milliseconds with 0 bytes received
6. Where is the time going?
curl -s -o /dev/null --cacert cert.pem \
-w 'dns %{time_namelookup}connect %{time_connect}tls %{time_appconnect}pretransfer %{time_pretransfer}ttfb %{time_starttransfer}total %{time_total}\n' \
https://localhost:8443/api/users/1
dns 0.000019connect 0.000111tls 0.003647pretransfer 0.003678ttfb 0.047594total 0.047645
These timers are cumulative: each one is measured from the start of the request, not from the previous step. So here the connection took about 0.1 ms, the TLS handshake finished at 3.6 ms, and the first response byte arrived at 47.6 ms, meaning the server spent roughly 44 ms working. Read them like this:
- Large time_namelookup: a DNS problem.
- Large gap between time_namelookup and time_connect: network distance or a filtered port.
- Large gap between time_connect and time_appconnect: a slow TLS handshake.
- Large gap between time_pretransfer and time_starttransfer: the server is slow to respond (time to first byte).
- Large gap between time_starttransfer and time_total: a big or slow download.
My local numbers are tiny because there is no network between the client and server. On a real API you would see meaningful values in each field.
For the deliberately slow endpoint (3 seconds), the output was ttfb 3.001115 total 3.001198.
Set timeouts in scripts:
curl -sS --connect-timeout 5 --max-time 20 https://api.example.com/health
--connect-timeout limits the connection phase and --max-time limits the whole operation. Without them, a stuck request can hang a script indefinitely.
With --max-time 1 on the slow endpoint, curl exited with code 28 as shown above. I could not demonstrate --connect-timeout against an unreachable address, because my sandbox's network intercepts such connections, so that flag is documented but not shown in action here.
7. Retries and rate limits
I made an endpoint that returns 503 twice before succeeding:
curl -sS --fail --retry 3 --retry-delay 1 http://localhost:8081/api/flaky
curl: (22) The requested URL returned error: 503
curl: (22) The requested URL returned error: 503
{"ok": true, "attempt": 3}
curl retried twice and then succeeded, exit code 0. With --retry 1 against the same endpoint it gave up with exit 22. Two details:
Without --fail, the bodies of the failed attempts were printed too ({"error": "unavailable"}{"error": "unavailable"}{"ok": true...}), which would break any script parsing the output. Use --fail with retries, or write to a file with -o.
For a 429 with Retry-After: 1, curl waited between attempts: two failures took 2 seconds in total before the success. So it honored the header in my test. Without Retry-After, --retry-delay and curl's default back-off apply.
By default curl retries only on what it considers transient errors. To retry on any failure, including connection refused, add --retry-all-errors (7.71.0 and newer). Be careful with it on non-idempotent requests like POST, because it can create duplicates.
8. Redirects
curl -s -o /dev/null -w '%{http_code} -> %{redirect_url}\n' http://localhost:8081/old
curl -sL -o /dev/null -w '%{http_code} final=%{url_effective} redirects=%{num_redirects}\n' http://localhost:8081/old
302 -> http://localhost:8081/api/users/1
200 final=http://localhost:8081/api/users/1 redirects=1
curl does not follow redirects unless you pass -L. A common surprise is calling an API and getting an empty body: it was a 301 or 302 to another URL (often HTTP to HTTPS). Use -i or the first command above to see it.
%{url_effective} and %{num_redirects} tell you where you ended up.
9. Compression
curl -s -o /dev/null -w 'plain: %{size_download} bytes\n' http://localhost:8081/api/gzip
curl -s --compressed -o /dev/null -w '--compressed: %{size_download} bytes on the wire\n' http://localhost:8081/api/gzip
plain: 901 bytes
--compressed: 408 bytes on the wire
--compressed sends Accept-Encoding and decompresses the response for you. If you set the header yourself instead (-H 'Accept-Encoding: gzip'), curl does not decompress it, and you get binary garbage on your terminal.
The first bytes were 1f 8b 08 00, the gzip signature. If you see unreadable output from an API, that is the first thing to check.
10. Cookies and sessions
curl -s -c jar.txt http://localhost:8081/api/login
curl -s -b jar.txt http://localhost:8081/api/me
curl -s http://localhost:8081/api/me
{"ok": true}
{"user": "ann"}
{"error": "no_session"}
-c saves cookies to a file and -b sends them. The third call, with no cookie jar, got the 401-style error, proving the session cookie was what made the difference.
11. Query strings and encoding
curl -s -G http://localhost:8081/api/search --data-urlencode 'q=hello world&x=1' --data-urlencode 'tag=a/b'
curl -s http://localhost:8081/api/search --url-query 'q=hello world' --url-query 'page=2'
{"path": "/api/search?q=hello+world%26x%3d1&tag=a%2fb"}
{"path": "/api/search?q=hello+world&page=2"}
Two lessons. -G turns --data-urlencode values into a query string. And look at the first line: the & inside 'q=hello world&x=1' was encoded as part of the value (%26), so the server saw one parameter, not two. Pass each parameter as its own argument.
--url-query needs curl 7.87.0 or newer.
A raw space in a URL fails: curl "http://localhost:8081/api/search?q=a b" exited with code 3 (malformed URL) in my test. Quote the URL in the shell, and encode spaces yourself or use the options above.
12. TLS and certificate problems
curl -sS https://localhost:8443/api/users/1
curl: (60) SSL certificate problem: self-signed certificate
More details here: https://curl.se/docs/sslcerts.html
The server's certificate was not signed by an authority curl trusts. Correct fix: tell curl which certificate or CA to trust.
curl -sS --cacert cert.pem https://localhost:8443/api/users/1
That worked. The quick and dirty alternative, -k (--insecure), also worked but disables verification entirely, so a man-in-the-middle would go unnoticed. Use it only on a throwaway local test, never against a real API with credentials.
A second flavor is a name mismatch:
curl -sS --cacert cert.pem https://127.0.0.1:8443/api/users/1
curl: (60) SSL: no alternative certificate subject name matches target host name '127.0.0.1'
The cert
Comments
No comments yet. Start the discussion.