Requests, methods and curl
Anatomy of an HTTP request, the main methods and how to send them with curl.
What a request looks like
POST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json
Authorization: Bearer eyJhbGci...
{"name":"ana"}It has a request line (method, path, version), headers, an empty line and an optional body.
The main methods
| Method | Use | Has a body? |
|---|---|---|
GET | Read a resource | No |
POST | Create or submit data | Yes |
PUT | Replace a resource | Yes |
PATCH | Change part of a resource | Yes |
DELETE | Remove a resource | Usually no |
HEAD | Like GET but only the headers | No |
A safe method does not change anything on the server (GET, HEAD). An idempotent method has the same effect when repeated (GET, PUT, DELETE). POST is neither, so a browser asks before resending a form.
curl in practice
curl https://example.com # GET, prints the body
curl -i https://example.com # include response headers
curl -I https://example.com # HEAD request: headers only
curl -L http://example.com # follow redirects
curl -o page.html https://example.com # save to a file
curl -H "Accept: application/json" https://api.example.com/items
curl -X POST -d "name=ana" https://api.example.com/users
curl -X POST -H "Content-Type: application/json" -d '{"name":"ana"}' https://api.example.com/usersNote-d sends data as a form body and already implies POST, so -X POST is optional there. Quote the data in single quotes so the shell does not alter it.
Query strings and encoding
Values in a URL must be percent-encoded: a space becomes %20 and & becomes %26. A search for rock & roll is ?q=rock%20%26%20roll.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.