Skip to content

Chapter 3 · POST and Request Body Construction ​

Chapter goals: master POST, PUT, DELETE and other methods; learn to build JSON bodies, form bodies, and multipart uploads.

3.1 HTTP Methods at a Glance ​

Besides GET, the commonly used HTTP methods are:

MethodPurposeIdempotent
GETFetch a resource✅
POSTCreate a resource / submit data❌
PUTReplace a resource entirely✅
PATCHUpdate part of a resource❌
DELETEDelete a resource✅
HEADFetch headers only (no body)✅
OPTIONSQuery supported methods✅
python
import requests

base = 'https://httpbin.org'

# GET - read
resp = requests.get(f'{base}/get')

# POST - create
resp = requests.post(f'{base}/post', json={'key': 'value'})

# PUT - full update
resp = requests.put(f'{base}/put', json={'key': 'value'})

# PATCH - partial update
resp = requests.patch(f'{base}/patch', json={'key': 'value'})

# DELETE - delete
resp = requests.delete(f'{base}/delete')

3.2 JSON Request Bodies ​

Modern APIs mostly exchange data as JSON. requests provides the json argument:

python
import requests

# Option 1: use the json argument (recommended; sets Content-Type automatically)
resp = requests.post(
    'https://httpbin.org/post',
    json={'name': 'Alice', 'age': 30, 'tags': ['python', 'ai']}
)
print(resp.json()['json'])  # {'name': 'Alice', 'age': 30, ...}

# Option 2: manual serialization (when you need a custom Content-Type)
import json
resp = requests.post(
    'https://httpbin.org/post',
    data=json.dumps({'name': 'Alice'}),
    headers={'Content-Type': 'application/json'}
)

The json argument automatically:

  • Serializes the Python object into a JSON string
  • Sets the Content-Type: application/json header

3.3 Form Request Bodies ​

Classic HTML forms use the application/x-www-form-urlencoded format:

python
import requests

# Form data (encoded automatically)
resp = requests.post(
    'https://httpbin.org/post',
    data={'username': 'admin', 'password': 'secret123'}
)

# Inspect what was sent
print(resp.json()['form'])  # {'username': 'admin', 'password': 'secret123'}

3.4 File Uploads ​

Use the files argument for single or multiple file uploads:

python
import requests

# Upload a single file
with open('report.pdf', 'rb') as f:
    resp = requests.post(
        'https://httpbin.org/post',
        files={'document': f}
    )

# Upload multiple files
files = [
    ('photos', ('a.jpg', open('a.jpg', 'rb'), 'image/jpeg')),
    ('photos', ('b.jpg', open('b.jpg', 'rb'), 'image/jpeg')),
]
resp = requests.post('https://httpbin.org/post', files=files)

# Custom filename and content type
resp = requests.post(
    'https://httpbin.org/post',
    files={
        'file': ('custom_name.txt', b'file content', 'text/plain')
    }
)

The files argument accepts several shapes:

  • A file object: {'file': open('x.pdf', 'rb')}
  • A tuple: {'file': ('name.ext', content, 'mime/type')}

3.5 Combining Request Bodies ​

In real scenarios you often need form fields and files together:

python
import requests

# Form fields + file
resp = requests.post(
    'https://httpbin.org/post',
    data={'title': 'Report', 'category': 'Engineering'},
    files={'document': open('report.pdf', 'rb')}
)

# Complex case: multiple files + fields
files = [
    ('attachments', ('doc1.pdf', open('doc1.pdf', 'rb'), 'application/pdf')),
    ('attachments', ('doc2.pdf', open('doc2.pdf', 'rb'), 'application/pdf')),
]
data = {
    'project': 'Alpha',
    'description': 'Quarterly report',
    'priority': 'high'
}
resp = requests.post('https://example.com/upload', data=data, files=files)

3.6 The httpx Equivalents ​

httpx's API is highly consistent with requests:

python
import httpx

# POST with JSON
resp = httpx.post('https://httpbin.org/post', json={'key': 'value'})

# POST with form data
resp = httpx.post('https://httpbin.org/post', data={'key': 'value'})

# File upload
with open('file.txt', 'rb') as f:
    resp = httpx.post('https://httpbin.org/post', files={'file': f})

3.7 Chapter Summary ​

  • The POST/PUT/PATCH/DELETE methods map to identically named functions in requests;
  • Use json for JSON bodies — it serializes automatically and sets Content-Type;
  • Use data for form fields and files for uploads;
  • httpx syntax is highly compatible with requests.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. What is the difference between the json and data arguments in requests.post()?

2. Which of these correctly uploads a file?

3. What is the main difference between PUT and PATCH?

4. How does the files argument in httpx compare to requests?

🛠️ Hands-On Exercises ​

  1. POST JSON to https://httpbin.org/post and print the returned JSON fields.
  2. Upload a text file to httpbin and inspect the filename and content the server received.
  3. Combine form fields with a file upload to simulate "submitting a form with attachments".