Sending a body with curl
Reading is GET. To send data, use POST with a body, which in modern APIs is almost always JSON, the {"key": "value"} data format from lesson 4-4. With curl:
curl -X POST https://api.example.com/notes \ -H "Content-Type: application/json" \ -d '{"text": "buy milk", "done": false}'
Three new flags:
-X POSTsets the method (lesson 4-3).-Hadds a request header.Content-Type: application/jsontells the server how to parse the body (the same header you read out of a response in lesson 4-2, now going the other way).-dsupplies the body. curl automatically computesContent-Lengthfor you.
Many APIs also require proof of who you are, usually another header: -H "Authorization: Bearer YOUR_TOKEN".
A guided session against a practice JSON API. Watch the status codes: they follow the lesson 4-3 rules exactly.
Step 1/4: Create a note with POST. The API answers 201 Created and echoes the stored object back, now with an id.
Code exercise · python
Run this. Offline, but real: json.dumps turns a Python dict into the exact body text you would pass to curl -d, and json.loads parses a response body string back into data. Note Python's False becomes JSON's false.
Code exercise · python
Your turn. This response body came back from GET /users/ada. Parse it with json.loads and print one line per repo in the format shown. The repos live in a list under the "repos" key.
Problem
You POST a JSON body to an API but the server keeps answering 400 and says it received plain text. Which request header, with which value, tells the server your body is JSON? Answer in the form Header: value.