-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython.py
More file actions
54 lines (37 loc) · 1.34 KB
/
python.py
File metadata and controls
54 lines (37 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
Postali API — Python 3.6+ examples using only the stdlib.
Run with: python3 examples/python.py
"""
import json
import urllib.parse
import urllib.request
BASE = "https://postali.app/api/v1"
def _get(path: str) -> dict:
with urllib.request.urlopen(f"{BASE}{path}") as r:
return json.loads(r.read())
def _post(path: str, body: dict) -> dict:
req = urllib.request.Request(
f"{BASE}{path}",
data=json.dumps(body).encode(),
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req) as r:
return json.loads(r.read())
def lookup(country: str, cp: str) -> dict:
return _get(f"/{country}/cp/{cp}")
def validate(country: str, cp: str) -> dict:
return _get(f"/{country}/validate/{cp}")
def search(country: str, q: str, limit: int = 10) -> dict:
qs = urllib.parse.urlencode({"q": q, "limit": limit})
return _get(f"/{country}/search?{qs}")
def list_estados(country: str) -> dict:
return _get(f"/{country}/estados")
def bulk(country: str, cps: list[str]) -> dict:
return _post(f"/{country}/bulk", {"cps": cps})
if __name__ == "__main__":
print(lookup("mx", "06700"))
print(validate("co", "050001"))
print(search("es", "barcelona", limit=5))
print(list_estados("co"))
print(bulk("mx", ["06700", "44100", "00000"]))