Product case study · November 27, 2026

Ask Claude Code to stop URL joins dropping your API path

Reproduce a Python urljoin bug that drops /v1, give Claude Code a precise route contract, and verify the repair without sending an API request.

Reading time
7 min
Checked
Nov 27, 2026
Layered paper route segments joined by an ochre connector lead to a blue destination card on a warm paper background.
Keep the configured API path in the destination, then prove it with a string comparison.
Bottom line

Test the complete destination URL before debugging credentials or retrying a request. A missing slash can change which endpoint you call.

Your configuration says /v1. Your request goes to /models. Before replacing the API key or asking the agent to add retries, print the URL: the version segment may have disappeared before any request left your machine.

This lab gives Claude Code a small, observable bug to repair. The useful habit is deciding what a correct destination looks like before touching the HTTP client. A string comparison is cheaper to investigate than a live authentication failure.

You need Bash, Python 3, and an installed, signed-in Claude Code session. The Python baseline and reference repair below were tested locally; the agent prompt is an authored exercise, not a recorded Claude run. Sources were checked November 27, 2026. All example URLs are fixtures; no API calls are needed.

Make the path disappear

Create a disposable folder and save a deliberately incomplete helper:

url_lab=$(mktemp -d /tmp/claude-url-path.XXXXXX)
cd "$url_lab"
cat > endpoints.py <<'PY'
from urllib.parse import urljoin


def endpoint_url(base, route):
    return urljoin(base, route)


if __name__ == "__main__":
    print(endpoint_url("https://api.example.com/v1", "models"))
    print(endpoint_url("https://api.example.com/v1/", "models"))
PY
python3 endpoints.py

The baseline prints:

https://api.example.com/models
https://api.example.com/v1/models

The first join treats v1 as the final segment to replace. The second keeps it as a directory. This follows the relative-path merge rules in RFC 3986, section 5.2.3: resolving a relative path uses the base path through its final slash. The slash carries meaning; it is not decorative punctuation.

Python’s urljoin() documentation describes URL resolution, including another surprise: an absolute second argument can replace the host. A general URL resolver is doing more than an API endpoint builder needs.

Decide what counts as a route

For this exercise, the base is trusted configuration: a valid HTTPS URL with an optional path, no query or fragment, and zero or one trailing slash. We want every configured path segment preserved. The route is a narrower input: one or more slash-separated segments containing only ASCII letters, digits, underscores or hyphens.

Save this contract as SPEC.md:

endpoint_url(base, route) returns a string.
The caller supplies a trusted HTTPS base URL with no query or fragment.
Preserve the entire base path, whether its trailing slash is present or absent.
Accept route segments containing only ASCII letters, digits, _ and -.
Allow nested routes such as jobs/status. Separate segments with one slash.
Raise ValueError for every other string route, including empty strings,
leading or trailing slashes, empty segments, dot segments, full URLs,
percent escapes, spaces, query strings and fragments.
Non-string inputs and validation of the trusted base are outside this lab.
Only endpoints.py may change. Preserve its demo; add no dependencies.
Do not send network requests.

I prefer rejecting a leading slash here to silently stripping it. If one caller means “start at the host root” and another means “append to the API prefix,” forgiving both hides a disagreement. Choose a contract the callers can read.

This deliberately limited alphabet is suitable for the example’s fixed endpoint names. It is not a general URL validator or an encoder for arbitrary customer input.

Keep the destination tests fixed

Save this as test_endpoints.py:

import unittest
from endpoints import endpoint_url


class EndpointTests(unittest.TestCase):
    def test_version_prefix_with_either_base_spelling(self):
        for base in ("https://api.example.com/v1",
                     "https://api.example.com/v1/"):
            with self.subTest(base=base):
                self.assertEqual(
                    endpoint_url(base, "models"),
                    "https://api.example.com/v1/models",
                )

    def test_nested_base_and_route(self):
        self.assertEqual(
            endpoint_url("https://api.example.com/team/v2", "jobs/status"),
            "https://api.example.com/team/v2/jobs/status",
        )

    def test_host_only_base(self):
        for base in ("https://api.example.com", "https://api.example.com/"):
            with self.subTest(base=base):
                self.assertEqual(
                    endpoint_url(base, "models"),
                    "https://api.example.com/models",
                )

    def test_allowed_segment_characters(self):
        self.assertEqual(
            endpoint_url("https://api.example.com/v1/", "Jobs_2/run-3"),
            "https://api.example.com/v1/Jobs_2/run-3",
        )

    def test_invalid_routes_raise(self):
        routes = (
            "", "/models", "models/", "jobs//status", ".", "../models",
            "https://elsewhere.example/models", "//elsewhere.example/models",
            "models?limit=2", "models#top", "%2e%2e/models", "two words",
            "models\n",
        )
        for route in routes:
            with self.subTest(route=route):
                with self.assertRaises(ValueError):
                    endpoint_url("https://api.example.com/v1/", route)

