How do you send JSON, form data and files with `requests`?
BeginnerConceptData formats, HTTP & REST APIs
Answer
s.post(url, json={"name": "api", "replicas": 3}, timeout=10) # sets Content-Type: application/json
s.post(url, data={"user": "ci", "token": t}, timeout=10) # form-encoded
with open("report.html", "rb") as f:
s.post(url, files={"file": ("report.html", f, "text/html")}, timeout=30)
A common mistake is data=json.dumps(payload) without the header, which the server receives as text/plain or form data and rejects with 415 or 400.
More on Data formats, HTTP & REST APIs
How do you read and write JSON, and what are the common gotchas?BeginnerWhy must you use `yaml.safe_load` rather than `yaml.load`?BeginnerHow do you load a multi-document Kubernetes YAML file?IntermediateHow do you read and write CSV files properly?BeginnerHow do you make an HTTP request with `requests` the right way?BeginnerWhy use a `requests.Session`?Intermediate