---
title: "Catch broken JSON links on localized pages"
description: "A localized page can return HTTP 200 while its JSON link fails. Reproduce the defect with a self-contained Python example and turn the observations into release checks."
author: "DIMA Mochalov"
author_url: "https://www.stackandskill.com/authors/dima-mochalov-inevidimka"
published: 2026-11-20
format: tutorial
tags: ["devops", "python", "testing", "localization"]
tested_with: ["Python 3.12.3"]
verified: 2026-11-20
reading_time: 10 min
related: ["https://www.stackandskill.com/blog/azure-devops-to-github-migrate-without-losing-your-history", "https://www.stackandskill.com/blog/building-a-rag-pipeline", "https://www.stackandskill.com/blog/zero-downtime-deployments-docker-github-actions"]
url: "https://www.stackandskill.com/blog/catch-broken-json-links-on-localized-pages"
cite: "Mochalov, D. (2026). Catch broken JSON links on localized pages. Stack & Skill. https://www.stackandskill.com/blog/catch-broken-json-links-on-localized-pages"
---

# Catch broken JSON links on localized pages

A localized page can pass a release check with HTTP 200 while a JSON link in its HTML points to a file that no longer exists at that address. During a multilingual site audit, I investigated four broken JSON links reported by a crawler. The localized pages linked to translated filenames that did not exist on the server. I proposed excluding the resource paths from translation or using stable absolute URLs. A colleague reported completing the fix. A later check found working links to the original JSON filenames.

The tutorial below models the same failure pattern with generated pages. It changes a path by adding a language prefix, while the original incident involved translated filenames. This makes the failure reproducible without the client’s site, code or translation plugin.

**The release check in one minute**

- Fetch the localized page and extract the resource link from the HTML it actually serves.
- Resolve that link against the page URL and request the resulting address.
- Check the resource’s response status, media type, and expected JSON data.
- Repeat the check on each locale that ships the link.

## How can a page return 200 while its JSON link is broken?

