Edits history of script submission #23917 for ' Call NetBox API (netbox)'

  • python3
    One script reply has been approved by the moderators
    Ap­pro­ved
    # py312
    # requirements:
    # pynetbox==7.9.0
    
    
    import re
    from typing import Literal, Optional, TypedDict, Union
    from urllib.parse import parse_qsl, urlsplit
    
    import pynetbox
    from pynetbox.core.query import _is_v2_token
    
    
    class netbox(TypedDict):
        url: str
        token: str
    
    
    def api(auth: netbox):
        # pynetbox adds /api itself; the resource URL may already end with it.
        return pynetbox.api(
            auth["url"].rstrip("/").removesuffix("/api"), token=auth["token"]
        )
    
    
    def main(
        auth: netbox,
        method: Literal["GET", "POST", "PUT", "PATCH", "DELETE"],
        path: str,
        query: Optional[dict] = None,
        body: Optional[Union[dict, list]] = None,
    ):
        """
        Call NetBox API
        Call any NetBox REST endpoint: path relative to /api (e.g. dcim/cables; the trailing slash is optional) or a full URL under the resource's API URL such as a next link (its query string wins over query for the same key), query params, and a JSON body (object, or a list for bulk PATCH/POST/DELETE).
        """
        # The form's JSON editor also lets a bare string or number through.
        if body not in (None, "") and not isinstance(body, (dict, list)):
            raise ValueError(
                f"body must be a JSON object or list, got {type(body).__name__}"
            )
        if method == "GET" and body not in (None, "", [], {}):
            raise ValueError("GET takes no body: use POST, PUT, PATCH or DELETE")
        # Any endpoint, so this uses pynetbox's HTTP session directly. NetBox needs the trailing
        # slash: without it NetBox 301s or 404s. Accepts a path relative to /api, or a full URL
        # (such as a next link) under the resource's own API URL.
        nb = api(auth)
        if re.match(r"https?://", path, re.I):
            # Same host and API path; scheme and port may differ behind a proxy.
            url, base = urlsplit(path), urlsplit(nb.base_url)
            if url.hostname != base.hostname or not (
                url.path == base.path or url.path.startswith(base.path + "/")
            ):
                raise ValueError(
                    f"{path} is not under this resource's API URL {nb.base_url}: pass the path relative to /api"
                )
            path = url.path[len(base.path) :] + (f"?{url.query}" if url.query else "")
        path, _, qs = re.sub(
            r"^api(?=[/?]|$)", "", path.split("#")[0].lstrip("/")
        ).partition("?")
        path = path.strip("/")
        if path:
            path += "/"
        params = {
            k: [x for x in (v if isinstance(v, list) else [v]) if x not in (None, "")]
            for k, v in (query or {}).items()
        }
        # A query string in the path (a next link's offset, say) wins over query for the same key.
        from_path = {}
        for k, v in parse_qsl(qs, keep_blank_values=True):
            from_path.setdefault(k, []).append(v)
        params |= from_path
        response = nb.http_session.request(
            method,
            f"{nb.base_url}/{path}",
            params=params,
            json=body if method != "GET" and body else None,
            # requests would replay a redirected write as a GET that changes nothing.
            allow_redirects=method == "GET",
            headers={
                # pynetbox's rule: v2 tokens (nbt_<key>.<secret>) use Bearer, v1 tokens Token.
                "Authorization": f"{'Bearer' if _is_v2_token(auth['token']) else 'Token'} {auth['token']}",
                "Accept": "application/json, */*;q=0.1",
            },
        )
        if 300 <= response.status_code < 400:
            raise Exception(
                f"{response.status_code} redirected to {response.headers.get('Location')}: set the resource url to the address NetBox is served at"
            )
        if not response.ok:
            raise Exception(f"{response.status_code} {response.text}")
        if response.status_code == 204 or not response.content:
            return {"success": True}
        if "json" not in response.headers.get("Content-Type", ""):
            # e.g. schema/ (YAML), or a login page reached through a redirected GET.
            return response.text
        return response.json()
    

    Submitted by hugo989 20 days ago

  • python3
    # py312
    # requirements:
    # pynetbox==7.9.0
    
    
    import re
    from typing import Literal, Optional, TypedDict
    
    import pynetbox
    
    
    class netbox(TypedDict):
        url: str
        token: str
    
    
    def api(auth: netbox):
        # pynetbox adds /api itself; the resource URL may already end with it.
        return pynetbox.api(
            auth["url"].rstrip("/").removesuffix("/api"), token=auth["token"]
        )
    
    
    def main(
        auth: netbox,
        method: Literal["GET", "POST", "PUT", "PATCH", "DELETE"],
        path: str,
        query: Optional[dict] = None,
        body: Optional[dict] = None,
    ):
        """
        Call NetBox API
        Call any NetBox REST endpoint: path relative to /api (e.g. dcim/cables/), query params, and a JSON body (object, or a list for bulk PATCH/POST/DELETE).
        """
        # Any endpoint, so this one uses pynetbox's HTTP session directly.
        nb = api(auth)
        params = {
            k: [x for x in (v if isinstance(v, list) else [v]) if x not in (None, "")]
            for k, v in (query or {}).items()
        }
        response = nb.http_session.request(
            method,
            f"{nb.base_url}/{re.sub(r'^/?(api/)?', '', path)}",
            params=params,
            json=body if method != "GET" and body else None,
            headers={
                "Authorization": f"{'Bearer' if auth['token'].startswith('nbt_') else 'Token'} {auth['token']}",
                "Accept": "application/json",
            },
        )
        if not response.ok:
            raise Exception(f"{response.status_code} {response.text}")
        if response.status_code == 204:
            return {"success": True}
        return response.json()
    

    Submitted by hugo989 21 days ago