# GraphQL conventions

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

How the Data API uses GraphQL: one input per query, enum spelling, field selection, batching, errors under 200 OK, persisted queries, and the explorer.

The Data API is one GraphQL endpoint that only reads. The rules on this page hold for all fourteen queries.

```text
POST https://data.mountaya.com/graphql
```

## Set up

Every sample on this page reuses this setup. It mints a session token with your secret key, so run it on your server.

**cURL**

```bash
export MOUNTAYA_PUBLISHABLE_KEY="pk_your_publishable_key"
export MOUNTAYA_DATA_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\"}" | jq -r .data.token)
```

**TypeScript**

```typescript
import { Mountaya } from "@mountaya/client";
import { MountayaAdmin } from "@mountaya/client/admin";

const publishableKey = process.env.MOUNTAYA_PUBLISHABLE_KEY ?? "";
const secretKey = process.env.MOUNTAYA_SECRET_KEY ?? "";

const server = new Mountaya({ credential: { secretKey } });
const { data: session } = await new MountayaAdmin(server).sessions.postSession({
  body: { publishable_key: publishableKey },
});

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

**Python**

```python
import os
import requests

session = 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"]},
    timeout=10,
).json()["data"]
```

## One input per query

Every query takes a single argument, `input`. Pass it as a variable, and spell enum values in capitals with underscores: `HIKING_AND_TRAIL`, `CITY`.

**cURL**

```bash
curl https://data.mountaya.com/graphql \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_DATA_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "query ReverseGeocode($input: ReverseGeocodeInput!) { reverseGeocode(input: $input) { places { name layer } } }",
    "variables": {
      "input": { "point": [6.8712, 45.9231], "limit": 1, "layers": ["CITY"] }
    }
  }'
```

**TypeScript**

```typescript
const town = await mountaya.data.reverseGeocode(
  { point: [6.8712, 45.9231], limit: 1, layers: ["CITY"] },
  { select: { places: { name: true, layer: true } } },
);

console.log(town.places[0]?.name);
```

**Python**

```python
query = """
query ReverseGeocode($input: ReverseGeocodeInput!) {
  reverseGeocode(input: $input) { places { name layer } }
}
"""

result = requests.post(
    "https://data.mountaya.com/graphql",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": session["token"],
    },
    json={
        "query": query,
        "variables": {"input": {"point": [6.8712, 45.9231], "limit": 1, "layers": ["CITY"]}},
    },
    timeout=30,
).json()

if "errors" in result:
    raise RuntimeError(result["errors"])
print(result["data"]["reverseGeocode"]["places"][0]["name"])
```

**Response**

```json
{
  "data": {
    "reverseGeocode": {
      "places": [
        {
          "name": "Chamonix-Mont-Blanc",
          "layer": "CITY"
        }
      ]
    }
  }
}
```

Send every request as a `POST` with a JSON body. Any other method answers `405 Method Not Allowed`.

## Select the fields you need

A GraphQL query lists the fields it wants back, and the answer holds those fields alone. Ask for a route's `geometry` only when you draw it: it holds one position per vertex.

In TypeScript, pass `select` to any `mountaya.data` method. Without it, the client asks for every field. The result type narrows to what you selected, so reading a field you did not select fails to compile.

## Batch up to four queries

One request can carry up to four queries. Give each one an alias to tell their answers apart.

**cURL**

```bash
curl https://data.mountaya.com/graphql \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_DATA_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "query Trailheads { chamonix: reverseGeocode(input: { point: [6.8712, 45.9231], limit: 1, layers: [CITY] }) { places { name } } argentiere: reverseGeocode(input: { point: [6.9271, 45.9822], limit: 1, layers: [DISTRICT] }) { places { name } } }"
  }'
```

**Python**

```python
query = """
query Trailheads {
  chamonix: reverseGeocode(input: { point: [6.8712, 45.9231], limit: 1, layers: [CITY] }) {
    places { name }
  }
  argentiere: reverseGeocode(input: { point: [6.9271, 45.9822], limit: 1, layers: [DISTRICT] }) {
    places { name }
  }
}
"""

result = requests.post(
    "https://data.mountaya.com/graphql",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": session["token"],
    },
    json={"query": query},
    timeout=30,
).json()

if "errors" in result:
    raise RuntimeError(result["errors"])
