# Import a GPX catalog

> Canonical URL: https://docs.mountaya.com/en/apis/map-studio/gpx-import/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Turn a folder of GPX files into published itineraries with the Map Studio API, with a script you can run again safely.

A script that turns a folder of GPX files into published itineraries. Run it again after adding files, or after a crash, and it imports only what is missing.

![The import script and its output](https://docs.mountaya.com/examples/tutorial-gpx-import.webp)

You need:

- a publishable key with the `studio-embedded` scope, and your secret key, from **Organization → API keys** in the [Mountaya app](https://app.mountaya.com/api-keys);
- the id of a member of your organization, who the imports act as;
- Node 22.18 or later with `@mountaya/client` (`npm install @mountaya/client`), or Python 3 with `requests` (`pip install requests`).

Map Studio comes with an agreement.

**1. Put the files in a folder**

The script reads every `.gpx` file in `catalog/`. To try it, save one route there:

```bash
mkdir -p catalog
cat > catalog/chamonix-argentiere.gpx <<'GPX'
<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Docs" xmlns="http://www.topografix.com/GPX/1/1">
  <trk>
    <name>Docs Chamonix to Argentière</name>
    <trkseg>
      <trkpt lat="45.9231" lon="6.8712"><ele>1037</ele></trkpt>
      <trkpt lat="45.9395" lon="6.8905"><ele>1060</ele></trkpt>
      <trkpt lat="45.9558" lon="6.9036"><ele>1110</ele></trkpt>
      <trkpt lat="45.9700" lon="6.9180"><ele>1180</ele></trkpt>
      <trkpt lat="45.9822" lon="6.9271"><ele>1252</ele></trkpt>
    </trkseg>
  </trk>
</gpx>
GPX
```

Each itinerary takes its name from the file's `<name>`, which must be unique in your organization.

**2. Mint a session token for a member**

Imports act as one of your members, so the script mints a session token that names them. Check that your keys and the member work by minting one by hand. It needs `jq`:

**cURL**

```bash
export MOUNTAYA_MEMBER_TOKEN=$(curl -s -X POST https://api.mountaya.com/v1/sessions \
  -H "X-API-Key: $MOUNTAYA_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"publishable_key\": \"$MOUNTAYA_PUBLISHABLE_KEY\", \"user_id\": \"7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1\", \"surface\": \"studio-embedded\"}" \
  | jq -r .data.token)
```

**Response**

```json
{
  "data": {
    "expires_at": "2026-11-09T13:56:09.864388Z",
    "token": "sess_your_session_token",
    "user_id": "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1"
  }
}
```

A token lasts five minutes. The script in the next step mints its own, and a fresh one before each expires.

- Mint on a server or in a trusted script only: the secret key never reaches a browser. `user_id` must name a member of the key's organization with a write role.
- The token lasts five minutes. Renew it on a timer from `expires_at`, never in reaction to a `401`: a token that expires mid-flight fails one request of a burst. The script below does: in TypeScript a `SessionTokenEngine` whose `mint` calls `postSession` renews before expiry while something subscribes to it (release the subscription once the script is done, or its timer keeps Node running; a request made after that mints again on demand), and in Python `member_token()` mints again a minute before `expires_at`.

**3. Import each file once**

Here is the whole script. For each file, it asks for a preview, which reads the route and saves nothing. It skips a route an earlier run already imported, and imports and publishes any other.

**TypeScript**

```typescript
import { readdir, readFile } from "node:fs/promises";
import { Mountaya, SessionTokenEngine } from "@mountaya/client";
import { MountayaAdmin } from "@mountaya/client/admin";

const publishableKey = process.env.MOUNTAYA_PUBLISHABLE_KEY ?? "";
const server = new Mountaya({
  credential: { secretKey: process.env.MOUNTAYA_SECRET_KEY ?? "" },
});

// Mints a token for the member, and a fresh one before each expires.
const session = new SessionTokenEngine({
  mint: async () => {
    const { data } = await new MountayaAdmin(server).sessions.postSession({
      body: {
        publishable_key: publishableKey,
        surface: "studio-embedded",
        user_id: "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1",
      },
    });
    return data;
  },
});
const release = session.subscribe(() => undefined);

const mountaya = new Mountaya({ credential: { publishableKey, sessionToken: session } });

const { data: activities } = await mountaya.studio.activities.getActivities();
const hikingId =
  activities
    .flatMap((category) => category.children)
    .find((activity) => activity.slug === "hiking-and-trail")?.id ?? "";

const files = (await readdir("catalog")).filter((file) => file.endsWith(".gpx")).sort();

for (const file of files) {
  // Read the route. Nothing is saved yet.
  const form = new FormData();
  form.append("provider", "gpx");
  form.append("activity_id", hikingId);
  form.append("file", new Blob([await readFile(`catalog/${file}`)]), file);
  const { data: preview } = await mountaya.studio.itineraries.postItineraryPreview({ body: form });
  const name = preview.name.trim().slice(0, 30);

  // A route an earlier run imported keeps its name: find it rather than import it twice.
  const { data: found } = await mountaya.studio.itineraries.getItineraries({
    query: { q: name, limit: 10 },
  });
  const existing = found.find((itinerary) => itinerary.name === name);
  if (existing?.status === "published") {
    console.log(`${file}: already published as ${existing.id}`);
    continue;
  }

  let itineraryId = existing?.id;
  if (itineraryId === undefined) {
    const body = {
      name,
      activity_id: hikingId,
      is_private: false,
      segments: preview.segments.map((segment) => {
        const candidate = segment[segment.recommendation] ?? segment.linestring;
        return { mode: candidate.mode, name: segment.name, geojson: candidate.geojson };
      }),
      waypoints: preview.waypoints,
    };
    // The client sends an Idempotency-Key, and resends it if it has to retry.
    const { data: imported } = await mountaya.studio.itineraries.postItineraryImport({ body });
    itineraryId = imported.id;
  }

  await mountaya.studio.itineraries.postItineraryPublication({ itinerary_id: itineraryId });
  console.log(`${file}: published as ${itineraryId}`);
}

// Stop renewing, so the script can exit.
release();
```

**Python**

```python
import os
import time
import uuid
from datetime import datetime
from pathlib import Path

import requests

MAX_WAIT = 60  # seconds: a longer Retry-After is not worth waiting for in a script
_session = {"token": "", "renew_at": 0.0}


def member_token():
    """Mints a session token for the member, and a fresh one a minute before it expires."""
    if time.time() >= _session["renew_at"]:
        minted = requests.post(
            "https://api.mountaya.com/v1/sessions",
            headers={"X-API-Key": os.environ["MOUNTAYA_SECRET_KEY"]},
            json={
                "publishable_key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
                "user_id": "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1",
                "surface": "studio-embedded",
            },
            timeout=10,
        ).json()["data"]
        expires_at = datetime.fromisoformat(minted["expires_at"]).timestamp()
        _session.update(token=minted["token"], renew_at=expires_at - 60)
    return _session["token"]


def send(method, url, headers, **kwargs):
    """Sends a request with a fresh token, waiting out a short 429."""
    while True:
        response = requests.request(
            method,
            url,
            headers={**headers, "X-Session-Token": member_token()},
            timeout=60,
            **kwargs,
        )
        retry_after = response.headers.get("Retry-After")
        # A ceiling (LIMIT_REACHED) names no wait, and a long wait is not worth sitting out.
        if response.status_code != 429 or retry_after is None or int(retry_after) > MAX_WAIT:
            response.raise_for_status()
            return response.json()["data"]
        time.sleep(int(retry_after))


catalog = send(
    "GET",
    "https://api.mountaya.com/v1/activities",
    headers={"X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"]},
)
hiking_id = next(
    activity["id"]
    for category in catalog
    for activity in category["children"]
    if activity["slug"] == "hiking-and-trail"
)

for path in sorted(Path("catalog").glob("*.gpx")):
    # Read the route. Nothing is saved yet.
    preview = send(
        "POST",
        "https://api.mountaya.com/v1/itineraries/preview",
        headers={
            "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
            "Idempotency-Key": str(uuid.uuid4()),
        },
        data={"provider": "gpx", "activity_id": hiking_id},
        files={"file": (path.name, path.read_bytes())},
    )
    name = preview["name"].strip()[:30]

    # A route an earlier run imported keeps its name: find it rather than import it twice.
    found = send(
        "GET",
        "https://api.mountaya.com/v1/itineraries",
        headers={"X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"]},
        params={"q": name, "limit": 10},
    )
    existing = next((itinerary for itinerary in found if itinerary["name"] == name), None)
    if existing and existing["status"] == "published":
        print(f"{path.name}: already published as {existing['id']}")
        continue

    itinerary_id = existing["id"] if existing else None
    if itinerary_id is None:
        body = {
            "name": name,
            "activity_id": hiking_id,
            "is_private": False,
            "segments": [
                {
                    "mode": segment["recommendation"],
                    "name": segment["name"],
                    "geojson": segment[segment["recommendation"]]["geojson"],
                }
                for segment in preview["segments"]
            ],
            "waypoints": preview["waypoints"],
        }
        # One key per import: send() resends it when it has to wait out a 429.
        imported = send(
            "POST",
            "https://api.mountaya.com/v1/itineraries/import",
            headers={
                "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
                "Idempotency-Key": str(uuid.uuid4()),
            },
            json=body,
        )
        itinerary_id = imported["id"]

    send(
        "POST",
        f"https://api.mountaya.com/v1/itineraries/{itinerary_id}/publication",
        headers={
            "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
            "Idempotency-Key": str(uuid.uuid4()),
        },
    )
    print(f"{path.name}: published as {itinerary_id}")
```

Save the TypeScript as `import-catalog.ts` and run `node import-catalog.ts`. Or save the Python as `import_catalog.py` and run `python3 import_catalog.py`. Both read `MOUNTAYA_PUBLISHABLE_KEY` and `MOUNTAYA_SECRET_KEY` from the environment.

**Output**

```text
chamonix-argentiere.gpx: published as 5ee02630-e3e5-45c3-8811-e1d8933b6ead
```

The preview picks a mode for each stretch of the route. `directions` re-routes it on the trail network, and `linestring` keeps your points as drawn.

- `POST /v1/itineraries/preview` is `multipart/form-data`: `provider` (`gpx`, `geojson`, `kml`, `kmz`, `fit`, `tcx`), `file` (at most 25 MiB, `413` past it), `activity_id` (required), optional `granularity`. It saves nothing. It answers `name` (the file's own, unchecked), `activity_id`, `segments`, `waypoints` and `warnings`; each segment has a `recommendation` (`directions` or `linestring`), a `recommendation_reason`, and a candidate per mode, `directions` absent when the stretch cannot be routed. Send a candidate's `geojson` back unchanged.
- `POST /v1/itineraries/import` creates the itinerary, its segments and its waypoints together or not at all, and answers `201` with the whole draft. `name` is 2 to 30 characters, trimmed, and unique in the organization: a duplicate is `409`, which is why the script looks the name up first with `GET /v1/itineraries?q=`. Match the name exactly: `q` is a search, not an equality filter.
- The name is what makes a re-run safe, not the `Idempotency-Key`. A key makes a retry of one request safe: a repeat with the same key within 12 hours replays the first answer, so a request retried after a lost answer never imports twice. Mint a fresh key per import; never derive one from the file or the body, or a re-run within 12 hours of deleting an itinerary replays the deleted itinerary's `201` (and its id, which then answers `404`). The same key with a different body is `400`. The TypeScript client mints a key per write and reuses it on its own retries.
- List items carry `status` (`draft` or `published`). A run that crashed between the import and the publication finds the draft and publishes it.
- `POST /v1/itineraries/{itinerary_id}/publication` copies the draft into the published snapshot a key alone reads.
- Previews and imports share a limit of 10 requests a minute per user and 60 per organization, and the requests they send the routing engine a limit of 4,000 a minute per user and 24,000 per organization, each charged what it sent once it ends, a few dozen for a preview of a recording on mapped ways; a `429` carries `Retry-After` in seconds. The TypeScript client waits out a per-minute `429` within its default retry budget; the Python helper waits as told. A file past 500,000 points, or a freehand stretch over 500 km or 10,000 positions, is `413`: split it.

**4. Run it again**

Run the script a second time. Every route is already there, so nothing is imported twice:

**Output**

```text
chamonix-argentiere.gpx: already published as 5ee02630-e3e5-45c3-8811-e1d8933b6ead
```

Add a file to `catalog/` and run it again: only the new route is imported.

## Next steps

- [Import and export](https://docs.mountaya.com/en/apis/map-studio/import-export.md): Every format, and route files back out.
- [Idempotency](https://docs.mountaya.com/en/apis/conventions/idempotency.md): How a key makes a retry safe.
