[Python] How to download file contents from private BitBucket repository using API token

Discussão em 'Python' iniciado por Stack, Agosto 20, 2025.

  1. Stack

    Stack Membro Participativo

    So far I got this

    def _parse_bitbucket_url(value: str) -> Dict[str, str]:
    parsed_url = urlparse(value)
    if not parsed_url.scheme or "bitbucket.org" not in parsed_url.netloc:
    raise Exception("Only links to bitbucket.org are supported")

    url_path = Path(parsed_url.path)
    parts = url_path.parts
    if len(parts) < 6 or parts[3] != "src":
    raise Exception("Unsupported Bitbucket URL structure")

    workspace = parts[1]
    repo_slug = parts[2]
    commit = parts[4]
    file_path = "/".join(parts[5:])

    return {
    "workspace": workspace,
    "repo_slug": repo_slug,
    "branch": commit,
    "path": file_path
    }


    async def download_raw_file_from_bitbucket(config: RunConfigurator, url: str) -> Optional[Any]:
    BITBUCKET_API_TOKEN = KeyManager(getattr(config, 'api_keys', {})).get_key("BITBUCKET_API_TOKEN")

    parsed = _parse_bitbucket_url(url)

    api_url = (
    f"https://api.bitbucket.org/2.0/repositories/"
    f"{parsed['workspace']}/{parsed['repo_slug']}/src/"
    f"{parsed['branch']}/{parsed['path']}"
    )

    headers = {
    "Authorization": f"Bearer {BITBUCKET_API_TOKEN}",
    "Accept": "application/json"
    }

    async with aiohttp.ClientSession() as session:
    async with session.get(api_url, headers=headers, allow_redirects=True) as response:
    if not response.ok:
    raise Exception(f"{response.status} {await response.text()}")

    text = await response.text()
    try:
    return json.loads(text)
    except json.JSONDecodeError:
    return text


    But all I get is the "Token is invalid, expired, or not supported for this endpoint." error.

    I tried with this cURL request:

    curl -H "Authorization: Bearer <my token goes here>" -H "Accept: application/json" "https://api.bitbucket.org/2.0/repositories/<user>/<repo>/<folder>/<folder>/<folder>/<folder>/<file.extension>"


    And still, the same error.

    Assuming the API token was created with the right permissions, what's the error in my code?

    Continue reading...

Compartilhe esta Página