print(result["data"]["chamonix"]["places"][0]["name"], result["data"]["argentiere"]["places"][0]["name"])
```

**Response**

```json
{
  "data": {
    "chamonix": {
      "places": [{ "name": "Chamonix-Mont-Blanc" }]
    },
    "argentiere": {
      "places": [{ "name": "Argentière" }]
    }
  }
}
```

The TypeScript client sends one query per call: run several calls with `Promise.all` instead. A fifth query in one request is refused, so split larger batches.

## Read errors in the body

A query that fails still answers `200 OK`. The body then carries an `errors` array, so check it on every response. Each error names a `code` and, for invalid input, the `path` of the field to fix.

**cURL**

```bash
curl https://data.mountaya.com/graphql \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_DATA_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "query Directions($input: DirectionsInput!) { directions(input: $input) { routes { distance } } }",
    "variables": {
      "input": { "activity": "HIKING_AND_TRAIL", "waypoints": [[6.8712, 45.9231]] }
    }
  }'
```

**TypeScript**

```typescript
import { MountayaDataError } from "@mountaya/client";

try {
  await mountaya.data.directions(
    { activity: "HIKING_AND_TRAIL", waypoints: [[6.8712, 45.9231]] },
    { select: { routes: { distance: true } } },
  );
} catch (error) {
  if (!(error instanceof MountayaDataError)) {
    throw error;
  }
  for (const entry of error.errors) {
    console.log(entry.extensions?.code, entry.extensions?.path, entry.message);
  }
}
```

**Python**

```python
query = """
query Directions($input: DirectionsInput!) {
  directions(input: $input) { routes { distance } }
}
"""

result = requests.post(
    "https://data.mountaya.com/graphql",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": session["token"],
    },
    json={
        "query": query,
        "variables": {"input": {"activity": "HIKING_AND_TRAIL", "waypoints": [[6.8712, 45.9231]]}},
    },
    timeout=30,
).json()

for error in result.get("errors", []):
    print(error["extensions"]["code"], error["extensions"].get("path"), error["message"])
```

**Response**

```json
{
  "errors": [
    {
      "message": "Must have at least 2 waypoints",
      "path": ["directions"],
      "locations": [{ "line": 1, "column": 46 }],
      "extensions": {
        "code": "VALIDATION_FAILED",
        "path": ["input", "waypoints"]
      }
    }
  ],
  "data": null
}
```

The TypeScript client throws a `MountayaDataError` holding the same entries. A request refused before any query runs, such as one with an expired token, gets an HTTP error status instead. [Errors](https://docs.mountaya.com/en/apis/conventions/errors.md) lists them.

## Persisted queries

A query document can be long, so you can send its SHA-256 hash in its place. The first time, the API may not know the hash: send the request again with the document. The TypeScript client does this for you.

```json
{
  "extensions": { "persistedQuery": { "version": 1, "sha256Hash": "11a4644a20386ce7a28aa711862e60231b43fef41ab0444f7a25b18c9352979b" } },
  "variables": { "input": { "locations": [[6.8712, 45.9231]] } }
}
```

**Response when the hash is unknown**

```json
{"errors":[{"message":"PersistedQueryNotFound","extensions":{"code":"PERSISTED_QUERY_NOT_FOUND"}}],"data":null}
```

## Explore the schema

The [Data API explorer](https://docs.mountaya.com/en/apis/data/explorer.md) runs queries from your browser. Open its **Headers** tab and paste your publishable key and a fresh session token as `X-API-Key` and `X-Session-Token`.

To generate types in your own tooling, download the [GraphQL schema](https://docs.mountaya.com/descriptions/graphql/data/schema.graphql).

Endpoint and transport:

- `POST https://data.mountaya.com/graphql`. Queries only: there are no mutations and no subscriptions. There is no sandbox host; test with a separate organization on the same host.
- Send `Content-Type: application/json` and a JSON object body with `query`, `variables`, `operationName` and `extensions` (no other members). A body not sent as `application/json`, one that does not decode as a JSON object, or a request asking to upgrade its connection is `400 BAD_REQUEST` (the body is never echoed). A body over 32 MiB is `413 PAYLOAD_TOO_LARGE`.
- Any method but `POST` is `405 METHOD_NOT_ALLOWED`, answered before the credential is read, costing no rate-limit unit, with `Allow: POST`. The API answers a CORS preflight and advertises `POST` and `OPTIONS` only.
- Credentials: the publishable key in `X-API-Key` and the session token in `X-Session-Token`, or, for a request that cannot set headers, the `publishable_key` and `session_token` query parameters. The header wins when both are sent. A query parameter present without its prefix (`pk_`, `sess_`) is `401`, never read as absent; an empty one counts as absent.
- Every answer carries `X-Request-Id` (32 lowercase hex characters). Quote it when reporting a problem.
- Every operation is answered within 30 seconds. One still running then is `504 GATEWAY_TIMEOUT` with no data; it counts toward the per-minute limit and its root fields toward no allowance. Wait a little longer than 30 seconds before giving up, as Mountaya's SDKs do.

