urban-json-http 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 black beard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: urban-json-http
3
+ Version: 0.1.0
4
+ Summary: Plugin urban-json : appels HTTP depuis les templates (http / httpget).
5
+ Author-email: Gael Beard <gaelgael5@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/gaelgael5/Jslt
8
+ Project-URL: Repository, https://github.com/gaelgael5/Jslt
9
+ Keywords: json,transform,template,jslt,http,rest,plugin
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: Internet :: WWW/HTTP
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: urban-json
26
+ Requires-Dist: httpx>=0.24
27
+ Dynamic: license-file
28
+
29
+ # urban-json-http
30
+
31
+ Plugin [urban-json](https://github.com/gaelgael5/Jslt) : appels **HTTP** depuis les
32
+ templates. L'appel est formalisé comme un objet **Fetch / `RequestInit`** (le
33
+ vocabulaire HTTP-en-JSON standard).
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install urban-json-http # tire urban-json et httpx
39
+ ```
40
+
41
+ `urban-json` découvre le plugin automatiquement via les entry points (`urban_json.functions`).
42
+
43
+ ## Utilisation
44
+
45
+ ```python
46
+ from urban_json import JsltTemplate
47
+
48
+ tpl = JsltTemplate.parse('''
49
+ {
50
+ "r:": http({
51
+ "method": "GET",
52
+ "url": "https://api.example.com/users",
53
+ "headers": { "Authorization": $.token },
54
+ "query": { "page": 1 }
55
+ }),
56
+ "code": r:$.status,
57
+ "users": r:$.body.items
58
+ }
59
+ ''')
60
+ tpl.transform({"token": "Bearer xyz"})
61
+ ```
62
+
63
+ - `http(request)` — `request` : `{ method, url, headers, query, body, timeout }`.
64
+ Renvoie `{ status, headers, body }` ; `body` est le JSON parsé si la réponse est
65
+ du JSON, sinon le texte.
66
+ - `httpget(url, headers)` — convenance GET renvoyant directement le `body`.
67
+
68
+ Le corps (`body`) de la requête est envoyé en **JSON** si c'est un objet ou un
69
+ tableau, sinon tel quel. Verbe par défaut : `GET`. Timeout par défaut : 30 s
70
+ (surchargeable via `"timeout"`).
71
+
72
+ ## Sécurité
73
+
74
+ `http` réalise de **vraies requêtes réseau**. Méfiez-vous des URL construites à
75
+ partir de données non fiables (SSRF). Un timeout par défaut est appliqué.
76
+
77
+ ## Licence
78
+
79
+ Apache-2.0.
@@ -0,0 +1,51 @@
1
+ # urban-json-http
2
+
3
+ Plugin [urban-json](https://github.com/gaelgael5/Jslt) : appels **HTTP** depuis les
4
+ templates. L'appel est formalisé comme un objet **Fetch / `RequestInit`** (le
5
+ vocabulaire HTTP-en-JSON standard).
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ pip install urban-json-http # tire urban-json et httpx
11
+ ```
12
+
13
+ `urban-json` découvre le plugin automatiquement via les entry points (`urban_json.functions`).
14
+
15
+ ## Utilisation
16
+
17
+ ```python
18
+ from urban_json import JsltTemplate
19
+
20
+ tpl = JsltTemplate.parse('''
21
+ {
22
+ "r:": http({
23
+ "method": "GET",
24
+ "url": "https://api.example.com/users",
25
+ "headers": { "Authorization": $.token },
26
+ "query": { "page": 1 }
27
+ }),
28
+ "code": r:$.status,
29
+ "users": r:$.body.items
30
+ }
31
+ ''')
32
+ tpl.transform({"token": "Bearer xyz"})
33
+ ```
34
+
35
+ - `http(request)` — `request` : `{ method, url, headers, query, body, timeout }`.
36
+ Renvoie `{ status, headers, body }` ; `body` est le JSON parsé si la réponse est
37
+ du JSON, sinon le texte.
38
+ - `httpget(url, headers)` — convenance GET renvoyant directement le `body`.
39
+
40
+ Le corps (`body`) de la requête est envoyé en **JSON** si c'est un objet ou un
41
+ tableau, sinon tel quel. Verbe par défaut : `GET`. Timeout par défaut : 30 s
42
+ (surchargeable via `"timeout"`).
43
+
44
+ ## Sécurité
45
+
46
+ `http` réalise de **vraies requêtes réseau**. Méfiez-vous des URL construites à
47
+ partir de données non fiables (SSRF). Un timeout par défaut est appliqué.
48
+
49
+ ## Licence
50
+
51
+ Apache-2.0.
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "urban-json-http"
7
+ dynamic = ["version"]
8
+ description = "Plugin urban-json : appels HTTP depuis les templates (http / httpget)."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Gael Beard", email = "gaelgael5@gmail.com" }]
14
+ keywords = ["json", "transform", "template", "jslt", "http", "rest", "plugin"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Software Development :: Libraries :: Python Modules",
26
+ "Topic :: Internet :: WWW/HTTP",
27
+ "Typing :: Typed",
28
+ ]
29
+ dependencies = [
30
+ "urban-json",
31
+ "httpx>=0.24",
32
+ ]
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/gaelgael5/Jslt"
36
+ Repository = "https://github.com/gaelgael5/Jslt"
37
+
38
+ # Découverte automatique par urban-json : installer ce paquet suffit à exposer http/httpget.
39
+ [project.entry-points."urban_json.functions"]
40
+ http = "urban_json_http:register"
41
+
42
+ [tool.setuptools.dynamic]
43
+ version = { attr = "urban_json_http.__version__" }
44
+
45
+ [tool.setuptools.packages.find]
46
+ where = ["src"]
47
+
48
+ [tool.setuptools.package-data]
49
+ urban_json_http = ["py.typed"]
50
+
51
+ [tool.pytest.ini_options]
52
+ testpaths = ["tests"]
53
+ pythonpath = ["src"]
54
+
55
+ [tool.ruff]
56
+ line-length = 100
57
+ src = ["src", "tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,110 @@
1
+ """Plugin jslt : appels HTTP depuis les templates (``http`` / ``httpget``).
2
+
3
+ Le moteur .NET n'offre qu'un GET minimal (``loadhttpgetJson``). Ce plugin le
4
+ remplace par une formalisation **déclarative** de l'appel, suivant la convention
5
+ Fetch / ``RequestInit`` (le vocabulaire HTTP-en-JSON standard) :
6
+
7
+ * ``http(request)`` — ``request`` est un objet
8
+ ``{method, url, headers, query, body, timeout}`` ; renvoie un objet réponse
9
+ ``{status, headers, body}`` (``body`` = JSON parsé si la réponse est du JSON,
10
+ sinon le texte brut).
11
+ * ``httpget(url, headers)`` — convenance GET renvoyant directement le ``body``.
12
+
13
+ Client HTTP : `httpx`. Le corps (``body``) est envoyé en JSON si c'est un objet ou
14
+ un tableau, sinon tel quel.
15
+
16
+ Sécurité : ``http`` réalise de **vraies requêtes réseau** vers l'URL fournie.
17
+ Attention aux URL issues de données non fiables (SSRF). Un ``timeout`` par défaut
18
+ (30 s) est appliqué et surchargeable par requête.
19
+
20
+ Découvert automatiquement par ``jslt`` via l'entry point ``urban_json.functions``.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from typing import Any
26
+
27
+ import httpx
28
+
29
+ __version__ = "0.1.0"
30
+
31
+ __all__ = ["execute_http", "execute_httpget", "register"]
32
+
33
+ #: Timeout par défaut (secondes) si la requête n'en précise pas.
34
+ DEFAULT_TIMEOUT = 30.0
35
+
36
+
37
+ def _build_client(timeout: float) -> httpx.Client:
38
+ """Fabrique le client HTTP. Point d'injection pour les tests (transport mocké)."""
39
+ return httpx.Client(timeout=timeout)
40
+
41
+
42
+ def _parse_body(response: httpx.Response) -> Any:
43
+ """Corps de réponse : JSON parsé si le content-type est JSON, sinon texte."""
44
+ content_type = response.headers.get("content-type", "")
45
+ if "json" in content_type.lower():
46
+ try:
47
+ return response.json()
48
+ except ValueError:
49
+ return response.text
50
+ return response.text
51
+
52
+
53
+ def execute_http(ctx: Any, request: Any = None) -> dict:
54
+ """Effectue un appel HTTP décrit par un objet Fetch/``RequestInit``.
55
+
56
+ Args:
57
+ request: objet ``{method, url, headers, query, body, timeout}``.
58
+ ``method`` défaut ``GET`` ; ``headers``/``query`` sont des objets ;
59
+ ``body`` est envoyé en JSON si objet/tableau, sinon tel quel.
60
+
61
+ Returns:
62
+ ``{"status": int, "headers": {...}, "body": <json|texte>}``.
63
+ """
64
+ if not isinstance(request, dict):
65
+ # ValueError (et non TypeError) : contrat « mauvais argument » uniforme.
66
+ raise ValueError("http: request doit être un objet {method, url, ...}") # noqa: TRY004
67
+ url = request.get("url")
68
+ if not url:
69
+ raise ValueError("http: 'url' est requis")
70
+
71
+ method = str(request.get("method") or "GET").upper()
72
+ headers = {str(k): str(v) for k, v in (request.get("headers") or {}).items()}
73
+ params = request.get("query") or {}
74
+ body = request.get("body")
75
+ timeout = request.get("timeout", DEFAULT_TIMEOUT)
76
+
77
+ kwargs: dict[str, Any] = {"headers": headers, "params": params}
78
+ if isinstance(body, (dict, list)):
79
+ kwargs["json"] = body
80
+ elif body is not None:
81
+ kwargs["content"] = body if isinstance(body, (str, bytes)) else str(body)
82
+
83
+ with _build_client(timeout) as client:
84
+ response = client.request(method, url, **kwargs)
85
+
86
+ return {
87
+ "status": response.status_code,
88
+ "headers": dict(response.headers),
89
+ "body": _parse_body(response),
90
+ }
91
+
92
+
93
+ def execute_httpget(ctx: Any, url: str | None = None, headers: Any = None) -> Any:
94
+ """GET de convenance : renvoie directement le corps (port « amélioré » du .NET)."""
95
+ response = execute_http(ctx, {"method": "GET", "url": url, "headers": headers or {}})
96
+ return response["body"]
97
+
98
+
99
+ def register(registry: Any) -> None:
100
+ """Enregistre les fonctions du plugin dans un registre jslt (entry point)."""
101
+ registry.register(
102
+ "http",
103
+ execute_http,
104
+ description="Appel HTTP (objet Fetch {method,url,headers,query,body}) -> {status,headers,body}.",
105
+ )
106
+ registry.register(
107
+ "httpget",
108
+ execute_httpget,
109
+ description="GET HTTP renvoyant directement le corps (JSON parsé ou texte).",
110
+ )
File without changes
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: urban-json-http
3
+ Version: 0.1.0
4
+ Summary: Plugin urban-json : appels HTTP depuis les templates (http / httpget).
5
+ Author-email: Gael Beard <gaelgael5@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/gaelgael5/Jslt
8
+ Project-URL: Repository, https://github.com/gaelgael5/Jslt
9
+ Keywords: json,transform,template,jslt,http,rest,plugin
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: Internet :: WWW/HTTP
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: urban-json
26
+ Requires-Dist: httpx>=0.24
27
+ Dynamic: license-file
28
+
29
+ # urban-json-http
30
+
31
+ Plugin [urban-json](https://github.com/gaelgael5/Jslt) : appels **HTTP** depuis les
32
+ templates. L'appel est formalisé comme un objet **Fetch / `RequestInit`** (le
33
+ vocabulaire HTTP-en-JSON standard).
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install urban-json-http # tire urban-json et httpx
39
+ ```
40
+
41
+ `urban-json` découvre le plugin automatiquement via les entry points (`urban_json.functions`).
42
+
43
+ ## Utilisation
44
+
45
+ ```python
46
+ from urban_json import JsltTemplate
47
+
48
+ tpl = JsltTemplate.parse('''
49
+ {
50
+ "r:": http({
51
+ "method": "GET",
52
+ "url": "https://api.example.com/users",
53
+ "headers": { "Authorization": $.token },
54
+ "query": { "page": 1 }
55
+ }),
56
+ "code": r:$.status,
57
+ "users": r:$.body.items
58
+ }
59
+ ''')
60
+ tpl.transform({"token": "Bearer xyz"})
61
+ ```
62
+
63
+ - `http(request)` — `request` : `{ method, url, headers, query, body, timeout }`.
64
+ Renvoie `{ status, headers, body }` ; `body` est le JSON parsé si la réponse est
65
+ du JSON, sinon le texte.
66
+ - `httpget(url, headers)` — convenance GET renvoyant directement le `body`.
67
+
68
+ Le corps (`body`) de la requête est envoyé en **JSON** si c'est un objet ou un
69
+ tableau, sinon tel quel. Verbe par défaut : `GET`. Timeout par défaut : 30 s
70
+ (surchargeable via `"timeout"`).
71
+
72
+ ## Sécurité
73
+
74
+ `http` réalise de **vraies requêtes réseau**. Méfiez-vous des URL construites à
75
+ partir de données non fiables (SSRF). Un timeout par défaut est appliqué.
76
+
77
+ ## Licence
78
+
79
+ Apache-2.0.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/urban_json_http/__init__.py
5
+ src/urban_json_http/py.typed
6
+ src/urban_json_http.egg-info/PKG-INFO
7
+ src/urban_json_http.egg-info/SOURCES.txt
8
+ src/urban_json_http.egg-info/dependency_links.txt
9
+ src/urban_json_http.egg-info/entry_points.txt
10
+ src/urban_json_http.egg-info/requires.txt
11
+ src/urban_json_http.egg-info/top_level.txt
12
+ tests/test_http.py
@@ -0,0 +1,2 @@
1
+ [urban_json.functions]
2
+ http = urban_json_http:register
@@ -0,0 +1,2 @@
1
+ urban-json
2
+ httpx>=0.24
@@ -0,0 +1 @@
1
+ urban_json_http
@@ -0,0 +1,115 @@
1
+ """Tests du plugin urban-json-http (``http`` / ``httpget``).
2
+
3
+ Aucune requête réseau réelle : on injecte un ``httpx.MockTransport`` via le point
4
+ d'injection ``_build_client``. Couvre : GET/POST, en-têtes, query, corps JSON,
5
+ réponse texte, convenance httpget, erreurs, découverte entry point, template.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+
12
+ import httpx
13
+ import pytest
14
+ from urban_json import FunctionRegistry, JsltTemplate
15
+
16
+ import urban_json_http
17
+ from urban_json_http import execute_http, execute_httpget, register
18
+
19
+
20
+ @pytest.fixture
21
+ def mock_http(monkeypatch):
22
+ """Installe un transport mocké ; renvoie la liste des requêtes capturées."""
23
+ captured = []
24
+
25
+ def handler(request: httpx.Request) -> httpx.Response:
26
+ captured.append(request)
27
+ if request.url.path == "/text":
28
+ return httpx.Response(200, text="plain", headers={"content-type": "text/plain"})
29
+ if request.url.path == "/boom":
30
+ return httpx.Response(500, json={"error": "nope"})
31
+ return httpx.Response(
32
+ 200,
33
+ json={"ok": True, "path": request.url.path},
34
+ headers={"x-demo": "1"},
35
+ )
36
+
37
+ transport = httpx.MockTransport(handler)
38
+ monkeypatch.setattr(
39
+ urban_json_http, "_build_client", lambda timeout: httpx.Client(transport=transport, timeout=timeout)
40
+ )
41
+ return captured
42
+
43
+
44
+ def test_get_returns_structured_response(mock_http) -> None:
45
+ r = execute_http(None, {"method": "GET", "url": "https://api/x"})
46
+ assert r["status"] == 200
47
+ assert r["body"] == {"ok": True, "path": "/x"}
48
+ assert r["headers"]["x-demo"] == "1"
49
+
50
+
51
+ def test_default_method_is_get(mock_http) -> None:
52
+ execute_http(None, {"url": "https://api/x"})
53
+ assert mock_http[0].method == "GET"
54
+
55
+
56
+ def test_headers_and_query_are_sent(mock_http) -> None:
57
+ execute_http(
58
+ None,
59
+ {"url": "https://api/x", "headers": {"Authorization": "Bearer z"}, "query": {"page": 1}},
60
+ )
61
+ req = mock_http[0]
62
+ assert req.headers["authorization"] == "Bearer z"
63
+ assert req.url.params.get("page") == "1"
64
+
65
+
66
+ def test_post_sends_json_body(mock_http) -> None:
67
+ execute_http(None, {"method": "POST", "url": "https://api/x", "body": {"a": 1}})
68
+ req = mock_http[0]
69
+ assert req.method == "POST"
70
+ assert json.loads(req.content) == {"a": 1}
71
+ assert "application/json" in req.headers["content-type"]
72
+
73
+
74
+ def test_text_response_body(mock_http) -> None:
75
+ r = execute_http(None, {"url": "https://api/text"})
76
+ assert r["body"] == "plain"
77
+
78
+
79
+ def test_httpget_returns_body(mock_http) -> None:
80
+ body = execute_httpget(None, "https://api/users")
81
+ assert body == {"ok": True, "path": "/users"}
82
+
83
+
84
+ def test_error_status_still_returned(mock_http) -> None:
85
+ r = execute_http(None, {"url": "https://api/boom"})
86
+ assert r["status"] == 500
87
+ assert r["body"] == {"error": "nope"}
88
+
89
+
90
+ def test_request_must_be_object() -> None:
91
+ with pytest.raises(ValueError, match="objet"):
92
+ execute_http(None, "not-an-object")
93
+
94
+
95
+ def test_url_required() -> None:
96
+ with pytest.raises(ValueError, match="url"):
97
+ execute_http(None, {"method": "GET"})
98
+
99
+
100
+ def test_register_into_custom_registry() -> None:
101
+ reg = FunctionRegistry()
102
+ register(reg)
103
+ assert "http" in reg and "httpget" in reg
104
+
105
+
106
+ def test_discovered_via_entry_point() -> None:
107
+ from urban_json import default_registry, load_plugins
108
+
109
+ load_plugins(default_registry)
110
+ assert "http" in default_registry and "httpget" in default_registry
111
+
112
+
113
+ def test_in_template(mock_http) -> None:
114
+ template = '{ "r:": http({ "url": "https://api/items" }), "code": r:$.status, "ok": r:$.body.ok }'
115
+ assert JsltTemplate.parse(template).transform({}) == {"code": 200, "ok": True}