What's the correct `content-type` when editing posts?

@pedroleaoc here is a little sample python script that demonstrates how to make authenticated requests and how to send the request data for put/post requests.

# discourse-api-demo.py
import requests
from requests.structures import CaseInsensitiveDict

# Basic GET request to a public url, no headers needed.
url = "http://localhost:3000/posts/10.json"

resp = requests.get(url)

print(resp.status_code)
print(resp.content)

# GET request to a private endpoint. Authentication headers are needed.
url = "http://localhost:3000/admin/users/list/active.json"
headers = {'Api-Username': 'system', 'Api-Key': '5c1c57915e2...'}
resp = requests.get(url, headers=headers)

print(resp.status_code)
print(resp.content)

# PUT request with a request body
url = "http://localhost:3000/posts/10.json"
data = { 'raw': "Cool post, but here's an updated to the post's body", 'edit_reason': "I changed this because I can." }

resp = requests.put(url, headers=headers, json=data)
print(resp.status_code)
print(resp.content)

From Quickstart — Requests 2.32.3 documentation

Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:

url = 'https://api.github.com/some/endpoint' >>> payload = {'some': 'data'} >>> r = requests.post(url, json=payload)

Note, the json parameter is ignored if either data or files is passed.

Using the json parameter in the request will change the Content-Type in the header to application/json .

1 Like