Run:

python3 -m unittest -v test_endpoints

Our baseline produced 15 failures across three test methods: the missing version prefix, the nested base path, and all 13 rejected-route subcases. The host-only and allowed-character tests passed. Those passing cases matter: they prevent a repair that simply hardcodes /v1/models.

The unittest documentation covers the equality checks, expected exceptions and subtests used here. Keep these tests unchanged while the helper is repaired.

Hand Claude Code the reproduction

Start claude inside the practice folder and paste:

Read SPEC.md, endpoints.py and test_endpoints.py.
Run python3 -m unittest -v test_endpoints and report the actual failures.
Explain why the first demo loses /v1 while the second retains it.
Change only endpoints.py to satisfy the contract and unchanged tests.
Preserve the demo. Do not edit tests, install packages, access other
folders, make network requests, delegate, commit or publish.
Run the same tests and python3 endpoints.py after the edit.
Report the results and explain how invalid routes are rejected.

Anthropic’s common workflows recommends giving Claude the error, reproduction steps and expected behavior when debugging, then verifying the fix. Here, the tests supply that expected behavior before the agent starts editing.

The prompt specifies scope; it does not create a filesystem sandbox. Use the permission review described in the first project-session lesson.

If Claude changes the expected URLs to remove /v1, restore the test file. If it proposes calling a real provider to check the result, bring it back to the string-building helper. Neither credentials nor a working service can resolve an unclear path contract.

Inspect a reference repair

This implementation passed all five test methods locally. Replace the import and function, leaving the demo beneath them:

import re
from urllib.parse import urljoin


def endpoint_url(base, route):
    if re.fullmatch(r"[A-Za-z0-9_-]+(?:/[A-Za-z0-9_-]+)*", route) is None:
        raise ValueError("route must contain slash-separated endpoint names")
    return urljoin(base.rstrip("/") + "/", route)

There are two decisions in this repair. The route check enforces the exercise’s alphabet and segment shape. Normalizing the trusted base to end with one slash makes its final path segment a directory for the join. The tests describe the result, so another implementation can pass without using this exact expression.

Leave the agent session and run both commands yourself:

python3 -m unittest -v test_endpoints
python3 endpoints.py

Both demo lines should now be:

https://api.example.com/v1/models
https://api.example.com/v1/models

If imports fail, check that your terminal is in the folder containing both Python files. If the tests pass but the demo differs, inspect whether the agent changed the example inputs. Keep the original inputs so the demonstration still exercises the bug.

Know what the green tests buy you

You have verified URL construction under a specific contract. You have not tested a server, authentication, redirects or whether a provider actually offers the chosen route. Before adapting this helper, check that the real configuration has the same shape as the trusted base in the lab.

Python also cautions that its URL parsing functions do not validate every input and that joining attacker-controlled absolute URLs can change the destination. This small helper avoids accepting those route forms; it is not a complete request-security boundary.

For a real client, keep one test using its actual configured path shape and a documented endpoint name. That test is where the next accidental deletion of /v1 should show up—before someone spends an afternoon rotating a perfectly good key.

Sources

Checked November 27, 2026:

Put this to work

How a base URL's trailing slash changes relative path resolution.

Try

Ask Claude Code to repair one URL helper in a disposable practice folder.

Prove it worked

Run five unchanged test methods against the baseline and repaired helper.

Keep in view

  • Reproduce a URL join that silently removes /v1.
  • Define which route strings the helper accepts.
  • Verify complete URLs with no network calls or credentials.
Learn the workflow: Set up your first Claude Code project session