Using curl to Understand Web Requests
Use curl to see headers, follow redirects, send data and time each stage of a web request.
Key takeaways
-
curl -vshows the connection, the TLS handshake, the request headers and the response headers. - curl doesn't follow redirects unless you add
-L, which makes redirect chains easy to inspect. - Use
-Hfor headers and-dor--jsonfor request bodies. - The
-woption prints timing for DNS, connection, TLS and the first byte. - In Windows PowerShell 5.1, type
curl.exe, becausecurlis an alias for a different command.
curl is a command-line program that sends a request to a server and shows you what comes back. Because it does only what you ask, with no cache, extensions or page rendering in the way, it's one of the clearest ways to see how a web request really works.
You can inspect headers, follow redirects one at a time, send data to an API, and measure where the time goes. All examples here use example.com; swap in addresses you're allowed to test.
Getting it
curl comes with macOS, most Linux distributions and current versions of Windows. Check yours with:
curl --version The output lists the version and supported protocols and features, such as HTTP/2. Builds differ, so an option available on one machine may be missing on another.
In older Windows PowerShell, curl maps to Invoke-WebRequest, which takes different options. Calling curl.exe avoids the surprise. Quoting also differs between Command Prompt, PowerShell and Unix-like shells, so JSON in a command may need to be escaped differently or read from a file.
Your first requests
With no options, curl fetches a URL with a GET request and prints the body:
curl https://example.com/ To see response headers along with the body, add -i. To ask for headers only, use -I, which sends a HEAD request. Some servers handle HEAD differently from GET, so if results look odd, request the page normally and discard the body:
curl -I https://example.com/
curl -s -D - -o /dev/null https://example.com/ Here -s silences the progress display, -D - writes headers to the screen and -o /dev/null throws the body away. On Windows, use NUL instead of /dev/null.
Seeing the whole conversation
The verbose option, -v, is where curl teaches the most.
curl -v https://example.com/ Lines starting with * are curl's notes about what it is doing, such as the address it connected to and certificate details. Lines starting with > are what you sent. Lines starting with < are what the server sent back.
If you're new to the request and response format, HTTP explained covers each part. For the encryption step, see the TLS handshake.
Following redirects
By default curl reports a redirect and stops. The Location header tells you where it points. Add -L to follow, and combine it with header output to see every step:
curl -sIL http://example.com/old-page This is a quick way to find chains that bounce from HTTP to HTTPS to a different hostname to a new path, or loops that never end. The status code matters too; the redirect codes behave differently, especially for non-GET requests.
Sending headers and data
Add or override headers with -H:
curl -H "Accept: application/json" \
-H "Authorization: Bearer $API_TOKEN" \
https://api.example.com/items Keep secrets out of the command text where you can. Commands are saved in shell history, may be visible to other users in the process list, and get pasted into tickets. Environment variables help with history; a protected config file is another option. Environment variables and secrets covers the trade-offs.
To send form data, use -d, which switches the method to POST and sets a form content type:
curl -d "name=Ada" -d "color=blue" https://api.example.com/form For JSON, set the content type yourself, or use --json in newer curl versions, which sets the headers for you:
curl -H "Content-Type: application/json" \
-d '{"name":"Ada"}' \
https://api.example.com/items Put @ before a file name to read the body from a file: -d @payload.json. Note that -d strips line breaks from a file; --data-binary @file sends it exactly.
Other methods use -X, as in -X PUT or -X DELETE. Don't add -X POST alongside -d; it's unnecessary and can cause odd behavior across redirects. HTTP methods explains what each one is meant to do.
Saving files
Use -o name to choose a file name, or -O to reuse the name from the URL. Add -f so curl treats HTTP error statuses as failures, which stops you saving an error page as if it were your download:
curl -fSL -o report.pdf https://example.com/report.pdf -S makes errors visible even when you've silenced progress. -C - resumes a partial download if the server supports range requests. After downloading software, compare it with a published hash as described in checksums and file verification.
Timing a request
The -w option prints values after the transfer finishes.
curl -s -o /dev/null -w "dns %{time_namelookup}\nconnect %{time_connect}\ntls %{time_appconnect}\nfirst byte %{time_starttransfer}\ntotal %{time_total}\ncode %{http_code}\n" https://example.com/ Each time is measured in seconds from the start, so subtract neighbors to get the length of a stage.
Run several times and look at the pattern. One sample can be skewed by a cold cache or a momentary hiccup.
Testing a specific server
Before moving a site, you can ask the new server for your hostname without changing DNS:
curl -v --resolve example.com:443:203.0.113.25 https://example.com/ The request keeps the right hostname for TLS and the Host header but connects to the address you gave. This is better than putting the IP address in the URL, which would cause a certificate mismatch.
Force an IP version with -4 or -6. Limit waiting with --connect-timeout 5 and --max-time 30, which matter in scripts that must not hang.
Cookies, caching and compression
curl keeps no state between runs unless you ask. To watch a sign-in or session flow on a system you're testing, save cookies to a file with -c jar.txt and send them back with -b jar.txt. The file holds live session values, so delete it when you're done. How cookies work explains the attributes you'll see in Set-Cookie headers.
Caching headers are easy to inspect too. Request a resource, note its ETag or Last-Modified value, then send it back as a condition:
curl -s -D - -o /dev/null -H 'If-None-Match: "abc123"' https://example.com/style.css A 304 Not Modified status means the server agrees your copy is current. ETags and conditional requests covers the logic.
To check compression, add --compressed, which asks for compressed content and decodes it for you. Look for a Content-Encoding response header. To request a particular protocol, builds that support it accept --http1.1 or --http2, and verbose output shows which one was negotiated.
Using curl in scripts
For automation, a few options make behavior predictable. Combine -f, -s and -S so that the script stays quiet when things work, reports errors when they don't, and returns a failing exit code for HTTP error statuses. Add time limits. The --retry option repeats transient failures, but think twice before retrying requests that create or charge for something.
A minimal health check that prints only the status code looks like this:
curl -s -o /dev/null -w "%{http_code}\n" --max-time 10 https://example.com/health Interpreting failures
curl exits with a number that describes what went wrong. Zero means the transfer completed, even if the server answered 404, unless you used -f. Common messages include:
- Could not resolve host: DNS failed.
- Connection refused: the host answered that nothing is accepting connections there.
- Operation timed out: packets are being dropped or something is very slow.
- Certificate problem: the chain, name or dates didn't check out, or your computer lacks the issuing root.
The -k option skips certificate verification. It can help confirm that the certificate is the problem on a test system you control, but it removes protection against impersonation, so never leave it in scripts. Fix the certificate or supply the correct authority with --cacert.
Copying requests from a browser
Browser developer tools usually offer "Copy as cURL" for any request in the network panel. It reproduces the headers and body, which is a fast way to isolate a bug. The copied command often includes your session cookies, so remove them before sharing it with anyone.
For a quick look at what headers a browser sends, the request header echo is handy, and the HTTP status reference decodes unfamiliar codes.
A habit worth building
When a web problem is unclear, run one verbose request and read it from top to bottom before changing anything. Check the address curl connected to, the certificate name, the status code, the Location header if there is one, and any caching or server headers. Then change a single thing, such as the IP version, a header or the target server, and compare the two outputs side by side. The difference between them usually points to the cause.