mapricot 0.1.0__py3-none-any.whl
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.
- mapricot/__init__.py +252 -0
- mapricot/py.typed +0 -0
- mapricot-0.1.0.dist-info/METADATA +94 -0
- mapricot-0.1.0.dist-info/RECORD +6 -0
- mapricot-0.1.0.dist-info/WHEEL +4 -0
- mapricot-0.1.0.dist-info/licenses/LICENSE +21 -0
mapricot/__init__.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""Official client for the Mapricot API: geocoding, places, routing, and IP geolocation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import time
|
|
8
|
+
import urllib.error
|
|
9
|
+
import urllib.parse
|
|
10
|
+
import urllib.request
|
|
11
|
+
from typing import Any, Literal, NotRequired, Sequence, TypedDict
|
|
12
|
+
|
|
13
|
+
__version__ = "0.1.0"
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Account",
|
|
17
|
+
"Address",
|
|
18
|
+
"Attribution",
|
|
19
|
+
"IpLocation",
|
|
20
|
+
"Leg",
|
|
21
|
+
"Mapricot",
|
|
22
|
+
"MapricotError",
|
|
23
|
+
"Place",
|
|
24
|
+
"PlaceResult",
|
|
25
|
+
"Places",
|
|
26
|
+
"Point",
|
|
27
|
+
"Route",
|
|
28
|
+
"Routes",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Point(TypedDict):
|
|
33
|
+
lat: float
|
|
34
|
+
lon: float
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Attribution(TypedDict):
|
|
38
|
+
source: str
|
|
39
|
+
text: str
|
|
40
|
+
url: str
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Address(TypedDict, total=False):
|
|
44
|
+
houseNumber: str
|
|
45
|
+
street: str
|
|
46
|
+
postalCode: str
|
|
47
|
+
locality: str
|
|
48
|
+
region: str
|
|
49
|
+
regionCode: str
|
|
50
|
+
country: str
|
|
51
|
+
countryCode: str
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Place(TypedDict):
|
|
55
|
+
id: str
|
|
56
|
+
type: str
|
|
57
|
+
name: str
|
|
58
|
+
label: str
|
|
59
|
+
lat: float
|
|
60
|
+
lon: float
|
|
61
|
+
address: NotRequired[Address]
|
|
62
|
+
categories: NotRequired[list[str]]
|
|
63
|
+
distanceMeters: NotRequired[int]
|
|
64
|
+
source: str
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Places(TypedDict):
|
|
68
|
+
results: list[Place]
|
|
69
|
+
attribution: list[Attribution]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class PlaceResult(TypedDict):
|
|
73
|
+
result: Place
|
|
74
|
+
attribution: list[Attribution]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class Leg(TypedDict):
|
|
78
|
+
distanceMeters: int
|
|
79
|
+
durationSeconds: int
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Route(TypedDict):
|
|
83
|
+
distanceMeters: int
|
|
84
|
+
durationSeconds: int
|
|
85
|
+
polyline: str
|
|
86
|
+
"""Encoded polyline with six decimal places of precision."""
|
|
87
|
+
legs: list[Leg]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Routes(TypedDict):
|
|
91
|
+
routes: list[Route]
|
|
92
|
+
attribution: NotRequired[list[Attribution]]
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class IpLocation(TypedDict):
|
|
96
|
+
ip: str
|
|
97
|
+
found: bool
|
|
98
|
+
continentCode: NotRequired[str]
|
|
99
|
+
countryCode: NotRequired[str]
|
|
100
|
+
countryName: NotRequired[str]
|
|
101
|
+
regionCode: NotRequired[str]
|
|
102
|
+
regionName: NotRequired[str]
|
|
103
|
+
city: NotRequired[str]
|
|
104
|
+
location: NotRequired[Point]
|
|
105
|
+
source: str
|
|
106
|
+
attributionUrl: str
|
|
107
|
+
licenseUrl: str
|
|
108
|
+
datasetRelease: str
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class Account(TypedDict):
|
|
112
|
+
id: str
|
|
113
|
+
name: str
|
|
114
|
+
status: str
|
|
115
|
+
created_at: str
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
class MapricotError(Exception):
|
|
119
|
+
"""An error response from the API, with its HTTP status, error code, and request ID."""
|
|
120
|
+
|
|
121
|
+
def __init__(self, status: int, code: str, message: str, request_id: str | None):
|
|
122
|
+
super().__init__(message)
|
|
123
|
+
self.status = status
|
|
124
|
+
self.code = code
|
|
125
|
+
self.message = message
|
|
126
|
+
self.request_id = request_id
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Mapricot:
|
|
130
|
+
"""A client for https://api.mapricot.com. The key defaults to the MAPRICOT_KEY environment variable."""
|
|
131
|
+
|
|
132
|
+
def __init__(
|
|
133
|
+
self,
|
|
134
|
+
api_key: str | None = None,
|
|
135
|
+
*,
|
|
136
|
+
base_url: str = "https://api.mapricot.com",
|
|
137
|
+
timeout: float = 30,
|
|
138
|
+
max_retries: int = 2,
|
|
139
|
+
):
|
|
140
|
+
api_key = api_key or os.environ.get("MAPRICOT_KEY")
|
|
141
|
+
if not api_key:
|
|
142
|
+
raise ValueError("Pass api_key or set MAPRICOT_KEY.")
|
|
143
|
+
self._api_key = api_key
|
|
144
|
+
self._base_url = base_url
|
|
145
|
+
self._timeout = timeout
|
|
146
|
+
self._max_retries = max_retries
|
|
147
|
+
|
|
148
|
+
def search(
|
|
149
|
+
self,
|
|
150
|
+
q: str,
|
|
151
|
+
*,
|
|
152
|
+
focus: Point | None = None,
|
|
153
|
+
country: str | Sequence[str] | None = None,
|
|
154
|
+
limit: int | None = None,
|
|
155
|
+
lang: str | None = None,
|
|
156
|
+
) -> Places:
|
|
157
|
+
"""Find addresses and places matching free text."""
|
|
158
|
+
return self._request("GET", "/v1/search", q=q, focus=focus, country=country, limit=limit, lang=lang)
|
|
159
|
+
|
|
160
|
+
def autocomplete(
|
|
161
|
+
self,
|
|
162
|
+
q: str,
|
|
163
|
+
*,
|
|
164
|
+
focus: Point | None = None,
|
|
165
|
+
country: str | Sequence[str] | None = None,
|
|
166
|
+
limit: int | None = None,
|
|
167
|
+
lang: str | None = None,
|
|
168
|
+
) -> Places:
|
|
169
|
+
"""Suggest addresses and places as someone types."""
|
|
170
|
+
return self._request("GET", "/v1/autocomplete", q=q, focus=focus, country=country, limit=limit, lang=lang)
|
|
171
|
+
|
|
172
|
+
def reverse(self, lat: float, lon: float, *, limit: int | None = None, lang: str | None = None) -> Places:
|
|
173
|
+
"""Find the address nearest a coordinate, or the area around it."""
|
|
174
|
+
return self._request("GET", "/v1/reverse", lat=lat, lon=lon, limit=limit, lang=lang)
|
|
175
|
+
|
|
176
|
+
def nearby(
|
|
177
|
+
self,
|
|
178
|
+
lat: float,
|
|
179
|
+
lon: float,
|
|
180
|
+
*,
|
|
181
|
+
category: str | Sequence[str] | None = None,
|
|
182
|
+
radius: int | None = None,
|
|
183
|
+
limit: int | None = None,
|
|
184
|
+
lang: str | None = None,
|
|
185
|
+
) -> Places:
|
|
186
|
+
"""List places around a coordinate, optionally by category."""
|
|
187
|
+
return self._request(
|
|
188
|
+
"GET", "/v1/nearby", lat=lat, lon=lon, category=category, radius=radius, limit=limit, lang=lang
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
def place(self, id: str, *, lang: str | None = None) -> PlaceResult:
|
|
192
|
+
"""Look up one place by its Mapricot ID."""
|
|
193
|
+
return self._request("GET", f"/v1/places/{urllib.parse.quote(id, safe='')}", lang=lang)
|
|
194
|
+
|
|
195
|
+
def route(self, waypoints: Sequence[Point], *, mode: Literal["drive", "walk", "bicycle"] | None = None) -> Routes:
|
|
196
|
+
"""Find a route through 2 to 20 waypoints."""
|
|
197
|
+
body: dict[str, Any] = {"waypoints": list(waypoints)}
|
|
198
|
+
if mode:
|
|
199
|
+
body["mode"] = mode
|
|
200
|
+
return self._request("POST", "/v1/route", body=body)
|
|
201
|
+
|
|
202
|
+
def ip(self, address: str) -> IpLocation:
|
|
203
|
+
"""Approximate location of a public IP address."""
|
|
204
|
+
return self._request("GET", f"/v1/ip/{urllib.parse.quote(address, safe='')}")
|
|
205
|
+
|
|
206
|
+
def account(self) -> Account:
|
|
207
|
+
"""The key's account. Not billed, so it checks a key for free."""
|
|
208
|
+
return self._request("GET", "/v1/account")
|
|
209
|
+
|
|
210
|
+
def _request(self, method: str, path: str, body: dict[str, Any] | None = None, **params: Any) -> Any:
|
|
211
|
+
query = urllib.parse.urlencode({name: _format(value) for name, value in params.items() if value is not None})
|
|
212
|
+
url = self._base_url + path + (f"?{query}" if query else "")
|
|
213
|
+
headers = {"Authorization": f"Bearer {self._api_key}", "User-Agent": f"mapricot-python/{__version__}"}
|
|
214
|
+
data = None
|
|
215
|
+
if body is not None:
|
|
216
|
+
headers["Content-Type"] = "application/json"
|
|
217
|
+
data = json.dumps(body).encode()
|
|
218
|
+
|
|
219
|
+
attempt = 0
|
|
220
|
+
while True:
|
|
221
|
+
request = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
222
|
+
try:
|
|
223
|
+
with urllib.request.urlopen(request, timeout=self._timeout) as response:
|
|
224
|
+
return json.load(response)
|
|
225
|
+
except urllib.error.HTTPError as response:
|
|
226
|
+
with response:
|
|
227
|
+
error = _error_from(response)
|
|
228
|
+
if attempt >= self._max_retries or not _retryable(error):
|
|
229
|
+
raise error
|
|
230
|
+
time.sleep(0.5 * 2**attempt)
|
|
231
|
+
attempt += 1
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _format(value: Any) -> str:
|
|
235
|
+
if isinstance(value, dict):
|
|
236
|
+
return f"{value['lat']},{value['lon']}"
|
|
237
|
+
if isinstance(value, (list, tuple)):
|
|
238
|
+
return ",".join(value)
|
|
239
|
+
return str(value)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _error_from(response: urllib.error.HTTPError) -> MapricotError:
|
|
243
|
+
request_id = response.headers.get("X-Request-Id")
|
|
244
|
+
try:
|
|
245
|
+
error = json.load(response)["error"]
|
|
246
|
+
return MapricotError(response.code, error["code"], error["message"], request_id)
|
|
247
|
+
except (ValueError, KeyError, TypeError):
|
|
248
|
+
return MapricotError(response.code, "unknown", f"HTTP {response.code}", request_id)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _retryable(error: MapricotError) -> bool:
|
|
252
|
+
return error.status == 503 or error.code == "concurrency_exceeded"
|
mapricot/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mapricot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official client for the Mapricot API: geocoding, places, routing, and IP geolocation.
|
|
5
|
+
Project-URL: Homepage, https://mapricot.com/
|
|
6
|
+
Project-URL: Documentation, https://mapricot.com/docs/python/
|
|
7
|
+
Project-URL: Source, https://github.com/mapricothq/mapricot/tree/main/sdks/python
|
|
8
|
+
Project-URL: Issues, https://github.com/mapricothq/mapricot/issues
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: geocoding,ip-geolocation,maps,places,routing
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Typing :: Typed
|
|
14
|
+
Requires-Python: >=3.11
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# Mapricot for Python
|
|
18
|
+
|
|
19
|
+
The official Python client for the [Mapricot API](https://mapricot.com/): address and place search, reverse geocoding, nearby places, routing, and IP geolocation, with 250,000 free requests every month.
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
pip install mapricot
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
It needs Python 3.11 or later and has no dependencies.
|
|
26
|
+
|
|
27
|
+
## Quick start
|
|
28
|
+
|
|
29
|
+
Create a server key in the [dashboard](https://app.mapricot.com/) and set it as `MAPRICOT_KEY`:
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
export MAPRICOT_KEY="mapricot_sk_…"
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from mapricot import Mapricot
|
|
37
|
+
|
|
38
|
+
client = Mapricot()
|
|
39
|
+
|
|
40
|
+
data = client.search("128 SW 3rd Ave, Portland", limit=1)
|
|
41
|
+
place = data["results"][0]
|
|
42
|
+
print(place["label"], place["lat"], place["lon"])
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Pass the key yourself with `Mapricot("mapricot_sk_…")`.
|
|
46
|
+
|
|
47
|
+
## Methods
|
|
48
|
+
|
|
49
|
+
Each method returns the API's JSON as a typed dict, with the same field names as the [API reference](https://mapricot.com/api-reference/).
|
|
50
|
+
|
|
51
|
+
| Method | Endpoint |
|
|
52
|
+
| --- | --- |
|
|
53
|
+
| `client.search(q, focus=, country=, limit=, lang=)` | [`GET /v1/search`](https://mapricot.com/docs/geocoding/#find-an-address) |
|
|
54
|
+
| `client.autocomplete(q, focus=, country=, limit=, lang=)` | [`GET /v1/autocomplete`](https://mapricot.com/docs/places/#suggest-as-people-type) |
|
|
55
|
+
| `client.reverse(lat, lon, limit=, lang=)` | [`GET /v1/reverse`](https://mapricot.com/docs/geocoding/#find-the-address-at-a-point) |
|
|
56
|
+
| `client.nearby(lat, lon, category=, radius=, limit=, lang=)` | [`GET /v1/nearby`](https://mapricot.com/docs/places/#list-places-around-a-point) |
|
|
57
|
+
| `client.place(id, lang=)` | [`GET /v1/places/{id}`](https://mapricot.com/docs/places/#look-up-a-saved-place) |
|
|
58
|
+
| `client.route(waypoints, mode=)` | [`POST /v1/route`](https://mapricot.com/docs/routing/#get-a-route) |
|
|
59
|
+
| `client.ip(address)` | [`GET /v1/ip/{ip}`](https://mapricot.com/docs/ip-geolocation/#look-up-an-address) |
|
|
60
|
+
| `client.account()` | `GET /v1/account`, which checks a key and is never billed |
|
|
61
|
+
|
|
62
|
+
`focus` and each waypoint are `{"lat": …, "lon": …}`. `country` and `category` take a list or a comma-separated string.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
nearby = client.nearby(45.52, -122.68, category=["food:coffee_shop"], radius=1000)
|
|
66
|
+
route = client.route([{"lat": 45.5189, "lon": -122.6793}, {"lat": 45.5214, "lon": -122.6828}], mode="walk")
|
|
67
|
+
print(route["routes"][0]["durationSeconds"])
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
A route's `polyline` is encoded with six decimal places. Decode it with precision 6, as [decoding a route polyline](https://mapricot.com/docs/polyline/) shows.
|
|
71
|
+
|
|
72
|
+
If your app shows results, show the credits in each response's `attribution`.
|
|
73
|
+
|
|
74
|
+
## Errors and retries
|
|
75
|
+
|
|
76
|
+
An error response raises `MapricotError`, with the HTTP `status`, the API's error `code`, a `message`, and the `request_id`:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from mapricot import MapricotError
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
client.search("")
|
|
83
|
+
except MapricotError as error:
|
|
84
|
+
print(error.status, error.code, error.message) # 400 invalid_request The service rejected the request.
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
The client retries `503` responses and `429 concurrency_exceeded`, up to twice, waiting longer each time. Errors aren't billed. Set `max_retries=` and `timeout=` (seconds) on `Mapricot(...)` to change this. The [API reference](https://mapricot.com/api-reference/#errors) lists every status.
|
|
88
|
+
|
|
89
|
+
## Links
|
|
90
|
+
|
|
91
|
+
- [Mapricot](https://mapricot.com/)
|
|
92
|
+
- [Python docs](https://mapricot.com/docs/python/)
|
|
93
|
+
- [API reference](https://mapricot.com/api-reference/)
|
|
94
|
+
- [Pricing](https://mapricot.com/pricing/)
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
mapricot/__init__.py,sha256=eodNIKM-Nr8UEncDvSuPBQUfe-QPU9YSDBpcZ8dnBPo,7414
|
|
2
|
+
mapricot/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
mapricot-0.1.0.dist-info/METADATA,sha256=5PiBMtkEQhuD_H-H2FtWzukPNOytxbw4_pwlJEs-u2k,4012
|
|
4
|
+
mapricot-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
5
|
+
mapricot-0.1.0.dist-info/licenses/LICENSE,sha256=XUUyLYEmz15umsXVNEkVcw3d91W2_Rku0WVCnv80YFQ,1065
|
|
6
|
+
mapricot-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mapricot
|
|
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.
|