Python Handle JSON Decode Error
Author: Newtum
This guide explains how to gracefully handle a `JSONDecodeError` when an API response is expected to be JSON but is not, or is malformed.
The Problem: Invalid JSON
Calling `.json()` on a response that does not contain valid JSON will raise a `requests.exceptions.JSONDecodeError`. This can happen if the server returns an HTML error page, plain text, or malformed JSON.
Handling the Exception
You should wrap the `response.json()` call in a `try...except` block to catch the `JSONDecodeError` and handle it, for example by inspecting the raw text of the response.
