Skip to content

curl Cheat Sheet for API Debugging: Commands and Fixes

Dasun Kalupahana 11 min read 8
On this page
  1. The six flags you will use every day
  2. 1. Make a request and see what came back
  3. Get only the status code
  4. 2. See the whole conversation: -v
  5. 3. Send JSON correctly
  6. The two classic mistakes
  7. Sending a body from a file
  8. 4. Authentication
  9. Keep secrets out of your shell history and process list
  10. 5. Is it a curl failure or an HTTP failure?
  11. Exit codes I hit while testing
  12. 6. Where is the time going?
  13. Set timeouts in scripts
  14. 7. Retries and rate limits
  15. 8. Redirects
  16. 9. Compression
  17. 10. Cookies and sessions
  18. 11. Query strings and encoding
  19. 12. TLS and certificate problems
  20. 13. Test a host before DNS exists: --resolve and Host
  21. 14. Proxy variables can bite
  22. 15. Machine-readable results with -w
  23. Troubleshooting by symptom
  24. A quirk: -X HEAD
  25. A reusable debugging one-liner
  26. Common mistakes
  27. Alternatives
  28. Related Dev Talk articles
  29. Frequently asked questions
  30. How do I see response headers with curl?
  31. How do I send a JSON POST with curl?
  32. Why does curl return exit code 0 on a 500 error?
  33. What does curl error 60 mean?
  34. How do I measure API response time with curl?
  35. Which curl version do I need?
  36. update log
  37. Sources

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

