1 | # py312 |
2 | # requirements: |
3 | # pynetbox==7.9.0 |
4 |
|
5 |
|
6 | import re |
7 | from typing import Literal, Optional, TypedDict, Union |
8 | from urllib.parse import parse_qsl, urlsplit |
9 |
|
10 | import pynetbox |
11 | from pynetbox.core.query import _is_v2_token |
12 |
|
13 |
|
14 | class netbox(TypedDict): |
15 | url: str |
16 | token: str |
17 |
|
18 |
|
19 | def api(auth: netbox): |
20 | # pynetbox adds /api itself; the resource URL may already end with it. |
21 | return pynetbox.api( |
22 | auth["url"].rstrip("/").removesuffix("/api"), token=auth["token"] |
23 | ) |
24 |
|
25 |
|
26 | def main( |
27 | auth: netbox, |
28 | method: Literal["GET", "POST", "PUT", "PATCH", "DELETE"], |
29 | path: str, |
30 | query: Optional[dict] = None, |
31 | body: Optional[Union[dict, list]] = None, |
32 | ): |
33 | """ |
34 | Call NetBox API |
35 | 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). |
36 | """ |
37 | # The form's JSON editor also lets a bare string or number through. |
38 | if body not in (None, "") and not isinstance(body, (dict, list)): |
39 | raise ValueError( |
40 | f"body must be a JSON object or list, got {type(body).__name__}" |
41 | ) |
42 | if method == "GET" and body not in (None, "", [], {}): |
43 | raise ValueError("GET takes no body: use POST, PUT, PATCH or DELETE") |
44 | # Any endpoint, so this uses pynetbox's HTTP session directly. NetBox needs the trailing |
45 | # slash: without it NetBox 301s or 404s. Accepts a path relative to /api, or a full URL |
46 | # (such as a next link) under the resource's own API URL. |
47 | nb = api(auth) |
48 | if re.match(r"https?://", path, re.I): |
49 | # Same host and API path; scheme and port may differ behind a proxy. |
50 | url, base = urlsplit(path), urlsplit(nb.base_url) |
51 | if url.hostname != base.hostname or not ( |
52 | url.path == base.path or url.path.startswith(base.path + "/") |
53 | ): |
54 | raise ValueError( |
55 | f"{path} is not under this resource's API URL {nb.base_url}: pass the path relative to /api" |
56 | ) |
57 | path = url.path[len(base.path) :] + (f"?{url.query}" if url.query else "") |
58 | path, _, qs = re.sub( |
59 | r"^api(?=[/?]|$)", "", path.split("#")[0].lstrip("/") |
60 | ).partition("?") |
61 | path = path.strip("/") |
62 | if path: |
63 | path += "/" |
64 | params = { |
65 | k: [x for x in (v if isinstance(v, list) else [v]) if x not in (None, "")] |
66 | for k, v in (query or {}).items() |
67 | } |
68 | # A query string in the path (a next link's offset, say) wins over query for the same key. |
69 | from_path = {} |
70 | for k, v in parse_qsl(qs, keep_blank_values=True): |
71 | from_path.setdefault(k, []).append(v) |
72 | params |= from_path |
73 | response = nb.http_session.request( |
74 | method, |
75 | f"{nb.base_url}/{path}", |
76 | params=params, |
77 | json=body if method != "GET" and body else None, |
78 | # requests would replay a redirected write as a GET that changes nothing. |
79 | allow_redirects=method == "GET", |
80 | headers={ |
81 | # pynetbox's rule: v2 tokens (nbt_<key>.<secret>) use Bearer, v1 tokens Token. |
82 | "Authorization": f"{'Bearer' if _is_v2_token(auth['token']) else 'Token'} {auth['token']}", |
83 | "Accept": "application/json, * |
84 | }, |
85 | ) |
86 | if 300 <= response.status_code < 400: |
87 | raise Exception( |
88 | f"{response.status_code} redirected to {response.headers.get('Location')}: set the resource url to the address NetBox is served at" |
89 | ) |
90 | if not response.ok: |
91 | raise Exception(f"{response.status_code} {response.text}") |
92 | if response.status_code == 204 or not response.content: |
93 | return {"success": True} |
94 | if "json" not in response.headers.get("Content-Type", ""): |
95 | # e.g. schema/ (YAML), or a login page reached through a redirected GET. |
96 | return response.text |
97 | return response.json() |
98 | |