typestar

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

  1. The payload is JSON encoded to bytes.
  2. Passing data and method='POST' sets the verb.
  3. The response body and headers are read back.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Web, step 11 of 41 in Domain tools.

← Previous Next →