Input and enums:

- Every query takes exactly one argument, `input`, a dedicated input type (`DirectionsInput`, `GeocodeInput`, ...).
- Enum values are SCREAMING_SNAKE_CASE. An enum value sent in the variables must be spelled as the schema spells it: another case (`city` for `CITY`, `en` for `EN`) passes the protocol's validation, which ignores case, and is then refused as a whole: `data` is null and the one error carries `GRAPHQL_VALIDATION_FAILED` with the value's place under its variable as `path`, such as `["variable", "input", "layers", 0]`, in a `200`. An enum value written in the document itself is matched exactly by the protocol's validation and refused there.
- Thirteen enums are shared with the REST APIs (Map Studio API, Tile API): `ActivitySlug`, `ExportFormat`, `ExportVariant`, `Language`, `ManeuverType`, `RangeType`, `SurfaceType`, `TrailDifficultyType`, `WaypointAmenity`, `WaypointPropertyFormat`, `WayType`, `ZoneLevel`, `ZoneMode`. REST spells them in kebab-case: lowercase the value and turn each underscore into a hyphen (`HIKING_AND_TRAIL` is `hiking-and-trail`).
- Coordinates are `[longitude, latitude]` (WGS 84), distances meters, durations seconds, elevations meters above sea level, gradients degrees. `speed` alone is km/h.

Selection and batching:

