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
    
    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 3 hours ago