urllib POST requests in Python
Sending a JSON body with urllib, no third-party libs.
import json
import urllib.request
payload = json.dumps({"title": "hello", "body": "world"}).encode()
req = urllib.request.Request(
"https://api.example.com/posts",
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=10) as res:
created = json.loads(res.read())
location = res.headers.get("Location")
How it works
- The payload is JSON encoded to bytes.
- Passing
dataandmethod='POST'sets the verb. - The response body and headers are read back.
Keywords and builtins used here
aswith
The run, in numbers
- Lines
- 14
- Characters to type
- 367
- Tokens
- 109
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 62 seconds.
Step 2 of 4 in Web, step 11 of 41 in Domain tools.