- `@mountaya/client` sends a generated, depth-bounded full selection when `select` is omitted, which includes 3D geometry and per-vertex elevations. Pass `select` to narrow both the document sent and the result type. A selection built at runtime is validated when the document is printed; a name the schema lacks throws `MountayaSelectionError`.
- Every operation is held to a depth limit of 15, then to a complexity ceiling of 500, before any field runs. A root field is at depth one, and each selection nested inside a field one deeper, fragments counted as written in place and introspection fields not counted. An operation nested deeper than 15 levels is refused as a whole: `data` is null and the one error carries `DEPTH_LIMIT_EXCEEDED` (outside `ErrorCode`), with an English message, in a `200`. No query of the schema needs that depth with its full selection.
- For the complexity ceiling, a field costs one plus what its selection costs, and a root field costs 100 on top, so an operation carries at most four root fields, aliases included, however small their selections, while any single query fits with its full selection. An operation over the ceiling is refused as a whole: `data` is null and the one error carries `COMPLEXITY_LIMIT_EXCEEDED` (outside `ErrorCode`), with an English message such as `operation has complexity 505, which exceeds the limit of 500`, in a `200`. Split a larger batch across requests.
- The per-minute limit counts HTTP requests (one request is one unit however many root fields it holds); the monthly allowance, 300,000 unless an agreement sets another figure, counts root fields answered without an error. See [rate limits](https://docs.mountaya.com/en/apis/conventions/rate-limits.md).

Errors:

- Once fields run, their errors arrive in a `200` response beside whatever data resolved. Each entry carries `message` (localized by `Accept-Language`; a region tag falls back to its primary language; an unsupported language reads English), the GraphQL `path` of the field, `locations`, and `extensions.code`.
- `extensions.path` is set on every `VALIDATION_FAILED` entry: the field path within the operation's input, such as `["input", "waypoints", 0]`, or `["input"]` when the refusal is about the input as a whole. It sits under `extensions`. The REST APIs carry the same fact on the entry itself, prefixed `["request", ...]`.
- One entry per refused field within a validation stage. Input is checked in stages, and a later stage runs only once earlier ones pass (the length of a list and the fields beside it before each position in it), so a refused `speed` hides a refused waypoint until it is corrected. Fix what was reported and send again.
- A non-null root field that fails nulls `data` as a whole, as the sample shows.
- A 5xx entry is opaque: a generic localized message, no `extensions.path`, and the GraphQL `path` of the field that failed. A field answered only in part because an upstream failed on Mountaya's side keeps the data it resolved and carries an `INTERNAL_ERROR` entry at its own path, and counts as a failed field.
- A refusal relayed from the routing engine, which `directions` alone relays, carries the engine's own message in English, as does a refusal by the GraphQL protocol itself.
- `@mountaya/client` throws `MountayaDataError` for any response whose body states `errors` (status 200), with the entries on `error.errors`, `error.status`, and `error.requestId`. A non-2xx response is classified by status into the shared error classes (`MountayaAuthenticationError` for 401, and so on).

A request refused before any field runs carries the HTTP status its code names. The checks run in this order, and a request wrong in several ways is answered for the first only:

1. `405 METHOD_NOT_ALLOWED`: any method but `POST`, before the credential is read.
2. `429 TOO_MANY_REQUESTS` (with `Retry-After`) when the client's IP address has had more than 60 unknown publishable keys refused within the minute and the key was not resolved moments earlier; then `401 UNAUTHORIZED`: no publishable key, a secret key in its place, or an unknown or revoked key.
3. `401 UNAUTHORIZED`: the key's organization has been canceled.
4. `403 FORBIDDEN`: the request's `Origin`, or failing that its `Referer`, names a page the organization does not allow. Add the host under **Organization → Security**, or call from a backend, which sends neither header.
5. `401 UNAUTHORIZED`: the session token is malformed, expired, minted for another publishable key, or missing. Mint a fresh one. Every `401` carries the same message and a `WWW-Authenticate` header.
6. `402 PAYMENT_REQUIRED`: the organization does not hold the Data API (no card opened the metered subscription and no agreement grants it).
7. `403 FORBIDDEN`: the key lacks the `data` scope (`mcp` on a request through Mountaya's MCP server).
8. `402 PAYMENT_REQUIRED`: the organization is billed by card and has no payment method on file.
9. `429 TOO_MANY_REQUESTS` with `Retry-After`: a spent monthly allowance, then the per-minute limit (for a `studio-embedded` token, the member's or address's bound, then the organization's).
10. `413 PAYLOAD_TOO_LARGE`: a body over 32 MiB.
11. `400 BAD_REQUEST`: a connection upgrade, a body not `application/json`, or not one JSON object, a field named twice and text that is not valid UTF-8 included.
12. The GraphQL protocol: the persisted query (`PERSISTED_QUERY_NOT_FOUND`, or `BAD_REQUEST` in a `200`), then the document (`GRAPHQL_PARSE_FAILED`, `GRAPHQL_VALIDATION_FAILED`, status `422`, or `400` when the response is negotiated as `application/graphql-response+json`: an `Accept` header naming that type ahead of `application/json`, `application/*` and `*/*`, or naming none of the four), then the depth limit (`DEPTH_LIMIT_EXCEEDED`), then the complexity ceiling (`COMPLEXITY_LIMIT_EXCEEDED`), then an enum value in the variables spelled in another case (`GRAPHQL_VALIDATION_FAILED`, `200`).
13. The fields: `VALIDATION_FAILED`, `NOT_FOUND`, `PAYLOAD_TOO_LARGE` and the rest, each entry in a `200` beside whatever data resolved.

A failure while checking a credential or reading entitlements is an opaque `500 INTERNAL_ERROR`, never a `401` or `402`. Refusals at steps 1 to 8 carry no `RateLimit` headers; a `200`, a `429` and refusals after the limits carry `RateLimit-Policy` and `RateLimit`.

Persisted queries (automatic persisted queries, protocol version 1):

- Send `extensions.persistedQuery` with `version: 1` and `sha256Hash`, the lowercase hex SHA-256 of the exact `query` string, and omit `query`. When the API does not hold the hash it answers `PERSISTED_QUERY_NOT_FOUND` in a `200` with `data` null: send the request again with both `query` and the extension, which registers it.
- A persisted-query request the API cannot read (an unreadable extension, a version other than 1, or a hash that does not match the document sent beside it) is answered `BAD_REQUEST` in a `200`, with an English message; sending it unchanged gets the same answer.
- This API never sends `PERSISTED_QUERY_NOT_SUPPORTED`; Mountaya's SDKs also recognize it, from servers that decline the protocol.
- `@mountaya/client` sends the hash first and the document once per hash, on every Data API method.

Explorer and schema:

- The explorer at `/en/apis/data/explorer/` loads the schema from a static file and needs no credential to browse. Running a query sends `X-API-Key` and `X-Session-Token` from its Headers tab to `https://data.mountaya.com/graphql` from the browser, so the request carries the docs site's `Origin` (`https://docs.mountaya.com`). That origin is Mountaya's own, admitted for every organization's key, so your allowed domains need not list it.
- The session token expires within five minutes; mint a fresh one when the explorer answers `401`.
- The SDL is at `/descriptions/graphql/data/schema.graphql` on the docs site. Field-level scopes are declared by the `@pkeyScope(anyOf: [DATA, MCP])` directive, which introspection does not report; each query's description states the same in words.

## Next steps

- [Data API overview](https://docs.mountaya.com/en/apis/data.md): The fourteen queries and the guide for each.
- [Data API explorer](https://docs.mountaya.com/en/apis/data/explorer.md): Browse the schema and run queries in your browser.
