mapricot 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.
- mapricot-0.1.0/.github/workflows/ci.yml +37 -0
- mapricot-0.1.0/.github/workflows/release.yml +26 -0
- mapricot-0.1.0/.gitignore +2 -0
- mapricot-0.1.0/LICENSE +21 -0
- mapricot-0.1.0/PKG-INFO +94 -0
- mapricot-0.1.0/README.md +78 -0
- mapricot-0.1.0/RELEASING.md +15 -0
- mapricot-0.1.0/pyproject.toml +23 -0
- mapricot-0.1.0/src/mapricot/__init__.py +252 -0
- mapricot-0.1.0/src/mapricot/py.typed +0 -0
- mapricot-0.1.0/tests/test_live.py +60 -0
- mapricot-0.1.0/tests/test_retry.py +48 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
name: CI
|
|
2
|
+
# Tests against the live API on every push and pull request, and weekly to catch API changes.
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
schedule:
|
|
8
|
+
- cron: '17 6 * * 1'
|
|
9
|
+
workflow_dispatch:
|
|
10
|
+
permissions:
|
|
11
|
+
contents: read
|
|
12
|
+
jobs:
|
|
13
|
+
test:
|
|
14
|
+
runs-on: ubuntu-latest
|
|
15
|
+
timeout-minutes: 10
|
|
16
|
+
strategy:
|
|
17
|
+
matrix:
|
|
18
|
+
python: ['3.11', '3.14']
|
|
19
|
+
steps:
|
|
20
|
+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
|
21
|
+
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
|
22
|
+
with:
|
|
23
|
+
python-version: ${{ matrix.python }}
|
|
24
|
+
- run: python -m unittest discover -s tests -v
|
|
25
|
+
env:
|
|
26
|
+
PYTHONPATH: src
|
|
27
|
+
MAPRICOT_KEY: ${{ secrets.MAPRICOT_KEY }}
|
|
28
|
+
endpoints:
|
|
29
|
+
# Fails when the API gains an endpoint that this client has no method for.
|
|
30
|
+
runs-on: ubuntu-latest
|
|
31
|
+
timeout-minutes: 5
|
|
32
|
+
steps:
|
|
33
|
+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
|
34
|
+
- run: |
|
|
35
|
+
curl -fsS https://api.mapricot.com/openapi.json | jq -r '.paths | keys[] | sub("\\{.*"; "")' | while read -r path; do
|
|
36
|
+
grep -rqF "$path" src || { echo "::error::No method for $path"; exit 1; }
|
|
37
|
+
done
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
name: Release
|
|
2
|
+
# Publishes the version in a GitHub release's tag, such as v0.1.0, after the live tests pass.
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
permissions:
|
|
7
|
+
contents: read
|
|
8
|
+
id-token: write
|
|
9
|
+
jobs:
|
|
10
|
+
publish:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
environment: release
|
|
13
|
+
timeout-minutes: 10
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
|
16
|
+
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
|
|
17
|
+
with:
|
|
18
|
+
python-version: '3.14'
|
|
19
|
+
- name: Check the tag matches __version__
|
|
20
|
+
run: grep -qx "__version__ = \"${GITHUB_REF_NAME#v}\"" src/mapricot/__init__.py
|
|
21
|
+
- run: python -m unittest discover -s tests -v
|
|
22
|
+
env:
|
|
23
|
+
PYTHONPATH: src
|
|
24
|
+
MAPRICOT_KEY: ${{ secrets.MAPRICOT_KEY }}
|
|
25
|
+
- run: pip install build && python -m build
|
|
26
|
+
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
|
mapricot-0.1.0/LICENSE
ADDED
|
@@ -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.
|
mapricot-0.1.0/PKG-INFO
ADDED
|
@@ -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/)
|
mapricot-0.1.0/README.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# Mapricot for Python
|
|
2
|
+
|
|
3
|
+
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.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install mapricot
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
It needs Python 3.11 or later and has no dependencies.
|
|
10
|
+
|
|
11
|
+
## Quick start
|
|
12
|
+
|
|
13
|
+
Create a server key in the [dashboard](https://app.mapricot.com/) and set it as `MAPRICOT_KEY`:
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
export MAPRICOT_KEY="mapricot_sk_…"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
from mapricot import Mapricot
|
|
21
|
+
|
|
22
|
+
client = Mapricot()
|
|
23
|
+
|
|
24
|
+
data = client.search("128 SW 3rd Ave, Portland", limit=1)
|
|
25
|
+
place = data["results"][0]
|
|
26
|
+
print(place["label"], place["lat"], place["lon"])
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Pass the key yourself with `Mapricot("mapricot_sk_…")`.
|
|
30
|
+
|
|
31
|
+
## Methods
|
|
32
|
+
|
|
33
|
+
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/).
|
|
34
|
+
|
|
35
|
+
| Method | Endpoint |
|
|
36
|
+
| --- | --- |
|
|
37
|
+
| `client.search(q, focus=, country=, limit=, lang=)` | [`GET /v1/search`](https://mapricot.com/docs/geocoding/#find-an-address) |
|
|
38
|
+
| `client.autocomplete(q, focus=, country=, limit=, lang=)` | [`GET /v1/autocomplete`](https://mapricot.com/docs/places/#suggest-as-people-type) |
|
|
39
|
+
| `client.reverse(lat, lon, limit=, lang=)` | [`GET /v1/reverse`](https://mapricot.com/docs/geocoding/#find-the-address-at-a-point) |
|
|
40
|
+
| `client.nearby(lat, lon, category=, radius=, limit=, lang=)` | [`GET /v1/nearby`](https://mapricot.com/docs/places/#list-places-around-a-point) |
|
|
41
|
+
| `client.place(id, lang=)` | [`GET /v1/places/{id}`](https://mapricot.com/docs/places/#look-up-a-saved-place) |
|
|
42
|
+
| `client.route(waypoints, mode=)` | [`POST /v1/route`](https://mapricot.com/docs/routing/#get-a-route) |
|
|
43
|
+
| `client.ip(address)` | [`GET /v1/ip/{ip}`](https://mapricot.com/docs/ip-geolocation/#look-up-an-address) |
|
|
44
|
+
| `client.account()` | `GET /v1/account`, which checks a key and is never billed |
|
|
45
|
+
|
|
46
|
+
`focus` and each waypoint are `{"lat": …, "lon": …}`. `country` and `category` take a list or a comma-separated string.
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
nearby = client.nearby(45.52, -122.68, category=["food:coffee_shop"], radius=1000)
|
|
50
|
+
route = client.route([{"lat": 45.5189, "lon": -122.6793}, {"lat": 45.5214, "lon": -122.6828}], mode="walk")
|
|
51
|
+
print(route["routes"][0]["durationSeconds"])
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
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.
|
|
55
|
+
|
|
56
|
+
If your app shows results, show the credits in each response's `attribution`.
|
|
57
|
+
|
|
58
|
+
## Errors and retries
|
|
59
|
+
|
|
60
|
+
An error response raises `MapricotError`, with the HTTP `status`, the API's error `code`, a `message`, and the `request_id`:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from mapricot import MapricotError
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
client.search("")
|
|
67
|
+
except MapricotError as error:
|
|
68
|
+
print(error.status, error.code, error.message) # 400 invalid_request The service rejected the request.
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
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.
|
|
72
|
+
|
|
73
|
+
## Links
|
|
74
|
+
|
|
75
|
+
- [Mapricot](https://mapricot.com/)
|
|
76
|
+
- [Python docs](https://mapricot.com/docs/python/)
|
|
77
|
+
- [API reference](https://mapricot.com/api-reference/)
|
|
78
|
+
- [Pricing](https://mapricot.com/pricing/)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Releasing
|
|
2
|
+
|
|
3
|
+
1. Bump the version in `src/mapricot/__init__.py` (`__version__`), following [semantic versioning](https://semver.org/), and merge it to `main`.
|
|
4
|
+
2. Publish a GitHub release whose tag is that version with a `v`, such as `v0.2.0`: `gh release create v0.2.0 --generate-notes`.
|
|
5
|
+
3. The release workflow runs the live tests, builds, and publishes to PyPI.
|
|
6
|
+
|
|
7
|
+
## Keeping up with the API
|
|
8
|
+
|
|
9
|
+
CI runs every Monday as well as on each push. Its `endpoints` job fails when [the API's OpenAPI description](https://api.mapricot.com/openapi.json) lists an endpoint this client has no method for, and its tests fail when a live response changes. Add or fix the method and its test, and release a new minor version. A new endpoint is added to every Mapricot SDK at the same time.
|
|
10
|
+
|
|
11
|
+
## One-time setup
|
|
12
|
+
|
|
13
|
+
- A repository secret or organization secret `MAPRICOT_KEY`: a server key with the `places`, `routing`, and `ip-geolocation` scopes and a monthly cap, used by the live tests.
|
|
14
|
+
- A `release` environment in this repository.
|
|
15
|
+
- On pypi.org, a pending trusted publisher for the `mapricot` project: this repository, workflow `release.yml`, environment `release`.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mapricot"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Official client for the Mapricot API: geocoding, places, routing, and IP geolocation."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.11"
|
|
13
|
+
keywords = ["geocoding", "places", "routing", "ip-geolocation", "maps"]
|
|
14
|
+
classifiers = ["Programming Language :: Python :: 3", "Typing :: Typed"]
|
|
15
|
+
|
|
16
|
+
[project.urls]
|
|
17
|
+
Homepage = "https://mapricot.com/"
|
|
18
|
+
Documentation = "https://mapricot.com/docs/python/"
|
|
19
|
+
Source = "https://github.com/mapricothq/mapricot/tree/main/sdks/python"
|
|
20
|
+
Issues = "https://github.com/mapricothq/mapricot/issues"
|
|
21
|
+
|
|
22
|
+
[tool.hatch.version]
|
|
23
|
+
path = "src/mapricot/__init__.py"
|
|
@@ -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"
|
|
File without changes
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import unittest
|
|
3
|
+
|
|
4
|
+
from mapricot import Mapricot, MapricotError
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@unittest.skipUnless(os.environ.get("MAPRICOT_KEY"), "set MAPRICOT_KEY to run tests against the live API")
|
|
8
|
+
class LiveTest(unittest.TestCase):
|
|
9
|
+
@classmethod
|
|
10
|
+
def setUpClass(cls):
|
|
11
|
+
cls.client = Mapricot()
|
|
12
|
+
|
|
13
|
+
def test_search(self):
|
|
14
|
+
data = self.client.search("128 SW 3rd Ave, Portland", country=["US"], limit=1)
|
|
15
|
+
self.assertEqual(data["results"][0]["address"]["locality"], "Portland")
|
|
16
|
+
self.assertTrue(data["attribution"])
|
|
17
|
+
|
|
18
|
+
def test_autocomplete(self):
|
|
19
|
+
data = self.client.autocomplete("stumptown", focus={"lat": 45.52, "lon": -122.68}, limit=1)
|
|
20
|
+
self.assertIn("Stumptown", data["results"][0]["name"])
|
|
21
|
+
|
|
22
|
+
def test_reverse(self):
|
|
23
|
+
data = self.client.reverse(45.5217, -122.6733, limit=1)
|
|
24
|
+
self.assertIsInstance(data["results"][0]["distanceMeters"], int)
|
|
25
|
+
|
|
26
|
+
def test_nearby(self):
|
|
27
|
+
data = self.client.nearby(45.52, -122.68, category=["food:coffee_shop"], radius=1000, limit=1)
|
|
28
|
+
self.assertIn("food:coffee_shop", data["results"][0]["categories"])
|
|
29
|
+
|
|
30
|
+
def test_place(self):
|
|
31
|
+
found = self.client.search("Pioneer Courthouse Square, Portland", limit=1)["results"][0]
|
|
32
|
+
self.assertEqual(self.client.place(found["id"])["result"]["id"], found["id"])
|
|
33
|
+
|
|
34
|
+
def test_route(self):
|
|
35
|
+
data = self.client.route([{"lat": 43.7396, "lon": 7.4275}, {"lat": 43.734, "lon": 7.4222}], mode="walk")
|
|
36
|
+
self.assertEqual(len(data["routes"][0]["legs"]), 1)
|
|
37
|
+
self.assertTrue(data["routes"][0]["polyline"])
|
|
38
|
+
|
|
39
|
+
def test_ip(self):
|
|
40
|
+
data = self.client.ip("8.8.8.8")
|
|
41
|
+
self.assertTrue(data["found"])
|
|
42
|
+
self.assertEqual(data["countryCode"], "US")
|
|
43
|
+
|
|
44
|
+
def test_account(self):
|
|
45
|
+
self.assertEqual(self.client.account()["status"], "active")
|
|
46
|
+
|
|
47
|
+
def test_invalid_request(self):
|
|
48
|
+
with self.assertRaises(MapricotError) as caught:
|
|
49
|
+
self.client.search("")
|
|
50
|
+
self.assertEqual(caught.exception.status, 400)
|
|
51
|
+
self.assertEqual(caught.exception.code, "invalid_request")
|
|
52
|
+
self.assertTrue(caught.exception.request_id)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class BadKeyTest(unittest.TestCase):
|
|
56
|
+
def test_unauthorized(self):
|
|
57
|
+
with self.assertRaises(MapricotError) as caught:
|
|
58
|
+
Mapricot("mapricot_sk_bad").account()
|
|
59
|
+
self.assertEqual(caught.exception.status, 401)
|
|
60
|
+
self.assertEqual(caught.exception.code, "unauthorized")
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import threading
|
|
3
|
+
import unittest
|
|
4
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
5
|
+
|
|
6
|
+
from mapricot import Mapricot, MapricotError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def serve(statuses):
|
|
10
|
+
seen = []
|
|
11
|
+
|
|
12
|
+
class Handler(BaseHTTPRequestHandler):
|
|
13
|
+
def do_GET(self):
|
|
14
|
+
seen.append(self.path)
|
|
15
|
+
status, code = statuses.pop(0) if statuses else (200, None)
|
|
16
|
+
body = {"ok": True} if status == 200 else {"error": {"code": code, "message": code}, "request_id": "r1"}
|
|
17
|
+
self.send_response(status)
|
|
18
|
+
self.send_header("Content-Type", "application/json")
|
|
19
|
+
self.send_header("X-Request-Id", "r1")
|
|
20
|
+
self.end_headers()
|
|
21
|
+
self.wfile.write(json.dumps(body).encode())
|
|
22
|
+
|
|
23
|
+
def log_message(self, *args):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
27
|
+
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
28
|
+
return server, seen, f"http://127.0.0.1:{server.server_port}"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class RetryTest(unittest.TestCase):
|
|
32
|
+
def test_retries_503_and_concurrency_exceeded(self):
|
|
33
|
+
server, seen, base_url = serve([(503, "origin_overloaded"), (429, "concurrency_exceeded")])
|
|
34
|
+
self.addCleanup(server.server_close)
|
|
35
|
+
self.addCleanup(server.shutdown)
|
|
36
|
+
client = Mapricot("k", base_url=base_url)
|
|
37
|
+
self.assertEqual(client.search("x", focus={"lat": 1, "lon": 2}, country=["US", "CA"]), {"ok": True})
|
|
38
|
+
self.assertEqual(len(seen), 3)
|
|
39
|
+
self.assertEqual(seen[0], "/v1/search?q=x&focus=1%2C2&country=US%2CCA")
|
|
40
|
+
|
|
41
|
+
def test_does_not_retry_credit_exhausted(self):
|
|
42
|
+
server, seen, base_url = serve([(429, "credit_exhausted")])
|
|
43
|
+
self.addCleanup(server.server_close)
|
|
44
|
+
self.addCleanup(server.shutdown)
|
|
45
|
+
with self.assertRaises(MapricotError) as caught:
|
|
46
|
+
Mapricot("k", base_url=base_url).account()
|
|
47
|
+
self.assertEqual((caught.exception.status, caught.exception.code, caught.exception.request_id), (429, "credit_exhausted", "r1"))
|
|
48
|
+
self.assertEqual(len(seen), 1)
|