Add an HTTP snippet
- ID
620413e- date
2026-03-29 21:21:44+00:00- author
Alex Chan <alex@alexwlchan.net>- parent
2512002- message
Add an HTTP snippet- changed files
2 files, 33 additions, 1 deletion
Changed files
create_snippets.py (8547) → create_snippets.py (8497)
diff --git a/create_snippets.py b/create_snippets.py
index 5dfc969..029067b 100755
--- a/create_snippets.py
+++ b/create_snippets.py
@@ -256,11 +256,11 @@ SNIPPETS = {
"!dt": "from datetime import datetime, timezone\n",
"!j": "import json\n",
"!pp": "from pprint import pprint; pprint({cursor})",
- "!ssl": "ssl_context = ssl.create_default_context(cafile=certifi.where())",
"@param": "@pytest.mark.parametrize({cursor})",
"!flapi": read("flapi.py"),
+ "!http": read("http.py"),
"py!aws": read("get_boto3_session.py"),
"py!dy": read("list_dynamodb_rows.py"),
expansions/http.py (0) → expansions/http.py (893)
diff --git a/expansions/http.py b/expansions/http.py
new file mode 100644
index 0000000..2d3b1f5
--- /dev/null
+++ b/expansions/http.py
@@ -0,0 +1,32 @@
+"""
+A basic wrapper for making HTTP requests with the standard library.
+"""
+
+import ssl
+import urllib.parse
+import urllib.request
+
+import certifi
+
+
+def http_get(url: str, params: dict[str, str] | None = None, headers: dict[str, str] | None = None) -> tuple[bytes, dict[str, str]]:
+ """
+ Makes an HTTP GET request to the given URL, and returns the body
+ of the response.
+ """
+ ssl_context = ssl.create_default_context(cafile=certifi.where())
+
+ if params:
+ params_str = urllib.parse.urlencode(params)
+ url = url + "?" + params_str
+
+ ssl_context = ssl.create_default_context(cafile=certifi.where())
+
+ req = urllib.request.Request(url)
+
+ if headers:
+ for name, value in headers.items():
+ req.add_header(name, value)
+
+ with urllib.request.urlopen(req, context=ssl_context) as resp:
+ return resp.read(), resp.headers