Python JSON API Requests and Responses
Sending data is where the errors get interesting: data= and json= do completely different things to the same dict, a rejected request has an explanation you have to go and fetch, and json= refuses five types that appear in real payloads - datetimes, Decimals, UUIDs, Paths and sets. This guide fixes each, and explains why money goes on the wire as a string.
APIs and Cloud Guide 26 of 39 Intermediate
- Control nodeUbuntu 26.04 LTS
- Python3.14.4
- requests2.34.2
- paramiko5.0.0
- TimeAbout 16 min
json= has been in requests since 2.4.2. json.dumps(default=...) is standard library and unchanged. The lab's fixture echoes back whatever it receives, which makes the round trip visible.
- pytest9.1.1
- PyYAML6.0.3
- boto3 / botocore1.43.78
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Control node - every script in this path runs here | 2 Core | 4 GB | 50 GB |
This guide includes
Use this when you are sending data rather than fetching it. This matters because json= and data= do completely different things to the same dictionary - and json= refuses five types that turn up in real payloads.
- posting JSON, and comparing
json=withdata= - reading what the server said about a 400
- finding the five types
json=refuses, and converting them deliberately - sending Decimal as a string rather than a float, and why
- wrapping it all in one function that raises with the server's own message
Before you start
-
Posting JSON
-
json= against data=
-
A 400, and reading what the server said about it
-
What json= refuses to serialise
-
So convert them, deliberately
-
Decimal, and why str rather than float
-
The whole thing as one function