Python HTTP Requests and Status Codes
Most automation eventually calls an API. requests.get is four characters more than you need to get it wrong, so this guide is about the parts that bite: ok is not == 200, raise_for_status throws away the server's explanation, an error page is usually HTML rather than JSON, and a Session is worth using for a reason you can count rather than time.
APIs and Cloud Guide 24 of 39 Intermediate
- Control nodeUbuntu 26.04 LTS
- Python3.14.4
- requests2.34.2
- paramiko5.0.0
- TimeAbout 18 min
requests 2.34.2 in the lab's virtual environment. r.json() raising requests.exceptions.JSONDecodeError rather than the stdlib one arrived in 2.27; before that you caught ValueError.
- 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 because most automation eventually calls an API. This matters because an error page is not JSON - the call that breaks in production is the one that assumed it was.
- making a first GET, and reading everything the response carries
- checking whether it worked three different ways
- separating
text,contentandjson, and meeting the error page that is not JSON - passing query parameters without building the string yourself
- using a Session and seeing what it actually reuses, then meeting the server that is not there
Before you start
-
The API these guides talk to
-
A first GET
-
Three ways to check whether it worked
-
text, content and json
-
An error page is not JSON
-
Query parameters, without building the string yourself
-
A Session, and what it actually reuses
-
The headers a Session sets once
-
When the server is not there at all