def convert_namespaces_ast(
    ast,
    api_url: str = None,
    namespace_targets: Mapping[str, List[str]] = None,
    canonicalize: bool = False,
    decanonicalize: bool = False,
):
    """Recursively convert namespaces of BEL Entities in BEL AST using API endpoint

    Canonicalization and decanonicalization is determined by endpoint used and namespace_targets.

    Args:
        ast (BEL): BEL AST
        api_url (str): endpoint url with a placeholder for the term_id (either /terms/<term_id>/canonicalized or /terms/<term_id>/decanonicalized)
        namespace_targets (Mapping[str, List[str]]): (de)canonical targets for converting BEL Entities

    Returns:
        BEL: BEL AST
    """

    if isinstance(ast, NSArg):
        given_term_id = "{}:{}".format(ast.namespace, ast.value)

        # Get normalized term if necessary
        if (canonicalize and not ast.canonical) or (
            decanonicalize and not ast.decanonical
        ):
            normalized_term = convert_nsarg(
                given_term_id,
                api_url=api_url,
                namespace_targets=namespace_targets,
                canonicalize=canonicalize,
                decanonicalize=decanonicalize,
            )
            if canonicalize:
                ast.canonical = normalized_term
            elif decanonicalize:
                ast.decanonical = normalized_term

        # Update normalized term
        if canonicalize:
            ns, value = ast.canonical.split(":")
            ast.change_nsvalue(ns, value)
        elif decanonicalize:
            ns, value = ast.canonical.split(":")
            ast.change_nsvalue(ns, value)

    # Recursively process every NSArg by processing BELAst and Functions
    if hasattr(ast, "args"):
        for arg in ast.args:
            convert_namespaces_ast(
                arg,
                api_url=api_url,
                namespace_targets=namespace_targets,
                canonicalize=canonicalize,
                decanonicalize=decanonicalize,
            )

    return ast
Recursively convert namespaces of BEL Entities in BEL AST using API endpoint

    Canonicalization and decanonicalization is determined by endpoint used and namespace_targets.

    Args:
        ast (BEL): BEL AST
        api_url (str): endpoint url with a placeholder for the term_id (either /terms/<term_id>/canonicalized or /terms/<term_id>/decanonicalized)
        namespace_targets (Mapping[str, List[str]]): (de)canonical targets for converting BEL Entities

    Returns:
        BEL: BEL AST