Sending requests with curl
curl writes HTTPThe Hypertext Transfer Protocol, the rules browsers, apps, and servers use to send requests and responses on the web. requests for you and shows what comes back, while still letting you choose every part: the method, the headers, the body and the credentials. Read with care, its output answers most questions about what a server did with a request.
The shape of a curl command
Typing HTTP by hand shows you exactly what travels over a connection,
but it gets tiring quickly. You have to remember every header, count
line endings and handle the encryptionTransforming data so that only someone holding the right key can read it. It protects confidentiality and, unlike hashing, is designed to be reversed by the key holder. yourself. curl
writes the request for you, sends it, and shows you what comes back.
A curl command is the word curl, some options, and a URLA web address, such as https://photos.example/api/albums/42?limit=10. It names how to connect (https), the domain, the path to a particular page or resource, and any extra parameters after the question mark.:
curl https://api.example.com/notes
With no options, curl sends a GET request and prints the
response body to standard output, so you can read it, save it with
> or pipe it into another command. The URL tells curl
everything it needs to connect: the scheme (https, so
TLSTransport Layer Security, the protection behind HTTPS. It encrypts traffic between two connected systems, detects changes on the way, and uses certificates so the client can confirm which server it reached. on port 443), the host (api.example.com) and the path
(/notes). A URL can also end with a query after a
?, such as ?done=false&limit=10.
Put single quotes around a URL that has a query. The shell treats
? as a pattern for matching file names, and
& as an instruction to run a command in the
background, so an unquoted query can turn into something quite
different from what you typed:
curl 'https://api.example.com/notes?done=false&limit=10'A few options appear in almost every command in this course:
| Option | What it does |
|---|---|
-o FILE | Saves the body to a file instead of printing it |
-s | Silent: hides the progress meter curl shows while saving or piping, and also hides error messages |
-S | Shows error messages even with -s. Together, -sS means "quiet unless something goes wrong" |
-L | Follows redirects to wherever the server points next |
Short options can be combined, as in -sS, and options can
go before or after the URL.
The parts of a URL
Clients, servers, and addresses took a URL apart into its scheme, host, port, path, query and fragment. A URL can carry one more part, and curl shows you what happens to each:
https://ava:[email protected]:8443/notes/7?tag=work&tag=urgent&q=oat%20milk#comments| Part | Here | What it does |
|---|---|---|
| Scheme | https | How to talk to the server |
| Userinfo | ava:example-password | A username and password before an @. curl sends them as Basic credentials |
| Host | api.example.com | Which server, by name |
| Port | 8443 | Which port, after a colon. Without one, https means 443 and http means 80 |
| Path | /notes/7 | Which thing on the server |
| Query | tag=work&tag=urgent&q=oat%20milk | Parameters after the ?, as name=value pairs joined with & |
| Fragment | comments | A place inside the page, after the #. It is never sent to the server |
The userinfoAn OpenID Provider endpoint that returns claims about the signed-in person to a client presenting an access token. Its sub must match the ID token's before the client uses anything it returns. part is an old way of putting credentials into an
address, and it is best avoided: a URL ends up in logs and history,
and browsers either ignore the part or warn about it. It also makes
addresses easy to misread. In
https://[email protected]/, the host is
login.example, and photos.example is only a
username.
A port written out explicitly is part of the address, so
https://api.example.com:443/ names the same place as
https://api.example.com/, while
https://api.example.com:8443/ reaches whatever program
listens on port 8443, which may be a different service altogether.
The query is text that the server splits into parameters. Its values
are percent-encoded, so %20 is a space. A name can appear
more than once, as tag does here, and servers do not
agree on what a repeated name means: one keeps the first value,
another the last, a third keeps both. That is why many identity
protocols refuse a request that repeats one of their parameters.
The fragment never leaves the browser, which uses it to scroll to a
heading or hand a value to the page's scripts. curl leaves it out
too, so a request for
https://api.example.com/notes/7#comments sends only
GET /notes/7.
Seeing the whole exchange
The body is only part of a response. The status line and headers often tell you more, especially when something goes wrong. Three options let you see them.
-i includes the status line and response headers before
the body. -I sends a HEAD request instead,
which asks the server for the status line and headers without the
body. That is a quick way to check whether a page exists or how big a
download is, although a few servers answer HEAD
differently from GET.
-v, for verbose, shows both sides of the conversation.
Example output, shortened:
$ curl -v https://api.example.com/notes
* Connected to api.example.com (203.0.113.10) port 443
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
...
> GET /notes HTTP/2
> Host: api.example.com
> User-Agent: curl/8.5.0
> Accept: */*
>
< HTTP/2 200
< content-type: application/json
< content-length: 14
<
{"notes": []}
Each line starts with a marker. * lines are curl's own
notes about the connection, such as the address it reached and the TLS
version. > lines are what curl sent, and
< lines are what it received, so the arrow points the
way the data travelled. The request and response have the same shape
you typed by hand in
Connections, ports and speaking HTTP by hand,
although this exchange used HTTP/2, which writes header names in
lowercase. They mean the same thing.
The verbose lines go to standard error and the body to standard
output, so curl -v URL > body.txt saves the body while
the conversation stays on screen. When you read verbose output, the
> lines answer a question that comes up often: did curl
actually send the header I meant to send?
Methods, headers and bodies
How applications communicate showed how a REST-style APIAn application programming interface: a defined way for software to interact with a service. A web API offers endpoints where other programs send HTTP requests. pairs an address with a method. For a
collection of notes, that means GET to read the list or
one note, POST to the list to create a note,
PUT to a note's own address to replace it, and
DELETE to remove it. curl can send each of them.
-H adds a header to the request. You write it exactly as
it appears on the wire, a name, a colon and a value, in quotes so the
shell keeps it as one argument:
curl -H 'Accept: application/json' https://api.example.com/notes
To send a body, use -d, the short form of
--data. It switches the method to POST and
labels the body with Content-Type:
application/x-www-form-urlencoded, the format of an HTML form:
name=value pairs joined with &. Many APIs
expect JSONA text format for structured information, written as named values inside curly braces. APIs, tokens, and discovery documents all use it. instead, and --json handles that in one
option. It sends the body as POST, sets
Content-Type: application/json so the server knows what it
is reading, and sets Accept: application/json to ask for
JSON back:
curl -sS -i --json '{"title": "Buy milk"}' https://api.example.com/notes
The single quotes keep the shell away from the double quotes that JSON
needs. A typical answer to this request is 201 Created with
a Location header such as Location: /notes/42.
The server chose the new note's identifier and tells you where the note
now lives. To send a body that is already in a file, write
@ and the file name: --json @note.json.
For other methods, -X sets the method name. It changes
only the word in the request line, so you still add the body yourself:
curl -sS -i -X PUT --json '{"title": "Buy oat milk", "done": true}' https://api.example.com/notes/42
curl -sS -i -X DELETE https://api.example.com/notes/42
PUT replaces the whole note, so a field you leave out is
not kept from before. It goes back to its default value.
PATCH, where an API offers it, changes only the fields you
send.
Reading status codes
The three-digit status codeThe three-digit number at the start of an HTTP response that says how the request went, such as 200 for success, 302 for a redirect, or 401 when authentication is needed. is the server's short answer, and its first digit tells you the family before you know the exact code:
- 2xx: it worked.
- 3xx: look somewhere else, or use the copy you already have.
- 4xx: the problem is in the request. Sending the same request again usually gets the same answer, so something has to change first.
- 5xx: the problem is on the server. The same request may work later.
| Code | Name | What it usually means |
|---|---|---|
200 | OK | It worked, and the body holds the answer |
201 | Created | Something new was created, often with a Location header naming its address |
204 | No Content | It worked, and there is no body, as after a delete |
301, 302 | Moved Permanently, Found | Look at the address in the Location header instead |
304 | Not Modified | The copy you already have is still current, so no body is sent |
400 | Bad Request | The server could not make sense of the request, such as broken JSON |
401 | Unauthorized | Credentials are missing or not valid. A WWW-Authenticate header says what kind to send |
403 | Forbidden | The server refuses the request. If you sent credentials, they do not allow this |
404 | Not Found | Nothing exists at this address, or the server will not admit that it does |
409 | Conflict | The request clashes with the current state, such as a full list |
415 | Unsupported Media Type | The body is in a format the server does not accept, often a missing or wrong Content-Type |
422 | Unprocessable Content | The server read the body, but the values in it are not acceptable |
429 | Too Many Requests | Slow down. A Retry-After header often says how many seconds to wait |
500 | Internal Server Error | Something broke inside the server |
503 | Service Unavailable | The server cannot answer right now, perhaps with a Retry-After |
The difference between 401 and 403 matters
in identity work. Despite its name, 401 means "I do not
know who you are": send credentials, or better ones. 403
means "I understood the request, and the answer is no". When you sent
valid credentials, the server usually knows who you are and has
decided you may not do this. Sending the same credentials again will
not change it.
Sending credentials
Most APIs want to know who is calling. Two common ways of saying so
both use the Authorization header.
Basic authentication sends a username and password.
curl builds the header for you with -u:
curl -u ava:example-password https://api.example.com/accountThe request then carries this header:
Authorization: Basic YXZhOmV4YW1wbGUtcGFzc3dvcmQ=
The jumble after Basic is only
ava:example-password in base64A way of encoding data as ordinary text characters so it can travel safely in headers, URLs, and JSON. Anyone can decode it, so it hides nothing; Base64url is a variant safe for URLs, used in JWTs., the encoding from
Keys, encryption, and signatures, and anyone can decode it. It is not encryption, so Basic
authentication is safe only over HTTPSHTTP protected by TLS, so traffic is encrypted and checked for changes while it travels. It protects the connection, but does not prove that the site at the other end is honest.. A password typed on the command
line also lands in your shell history. Give -u just the
username, as in -u ava, and curl asks for the password
without showing it.
Bearer tokens are what most modern APIs use. As
How applications communicate explained, whoever holds a bearer token can use it, with no further
proof. You send it with -H, keeping it in a variable so
it never appears on screen or in your history:
read -rs API_TOKEN
curl -sS -H "Authorization: Bearer $API_TOKEN" https://api.example.com/notesThe double quotes let the shell put the token's value into the header. Tokens belong in headers over HTTPS and never in URLs: a URL ends up in server logs, browser history and your shell history, and anyone who reads it there could use the token.
The variable keeps the token off your screen and out of your history,
but not out of sight entirely. The shell expands
$API_TOKEN before curl starts, so the token is one of
curl's arguments. While curl runs, other people signed in to the same
computer can read every program's arguments with ps, the
command that lists running programs. On your own laptop that hardly
matters. On a shared server, hand curl the header on its standard
input instead:
printf 'Authorization: Bearer %s\n' "$API_TOKEN" | curl -sS -H @- https://api.example.com/notes
-H @- tells curl to read headers from standard input, one
per line, and -H @headers.txt reads them from a file.
printf runs inside the shell itself rather than as a
separate program, so the token never appears in any argument list.
When a request fails
To curl, a 404 or a 500 is not a failure. It
connected, sent the request and received a complete response, so it
exits with status 0, the code that means success. Exit
codes other than 0 are for problems that stopped the
exchange itself, such as a name that does not resolve (6), a connection
that is refused (7) or a request that times out (28).
That is a problem in scripts, where && and
if rely on exit codes. Two options make curl treat HTTP
errors as failures. --fail exits with code
22 for any status of 400 or above, and prints no body.
--fail-with-body exits with 22 too, but still
writes the body, which is usually where the server explains what went
wrong. Used as the condition of an if, it lets a script
take a different branch for an HTTP error:
if curl -sS --fail-with-body -o note.json https://api.example.com/notes/42; then
echo "Saved the note"
else
echo "The request failed. The server said:"
cat note.json
fiIf the note does not exist, the example output is:
curl: (22) The requested URL returned error: 404
The request failed. The server said:
{"error": "not_found"}
The error line appears because of -S, and the server's
explanation was saved in note.json. Without
--fail-with-body, the script would have said "Saved the
note" and kept the server's error message as if it were the note.
Using curl as a probe
Often you do not want the body at all, only one fact about the
answer: the status code, where a redirect points, or a single header.
-w, short for --write-out, prints details
that curl knows once the transfer ends, and -o /dev/null
throws the body away:
$ curl -sS -o /dev/null -w '%{http_code}\n' https://api.example.com/notes
200
That one number is easy to test in a script, for example
status=$(curl -sS -o /dev/null -w '%{http_code}' URL)
followed by [[ "$status" == 200 ]].
-w knows many other details, written the same way, such
as %{content_type} and %{time_total}.
Redirects deserve a closer look, because in identity work the
interesting part of a sign-in is often the address a server sends you
to, not the page at the end. curl does not follow redirects unless you
add -L, so it can show you a 302 and stop.
-D - writes the response headers to standard output (the
- means standard output), and grep -i keeps
the lines you care about, whatever the case of their names:
$ curl -sS -D - -o /dev/null 'https://photos.example.com/albums?view=grid' | grep -iE '^(HTTP/|location:)'
HTTP/2 302
location: /signin?next=%2Falbums%3Fview%3Dgrid
Without -L, curl stops at the 302 and shows
you where it points. With -L, curl sends a new request to
the Location and keeps going until a response is not a
redirect: here
GET /signin?next=%2Falbums%3Fview%3Dgrid, which answers
200 with the sign-in page. Add -i as well
and it prints every response along the way.
This Location is relative: it starts with
/, so it means the same scheme and host as the request,
https://photos.example.com/signin?next=..., as
How applications communicate described for redirects. %{redirect_url} resolves it for you and prints
the full address the redirect points to:
$ curl -sS -o /dev/null -w '%{http_code} %{redirect_url}\n' 'https://photos.example.com/albums?view=grid'
302 https://photos.example.com/signin?next=%2Falbums%3Fview%3Dgrid
To use a header's value in a script, cut it out of the headers.
cut -d' ' -f2 keeps the text after the first space, and
tr -d '\r' deletes the carriage return that ends every
header line. Without it, the variable holds an invisible
\r, and a URL built from it breaks in ways that are hard
to see:
next=$(curl -sS -D - -o /dev/null 'https://photos.example.com/albums?view=grid' | grep -i '^location:' | cut -d' ' -f2 | tr -d '\r')
printf '[%s]\n' "$next"
The brackets show where the value starts and ends, so a leftover
\r would be easy to spot. Reading a redirect without
following it lets you see exactly what the server handed back, such
as a value in the query, before any other server receives it. The same
pattern with www-authenticate: shows why a server refused
a request without the body getting in the way.
Check your understanding
Try these questions before moving on. If an answer isn't right, use the feedback and try again.
Try it in the Lab
- Create, replace and delete a note with curl, reading every status codeInspect requests and responses with -i and -v, send headers and JSON bodies, branch on HTTP errors, probe a redirect, then create, replace and delete a note whose address you capture from a header.