CertGrid CertGrid
Hands-on Lab·Python Automation for IT

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

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.

Everything on this page runs on the control node. Any machine with Python 3 will do.
Server NameIP AddressOSRolesCPURAMHDD
RUNNER01192.168.0.27Ubuntu 26.04 LTSControl node - every script in this path runs here2 Core4 GB50 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.

Before you start

  1. The API these guides talk to

  2. A first GET

  3. Three ways to check whether it worked

  4. text, content and json

  5. An error page is not JSON

  6. Query parameters, without building the string yourself

  7. A Session, and what it actually reuses

  8. The headers a Session sets once

  9. When the server is not there at all

Official sources