When 2Captcha Returns HTML Instead of JSON
Test a balance API with Python and GitHub Actions before a bad response reaches your dashboard

An account-balance widget can show $0.00 for two very different reasons. The account might genuinely be empty, or the lookup might have failed and the code defaulted to zero. I’d rather discover that bug in a pull request than from an alert during a release. The example here uses the read-only balance endpoint from 2Captcha.
The failure I want to catch is an HTTP 200 with an HTML response. An intermediary can return an error page with a successful status, and a client that only checks the status will pass the page straight to its JSON decoder. I’ll put a small Python client in front of the dashboard and run its contract tests against a local HTTP server. The server will send real HTTP responses, including the ones I’d have trouble reproducing against a live account.
Decide what a successful response means
The balance endpoint accepts a JSON POST with a clientKey. Its documented success response has an integer errorId of 0 and a numeric balance. A valid 200 gets the client through the HTTP check. The response still has to pass the content type, JSON and application checks before I can show a balance. 2Captcha’s getBalance reference
I keep two outcomes in the application model. A successful read contains a decimal amount and can include zero. A failed read contains a reason and has no new amount. The distinction matters downstream. A low-balance alert should fire on a fresh zero. On a failed refresh, the dashboard can keep the most recent successful amount, show when it was last verified and mark it stale. If there has never been a successful read, show “Balance unavailable.”
| Response | Result | What I’d check first |
|---|---|---|
200 with valid JSON and balance: 0 |
Successful read of zero | The account balance |
200 with text/html |
content_type |
Recent proxy, routing or service changes |
200 with malformed JSON |
invalid_json |
Response framing or a broken intermediary |
200 with an application error |
provider_error_<id> |
The documented meaning of the error ID |
429 or 503 |
http_429 or http_503 |
Request frequency or upstream availability |
307 with a redirect |
http_307 |
The configured host and request path |
These are client outcomes for the fixtures below. They’re useful even when the provider’s actual failure response differs. In particular, a content-type failure tells me what arrived at the client. It takes independent evidence to identify which hop sent it. 2Captcha’s API error reference
Put the checks in one place
Save this as balance_client.py. The production wrapper connects to a fixed HTTPS host. I can exercise the same request and validation logic locally by passing a connection to a loopback server. The example has no retry loop, so each call makes one request. HTTP redirects are surfaced as failures, which keeps the credential from being forwarded to a different destination.
import json
from decimal import Decimal, InvalidOperation
from http.client import HTTPConnection, HTTPException, HTTPSConnection
MAX_BODY_BYTES = 16 * 1024
class BalanceError(Exception):
"""The message is a diagnostic label safe to log."""
def read_balance(connection: HTTPConnection, client_key: str) -> Decimal:
try:
connection.request(
"POST",
"/getBalance",
body=json.dumps({"clientKey": client_key}).encode("utf-8"),
headers={"Content-Type": "application/json", "Accept": "application/json"},
)
with connection.getresponse() as response:
if response.status != 200:
raise BalanceError(f"http_{response.status}")
media_type = response.getheader("Content-Type", "")
if media_type.split(";", 1)[0].strip().lower() != "application/json":
raise BalanceError("content_type")
body = response.read(MAX_BODY_BYTES + 1)
if len(body) > MAX_BODY_BYTES:
raise BalanceError("body_too_large")
if response.length not in (None, 0):
raise BalanceError("incomplete_body")
except TimeoutError:
raise BalanceError("timeout") from None
except (OSError, HTTPException):
raise BalanceError("transport") from None
finally:
connection.close()
try:
payload = json.loads(body, parse_float=Decimal, parse_constant=Decimal)
except (ValueError, InvalidOperation, RecursionError):
raise BalanceError("invalid_json") from None
if not isinstance(payload, dict):
raise BalanceError("invalid_envelope")
error_id = payload.get("errorId")
if type(error_id) is not int or not 0 <= error_id <= 9999:
raise BalanceError("invalid_envelope")
if error_id:
raise BalanceError(f"provider_error_{error_id}")
value = payload.get("balance")
if type(value) not in (int, Decimal):
raise BalanceError("invalid_balance")
amount = Decimal(value)
if not amount.is_finite():
raise BalanceError("invalid_balance")
return amount
def get_balance(client_key: str) -> Decimal:
return read_balance(HTTPSConnection("api.2captcha.com", timeout=3), client_key)
Three details are easy to miss. Python treats True as an integer for isinstance checks, which is why the two numeric fields use an exact type check. Parsing fractional amounts directly into Decimal preserves the digits the server sent. The finite check excludes NaN and Infinity, which Python’s JSON decoder accepts by default even though they fall outside standard JSON.
The client keeps arbitrary response text out of its errors. An HTML page can contain cookie prompts, routing details or values echoed by a server. A diagnostic event needs a stable reason, an elapsed time and a timestamp. I’d put an upstream request ID in the event only when the integration has a documented header for it. For metrics, I’d use broad categories such as http, transport and invalid_response and leave the individual provider IDs in logs.
The 16 KiB response limit is an application choice for this tiny endpoint. The socket timeout limits individual blocking operations. If the balance job has a strict end-to-end budget, enforce the overall deadline in the worker that calls the client. Track the timestamp of the last successful read separately so a dashboard can show data age even when an in-flight request stalls.
Test over HTTP with a disposable fixture
Save this as test_balance_client.py. I use a server bound to 127.0.0.1 on an ephemeral port, so each case owns its socket. The handler records what the client sent and then writes a response for that case. This covers more than calling a parser directly. A test can detect a wrong method, path or request payload, and the same suite covers the usual response failures.
import json
import unittest
from decimal import Decimal
from http.client import HTTPConnection
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from balance_client import BalanceError, read_balance
class BalanceContractTest(unittest.TestCase):
def check_exchange(self, status, body, *, expected=None, error=None,
content_type="application/json", length=None):
requests = []
class FixtureHandler(BaseHTTPRequestHandler):
def do_POST(self):
size = int(self.headers["Content-Length"])
requests.append((self.command, self.path, self.rfile.read(size)))
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body) if length is None else length))
if status == 307:
self.send_header("Location", "/unexpected")
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args):
pass
with HTTPServer(("127.0.0.1", 0), FixtureHandler) as server:
worker = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.01})
worker.start()
connection = HTTPConnection("127.0.0.1", server.server_port, timeout=2)
try:
if error is None:
self.assertEqual(read_balance(connection, "fixture-key"), expected)
else:
with self.assertRaises(BalanceError) as raised:
read_balance(connection, "fixture-key")
self.assertEqual(str(raised.exception), error)
finally:
server.shutdown()
worker.join()
self.assertEqual(len(requests), 1)
method, path, raw = requests[0]
self.assertEqual((method, path), ("POST", "/getBalance"))
self.assertEqual(json.loads(raw), {"clientKey": "fixture-key"})
def test_preserves_decimal_precision(self):
self.check_exchange(200, b'{"errorId":0,"balance":0.1234567890123456789}',
expected=Decimal("0.1234567890123456789"),
content_type="application/json; charset=utf-8")
def test_zero_is_a_success(self):
self.check_exchange(200, b'{"errorId":0,"balance":0}', expected=Decimal("0"))
def test_html_with_http_200(self):
self.check_exchange(200, b"<html>Gateway unavailable</html>",
content_type="text/html", error="content_type")
def test_malformed_json(self):
self.check_exchange(200, b'{"errorId":', error="invalid_json")
def test_truncated_http_body(self):
body = b'{"errorId":0,"balance":1}'
self.check_exchange(200, body, length=len(body) + 5, error="incomplete_body")
def test_provider_error(self):
self.check_exchange(200, b'{"errorId":1,"errorCode":"ERROR_KEY_DOES_NOT_EXIST"}',
error="provider_error_1")
def test_wrong_balance_types(self):
for value in (b'true', b'null', b'"0.25"', b'NaN', b'Infinity'):
with self.subTest(value=value):
self.check_exchange(200, b'{"errorId":0,"balance":' + value + b'}',
error="invalid_balance")
def test_wrong_envelope(self):
for body in (b'[]', b'{"errorId":false,"balance":0}', b'{"balance":1}'):
with self.subTest(body=body):
self.check_exchange(200, body, error="invalid_envelope")
def test_http_failures(self):
for status in (429, 503):
with self.subTest(status=status):
self.check_exchange(status, b"unavailable", error=f"http_{status}")
def test_redirect_is_not_followed(self):
self.check_exchange(307, b"", error="http_307")
def test_oversized_response(self):
self.check_exchange(200, b" " * 17000, error="body_too_large")
Run python -m unittest -v. The deliberately truncated case sends a complete JSON object but claims a longer body in Content-Length. A decoder alone would accept it. The client rejects the incomplete HTTP response before using the amount. The redirect case checks that the fixture only received one request, so a careless change that silently follows the redirect will also fail.
On a local Python 3.13.6 run, all 11 tests passed. This output comes from the loopback test suite. Use the separate manual check below to test live connectivity with your own key.
Ran 11 tests in 0.180s
OK
Run the same test on every pull request
With both Python files at the repository root, save this as .github/workflows/balance-contract.yml. I use pull_request and give the job read-only repository access. The workflow needs no provider secret, so contributors can run the same tests from forks. The checkout step also disables credential persistence because the job only needs to read its checkout. GitHub’s checkout action and Python setup action
name: Balance API contract
on: [pull_request]
permissions:
contents: read
jobs:
contract:
runs-on: ubuntu-latest
timeout-minutes: 3
steps:
- uses: actions/checkout@v6
with:
persist-credentials: false
- uses: actions/setup-python@v6
with:
python-version: '3.13'
- run: python -m unittest -v
A thousand local fixture requests generate zero requests to the provider, so the provider charge for those fixtures is zero. Runner time is an independent cost if the repository pays for hosted CI minutes. I’d keep the pull request check deterministic and use a single authenticated read from a trusted environment when I need to verify live connectivity or a credential change.
Check the behavior readers will actually see
Once the client is covered, I’d add one dashboard test around a sequence of three responses. Start with a successful balance of 0.25, send an HTML failure and finish with a successful balance of 0. During the failure, the widget should still show 0.25 with a stale indicator and retain the original verification timestamp. When the third response arrives, it should show a fresh zero, advance the timestamp and let the low-balance alert evaluate the new amount. A dashboard that updates its “last checked” label can show the failed attempt separately from the last verified value.
I’d set the stale threshold from the refresh schedule. For a widget that polls once every five minutes, two missed refreshes are a reasonable starting point for deciding when to notify the operator. An isolated 503 and a sustained outage then have different effects. Keep the threshold in the dashboard or worker, where it can change without touching the HTTP contract. If a proxy starts labeling its HTML error page as JSON, the client will report invalid_json instead of content_type. Both outcomes should take the same stale-state path in the widget.
Make one live read when it answers a real question
After injecting TWOCAPTCHA_API_KEY through your environment’s secret manager, run the wrapper below from a trusted shell. This prints a short result and keeps the account amount out of shared job output. An ok means the endpoint accepted the request and returned a valid balance at that moment. A provider error gives you an ID to look up before retrying.
python - <<'PY'
import os
from balance_client import BalanceError, get_balance
key = os.environ.get("TWOCAPTCHA_API_KEY")
if not key:
raise SystemExit("TWOCAPTCHA_API_KEY is missing")
try:
get_balance(key)
except BalanceError as exc:
raise SystemExit(f"Balance contract failed ({exc})") from None
print("Balance contract OK")
PY
If the live call returns 429, leave the second attempt to the worker’s rate-limit policy. If it returns a credential error, check how the key was deployed. If it returns HTML, check which component produced the page before changing the parser. Every failure path protects the last verified balance from being silently replaced by zero.
Try the zero and HTML fixtures first. If they produce different states all the way through your dashboard, you’ve fixed the bug that motivated this example. When you’re ready to check the real account path, open 2Captcha and run one balance read from your trusted environment.
Prepared with AI assistance. The Python examples were run against a local HTTP fixture.
Further reading
- 2Captcha pricing and service overview to understand the service and its cost model.
- Choosing fields for a balance trace to decide which context belongs in safe diagnostics.
Comments
Join the discussionNo comments yet. Be the first to comment.