FlagWhat it does
-sSilent: no progress meter
-SWith -s, still show errors. Use -sS together
-iInclude response headers in the output
-vVerbose: request and response headers, connection details
-o fileWrite the body to a file (-o /dev/null to 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": "ann@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": "ann@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":"bob@example.com"}'
{"id": 2, "name": "Bob", "email": "bob@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":"bob@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

ExitMessage (as printed)Meaning
3(URL with a literal space)URL is malformed
6Could not resolve host: no-such-host.invalidDNS lookup failed
7Failed to connect to localhost port 9 ... Couldn't connect to serverNothing is listening, or something blocks the connection
22The requested URL returned error: 500HTTP error with --fail
28Operation timed out after 1001 milliseconds with 0 bytes receivedTimeout
60SSL certificate problem: self-signed certificateTLS 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.000019  connect 0.000111  tls 0.003647  pretransfer 0.003678  ttfb 0.047594  total 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 certificate was trusted, but it was issued for localhost, not the IP address. Connect using a name that is in the certificate (next section). Neither of these will be fixed by retrying.

13. Test a host before DNS exists: --resolve and Host

curl -sS --resolve api.test.local:8443:127.0.0.1 --cacert cert.pem https://api.test.local:8443/api/host
{"host": "api.test.local:8443"}

--resolve HOST:PORT:IP makes curl use that IP for the name, while still sending the right Host header and TLS server name. It is how you test a new server, a staging copy or one node behind a load balancer without touching DNS or /etc/hosts. For plain HTTP, -H 'Host: api.test.local' does a similar job; I tested that too, but it does not set the TLS server name, so use --resolve for HTTPS.

14. Proxy variables can bite

curl honors proxy environment variables such as https_proxy. If one is set in your shell, requests go through it, which can surprise you with a connection error or a certificate you did not expect. I reproduced this by setting https_proxy=http://127.0.0.1:9 for one command:

curl: (7) Failed to connect to 127.0.0.1 port 9 after 0 ms: Couldn't connect to server

The error names the proxy's address, not the API's, which is the clue. curl -v also prints a line about the proxy variables it picked up. Bypass them with --noproxy '*', which made the --resolve request in the previous section work in my environment.

15. Machine-readable results with -w

curl -s -o /dev/null -w '%{json}' http://localhost:8081/api/users/1 | jq '{http_code, http_version, remote_ip, url_effective, exitcode}'

%{json} (7.72.0 and newer) prints all write-out variables as one JSON object; %{header_json} (7.83.0 and newer) prints the response headers as JSON with each value in an array. I parsed both successfully: the status was 200, the HTTP version 1.1, the remote IP 127.0.0.1, and x-request-id was ["req-123"]. That is handy for logging and for tests that need to assert on headers.

Troubleshooting by symptom

SymptomFirst commandLikely cause
Nothing printedcurl -i URLA redirect (3xx), 204 No Content, or -s hiding an error: use -sS
Exit 6curl -v URLDNS: typo, missing record, resolver problem
Exit 7curl -v URLWrong port, service down, firewall, proxy variable
Exit 28-w with time_*Find which phase is slow
Exit 60curl -v URLSelf-signed or untrusted CA, or hostname not in certificate
401curl -i URLMissing or expired token: read WWW-Authenticate and the body
415 or 400 on POSTcurl -v or --trace-ascii -Wrong Content-Type or invalid JSON
429curl -i URLRate limit: read Retry-After and rate-limit headers
5xx--fail-with-bodyServer problem: capture the body and request ID, check server logs
Binary garbagecurl --compressed URLCompressed body shown without decompression
-X HEAD hangsUse -ISee below

A quirk: -X HEAD

Using -X HEAD instead of -I hangs. curl sent a HEAD request but still waited for the 52-byte body the headers promised. With -m 2 it ended with curl: (28) Operation timed out after 2001 milliseconds with 0 out of 52 bytes received. Use -I for HEAD. As a general rule, avoid -X unless you need a method curl cannot infer, like PUT, PATCH or DELETE.

A reusable debugging one-liner

curl -sS -D - -o response.json --max-time 20 \
  -w '\nstatus=%{http_code} ip=%{remote_ip} ttfb=%{time_starttransfer}s total=%{time_total}s\n' \
  -H "Authorization: Bearer $TOKEN" \
  https://api.example.com/v1/things

-D - prints the response headers to the terminal while -o saves the body to a file, so you get headers, status, timing and an untouched body in one run. I tested -D - with -o against the local server and it printed the status line and headers while the body went to the file.

Common mistakes

  • Using -s alone and wondering why failures are invisible. Use -sS.
  • Trusting exit code 0 as success on HTTP errors. Use --fail-with-body or check the status code.
  • Forgetting -H 'Content-Type: application/json' (or --json) on POST.
  • Pasting verbose output with a live token into a public issue.
  • Using -k as a permanent fix.
  • Putting tokens directly on the command line on shared machines.
  • Retrying non-idempotent POSTs with --retry-all-errors.
  • Splitting a query value on & without encoding it, and quoting the URL incorrectly.

Alternatives

  • HTTPie and similar tools have friendlier syntax and colored output. I did not test them here.
  • Postman or your IDE's HTTP client are better for exploring and saving collections; curl is better for scripts, servers with no GUI, and reproducible bug reports. Most tools can export a request as a curl command.
  • Browser developer tools let you copy a request as curl. Remember that the copied command contains your cookies and tokens.

Frequently asked questions

How do I see response headers with curl?

Use -i to include them with the body, -I for a HEAD request that shows only headers, or -D - to dump headers while saving the body elsewhere.

How do I send a JSON POST with curl?

Use -H 'Content-Type: application/json' -d '{...}', or --json '{...}' on curl 7.82 or newer.

Why does curl return exit code 0 on a 500 error?

Because the transfer itself succeeded. Add --fail-with-body (7.76 or newer) to get a non-zero exit code and keep the error body.

What does curl error 60 mean?

TLS certificate verification failed: an untrusted or self-signed certificate, or a hostname that is not in the certificate. Fix it with --cacert or by connecting using the right name, not by using -k in production.

How do I measure API response time with curl?

Use -w with %{time_total}, or with the cumulative time_namelookup, time_connect, time_appconnect, time_starttransfer variables to see which phase is slow.

Which curl version do I need?

I tested on 8.5.0. Features and the version that added them: --fail-with-body 7.76.0, --json 7.82.0, --retry-all-errors 7.71.0, --url-query 7.87.0, %{json} 7.72.0, %{header_json} 7.83.0, %{exitcode} and %{errormsg} 7.75.0. Check yours with curl --version.

update log

  • 15 November 2026: first version.
  • To recheck on each update: the current curl release notes for new or changed flags, and the version table above.

Sources

Keep reading

All Linux articles
  1. Same topic Linux High CPU or Load Average: Troubleshooting Checklist 9 min read
  2. Same topic Best Linux Commands for Developers and Sysadmins 3 min read
  3. Same topic No Space Left on Device, df Shows Space? 3 min read
  4. Popular this week Claude Code vs Cursor vs Copilot: Which Is Best in 2026? 8 min read

Free resources for this topic

Code snippets and fixes for this topic

Get one practical tip every week

New tutorials, fixes and free cheat sheets from DEV Talk, straight to your inbox. No spam, unsubscribe in one click.

Free download: Docker cheat sheet (PDF)

Have a question about this post?

Ask the community: other developers and the author can answer.

Ask the community

Get notified about new articles

One click, no email needed. Turn it off anytime with the bell at the top.

Get new articles on your iPhone

Add DEV Talk to your Home Screen, open it, then tap the bell.

Rate this post
0.0
Share

Enjoying the content?

If this article helped you, you can support the author with a coffee. It keeps new posts coming.

Buy me a coffee (opens in a new tab)

Comments 0

Be kind. Comments with links are reviewed before they appear.

No comments yet

Be the first to share your thoughts.

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.