An HTTP response describes the request that produced it. A successful response for an HTML document says the server answered that document request. The JSON resource has its own URL and gets its own response. If the smoke test stops at the page response, the file remains unchecked. [HTTP semantics for 200 OK](https://www.rfc-editor.org/rfc/rfc9110.html#name-200-ok)

Take a site that serves one catalog at `/shared/catalog.json`. Its translated HTML can use localized labels while pointing to the same file. Now suppose a rewrite adds the locale prefix to that resource path. The Finnish page still loads, but the HTML sends the reader to `/fi/shared/catalog.json`. If the server only serves the catalog at the shared path, that follow-up request fails.

Both paths start with a slash. Given a base page such as `https://example.com/fi/overview`, a leading slash resolves from the origin root. The browser goes to the locale-prefixed URL because the link already contains the prefix. The demonstration changes the emitted link to model that behavior. The same approach can catch a different rewrite, such as a change to the filename. [MDN’s guide to resolving relative URL references](https://developer.mozilla.org/en-US/docs/Web/API/URL_API/Resolving_relative_references)

## How do you reproduce the failure locally?

The script below starts an HTTP server on the loopback address and asks the operating system for a free port. It serves two synthetic locales, Finnish and Dutch. Each locale has a rewritten page and a shared-path page. All four pages return HTML with status 200. The rewritten pages point to a missing locale-prefixed file. The other pages point to the shared catalog.

Save the block as `replay.py` in a writable directory and run `python3 replay.py`. It uses Python’s standard library and was tested on Python 3.12.3. The script prints the observations and writes or replaces `observed.json` next to the script. It shuts down the local server when the run finishes.

```python
#!/usr/bin/env python3
"""Reproduce a localization rewrite that breaks a shared machine resource."""

import json
from html.parser import HTMLParser
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from threading import Thread
from urllib.error import HTTPError
from urllib.parse import urljoin
from urllib.request import urlopen


LOCALES = {"fi": "Esittely", "nl": "Overzicht"}
RESOURCE = "/shared/catalog.json"
CATALOG = {"version": 1, "entries": [{"id": "demo-item"}]}
OUTPUT = Path(__file__).with_name("observed.json")


class LinkReader(HTMLParser):
    def __init__(self):
        super().__init__()
        self.links = []

    def handle_starttag(self, tag, attrs):
        attributes = dict(attrs)
        if tag == "a" and attributes.get("data-purpose") == "machine-catalog":
            self.links.append(attributes.get("href"))


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


class FixtureHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == RESOURCE:
            return self.respond(200, "application/json", json.dumps(CATALOG))

        parts = self.path.strip("/").split("/")
        if len(parts) == 3:
            variant, locale, page = parts
            if variant in ("rewritten", "shared") and locale in LOCALES and page == "overview":
                href = f"/{locale}{RESOURCE}" if variant == "rewritten" else RESOURCE
                title = LOCALES[locale]
                return self.respond(200, "text/html", f"""<!doctype html>
<html lang="{locale}"><meta charset="utf-8"><title>{title}</title>
<main><h1>{title}</h1><a data-purpose="machine-catalog" href="{href}">JSON</a></main>
</html>""")

        self.respond(404, "text/html", "<!doctype html><title>Missing test resource</title>")

    def respond(self, status, content_type, text):
        body = text.encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", f"{content_type}; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, format, *args):
        return


def get(url):
    try:
        with urlopen(url, timeout=5) as response:
            return response.status, response.headers.get_content_type(), response.read().decode()
    except HTTPError as response:
        with response:
            return response.code, response.headers.get_content_type(), response.read().decode()


def measure(base_url, variant, locale):
    page_path = f"/{variant}/{locale}/overview"
    page_url = urljoin(base_url, page_path)
    page_status, page_type, page_body = get(page_url)
    require(
        page_status == 200 and page_type == "text/html",
        f"{page_path}: expected HTML 200, got {page_status} {page_type}",
    )

    parser = LinkReader()
    parser.feed(page_body)
    require(
        len(parser.links) == 1 and bool(parser.links[0]),
        f"{page_path}: expected exactly one nonempty catalog link, got {parser.links!r}",
    )
    href = parser.links[0]
    asset_url = urljoin(page_url, href)
    asset_status, asset_type, asset_body = get(asset_url)
    parsed = json.loads(asset_body) if asset_type == "application/json" else None

    if variant == "rewritten":
        expected = (404, "text/html", None)
    else:
        expected = (200, "application/json", CATALOG)

    require(
        (asset_status, asset_type, parsed) == expected,
        f"{page_path}: unexpected fixture response from {asset_url}: "
        f"{asset_status} {asset_type}, parsed={parsed!r}",
    )

    return {
        "locale": locale,
        "variant": variant,
        "pagePath": page_path,
        "pageStatus": page_status,
        "href": href,
        "assetUrl": asset_url,
        "assetStatus": asset_status,
        "assetType": asset_type,
        "parsedJson": parsed,
        "catalogUsable": (asset_status, asset_type, parsed) == (
            200, "application/json", CATALOG
        ),
    }


def main():
    with ThreadingHTTPServer(("127.0.0.1", 0), FixtureHandler) as server:
        thread = Thread(target=server.serve_forever, daemon=True)
        thread.start()
        server_url = f"http://127.0.0.1:{server.server_port}"
        try:
            rows = [measure(server_url, variant, locale)
                    for locale in LOCALES for variant in ("rewritten", "shared")]
        finally:
            server.shutdown()
            thread.join()

    report = json.dumps({"scope": "Generated fixture served over loopback HTTP", "observations": rows},
                        ensure_ascii=False, indent=2) + "\n"
    OUTPUT.write_text(report, encoding="utf-8")
    print(report, end="")


if __name__ == "__main__":
    main()
```

The script selects the catalog anchor by its `data-purpose` attribute. That lets the visible link text change with the locale. It resolves the extracted `href` with `urljoin` and fetches the result. `urllib` raises `HTTPError` for a 404, so the helper records the status and media type from that response as well. Each observation contains the page path and the literal link, which makes it possible to see where the rewrite happened. [Python’s documentation for `urljoin`](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin) and [`HTTPError`](https://docs.python.org/3/library/urllib.error.html#urllib.error.HTTPError)

| Locale | Status of either HTML page | Rewritten link and asset response | Shared link and asset response |
|---|---|---|---|
| Finnish | 200 | `/fi/shared/catalog.json` → 404, `text/html` | `/shared/catalog.json` → 200, `application/json` |
| Dutch | 200 | `/nl/shared/catalog.json` → 404, `text/html` | `/shared/catalog.json` → 200, `application/json` |

These are the results from the local replay. Both shared links returned the same JSON object with `version` set to `1` and an `entries` array containing `demo-item`. The script checks equality with the fixture’s expected object and records whether the catalog is usable. In this small example, an exact match is practical because the entire object is controlled. A real catalog may change frequently, so a release check should validate the fields and types its consumers require.

## What does a successful script run mean?

A normal run writes four observations. The two rewritten paths have `catalogUsable: false`, and the two shared paths have `catalogUsable: true`. The process exits with code 0 when both the deliberately broken and working examples behave as expected. A mismatch raises an error and stops the run. These expectations let you check that the demonstration still exposes the defect.

For a release gate, every required catalog must be usable. If you adapt this example to staging, remove the branch that expects a 404 and require a successful response for every page. A missing or duplicated catalog link should fail the check as well. The sample enforces one nonempty matching link and raises explicit errors, including when Python runs with optimization enabled.

Try changing the rewritten href in `FixtureHandler` to `RESOURCE`. The demonstration will stop because the deliberately broken example now works. That is the point at which a real release check should pass after its expected response has been changed to 200 and valid JSON.

## What should a real release check verify?

1. **Choose the localized pages that should carry the link.** Start from the list of routes and locales that the deployment actually ships. Include at least one page per template that renders the link. If a locale has an override for that template, check that route too. A link on the default language page can be healthy while the translated HTML points somewhere else.
2. **Identify the link by its purpose.** The demo uses an attribute that survives translated labels. On your site, use a selector that uniquely identifies the intended link. Have the check report missing or duplicate matches. If the build owns the markup, keeping a stable attribute gives the check a way to find the link even when copy editors change its caption.
3. **Resolve the exact URL that the page emitted.** Use the final document URL when a request redirects. Account for any `<base href>` that changes how the browser resolves relative links. A page that adds the link in JavaScript needs a browser check that reads the rendered DOM. For a catalog that should stay on your own site, restrict requests and redirects to the expected origin. [MDN’s documentation for the HTML `base` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/base)
4. **Verify what you actually received.** Use a GET request so you can inspect the body. Expect the status and media type that your resource promises. Parse the JSON and check the fields a consumer uses, such as the catalog version and the shape of its entries. A missing file behind a catch-all route can answer with an HTML page and status 200. The media-type and body checks make that failure visible. If two locales intentionally use different catalogs, set the expected path and data for each.
5. **Print enough detail to fix a failure.** Include the tested page, literal `href`, resolved URL and response status. Add the media type or the first failing field when the URL returns a response. If the link goes through redirects, retain the destination so reviewers can tell whether the working response came from the right resource. A failure such as “Finnish overview → `/fi/shared/catalog.json` → 404” gives the developer a place to start.

## How do you tell which layer to investigate?

Read the failure from left to right. If the translated page fails to load, start with its route or deployment. If the page opens and the anchor is missing, inspect the template or the transform that produced the markup. If the anchor exists and the literal path differs from the one configured for that locale, capture both values and check where the path is assembled.

A correct href with a failing response points you towards the resource route or the components in front of it. Check whether the file was deployed where the link expects it, then inspect routing, redirects, and caching. For example, a correct final path that serves an earlier catalog version may require comparing the response from the deployment with the expected build artifact.

Keep locale-specific expectations close to the list of pages the check reads. For a shared catalog, each check can reuse one resource path and one data contract. For per-language files, list each expected path and verify the fields readers rely on. This gives reviewers a concrete way to distinguish a broken link from an intended localization change.

## Where should the fix go?

If the file is shared by design, keep its URL in the template or configuration that owns resource paths. Give the translation system the visible label. When a build rewrites links automatically, exclude this resource from the rewrite and keep a regression check against the resulting HTML. A localized catalog should have its own expected URL for each language, with fixtures that check that distinction explicitly.

After a change, fetch the same published or staging page that exposed the failure. Confirm that the link now resolves to the intended catalog and returns the expected data. Start at the page again. An old href can survive in a generated page or a cached response even while a direct request to the corrected catalog succeeds.

If you add this to CI, log the failures by locale and template. A test suite can run the small fixture first to prove the check detects a broken link. Use the actual deployment URL in the release job to test what the build emitted. Keep the fixture and deployment results separately, so a failure in the server setup has a different diagnostic from a broken path on a deployed page.

For the wider deployment pipeline, Stack & Skill’s [guide to zero-downtime deployments with Docker and GitHub Actions](https://www.stackandskill.com/blog/zero-downtime-deployments-docker-github-actions) covers readiness checks, traffic switches and rollback. The resource-link check here adds a content-specific check to that release process.

The replay covers UTF-8 server-rendered HTML and a single controlled rewrite. Its generated pages have no redirects or base element. It reads an anchor pointing to an external JSON file. For inline JSON-LD or JavaScript fetch calls, select and validate the corresponding data source instead. Its observations describe the generated pages and their local HTTP responses. Sites with JavaScript-generated links, a content delivery network, or access controls need a check against the environment and client that will consume the file. The minimum useful rule stays the same. Start on the localized page, follow the link it actually emits, and inspect what comes back.

**AI assistance**  
I used Codex to help draft and edit the article and prepare the local reproduction. I ran the example locally.
