{"schema_version":1,"generated_at":"2026-11-20T10:57:14.261Z","site_commit":"d9767cb32ca3bfe8c77b8b576d78dd835f9b74b8","base_url":"https://ir.railcore.tech/v1","docs_origin":"https://railcore.tech","date_placeholders":[{"token":"{{date:days_ahead_utc:7}}","meaning":{"kind":"days_ahead_utc","days":7}},{"token":"{{date:days_ahead_utc:8}}","meaning":{"kind":"days_ahead_utc","days":8}},{"token":"{{date:today_ist}}","meaning":{"kind":"today_ist"}}],"rules":{"signing":"Growth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.","key_headers":"Send the key in X-RailCore-Key, or as Authorization: Bearer <key>, or in X-Api-Key. Use one header: two headers with different keys answer 401 AMBIGUOUS_API_KEY.","account_limits":"Rate limits are per account. Every key on the account shares them, and creating another key does not reset them.","day_headers":"Only Free accounts have a daily cap, and only their keys receive the X-RailCore-RateLimit-Day-* headers. A key without a daily cap gets no Day-* headers and never a daily 429.","minute_headers":"X-RailCore-RateLimit-Limit, -Remaining and -Reset are sent only when the account's plan has a per-minute limit. A plan without one (Enterprise), and a request refused before the key was read (a malformed request, a missing or wrong key), get none of the three, never 0.","playground_token_minutes":15,"signing_plan_ids":["developer_growth","developer_scale","developer_enterprise"],"signing_guide_url":"https://railcore.tech/docs/hmac"},"plans":[{"id":"developer_free","name":"Free","price_inr_per_month":0,"requests_per_month":500,"requests_per_minute":10,"requests_per_day":100,"must_sign_requests":false,"ip_allowlist":false,"charts_and_jobs":false,"commercial_use":false,"intro_offer":null,"support":"Docs","summary":"Build and evaluate. No card, no phone number.","highlights":["500 requests a month","Every core endpoint, live status included","Failed requests are free"]},{"id":"developer_starter","name":"Starter","price_inr_per_month":699,"requests_per_month":40000,"requests_per_minute":60,"requests_per_day":null,"must_sign_requests":false,"ip_allowlist":false,"charts_and_jobs":false,"commercial_use":true,"intro_offer":{"kind":"trial","days":30},"support":"Email, 24 h","summary":"For a live app with real users.","highlights":["40,000 requests a month","No daily cap","Commercial use"]},{"id":"developer_growth","name":"Growth","price_inr_per_month":2499,"requests_per_month":150000,"requests_per_minute":200,"requests_per_day":null,"must_sign_requests":true,"ip_allowlist":true,"charts_and_jobs":false,"commercial_use":true,"intro_offer":{"kind":"discount","percent":50,"cycles":1},"support":"Priority email and WhatsApp, 8 h","summary":"For products with steady traffic and bursts.","highlights":["1,50,000 requests a month","200 requests a minute","IP allowlists; request signing required"]},{"id":"developer_scale","name":"Scale","price_inr_per_month":6499,"requests_per_month":500000,"requests_per_minute":500,"requests_per_day":null,"must_sign_requests":true,"ip_allowlist":true,"charts_and_jobs":true,"commercial_use":true,"intro_offer":{"kind":"discount","percent":50,"cycles":1},"support":"Priority email and WhatsApp, 4 h","summary":"High volume, plus the vacant-berth suite.","highlights":["5,00,000 requests a month","500 requests a minute","Vacant berths and chart status"]},{"id":"developer_enterprise","name":"Enterprise","price_inr_per_month":null,"requests_per_month":null,"requests_per_minute":null,"requests_per_day":null,"must_sign_requests":true,"ip_allowlist":true,"charts_and_jobs":true,"commercial_use":true,"intro_offer":null,"support":"Named contact and an SLA","summary":"Custom volume, limits and terms.","highlights":["Agreed volume and limits","Contract and invoicing","Uptime commitment"]}],"request_weights":{"core":1,"seatBatchPerTrainClass":1,"journeysComparePerRoute":1,"pnrStatus":1,"pnrPrediction":2,"chartStatus":1,"vacantBerths":3,"vacantBerthsHopping":4,"vacantBerthsRouteScan":8,"jobPolling":0},"pricing_url":"https://railcore.tech/pricing","endpoints":[{"id":"search-stations","category":"Stations","method":"GET","path":"/stations/search","url_template":"https://ir.railcore.tech/v1/stations/search","title":"Search stations","summary":"Find stations by code, city, name, or alias.","description":"Searches the RailCore reference index and returns ranked canonical station records suitable for autocomplete and station resolution.","scope":"stations:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"q","in":"query","type":"string","required":true,"description":"Search text, station code, city, or alias. 1 to 80 characters.","example":"bhusaval","pattern":".{1,80}"},{"name":"limit","in":"query","type":"integer","required":false,"description":"Maximum results.","example":"5","default":"10","minimum":1,"maximum":50}],"body_fields":[],"response_fields":[{"name":"query","type":"string","description":"Normalized query."},{"name":"limit","type":"integer","description":"Applied result limit."},{"name":"enriched","type":"boolean","description":"Whether some results' city, state or position were filled in from a second station source. false when every result comes from RailCore's own station reference, as it does today."},{"name":"results[]","type":"Station[]","description":"Ranked station records."},{"name":"results[].station_code","type":"string","description":"Canonical station code."},{"name":"results[].station_name","type":"string","description":"Canonical station name."},{"name":"results[].display_name","type":"string","description":"Name formatted for user interfaces."},{"name":"results[].city","type":"string | null","description":"Associated city when available."},{"name":"results[].state","type":"string | null","description":"Indian state or union territory when available."},{"name":"results[].country","type":"string","description":"ISO country code, normally IN."},{"name":"results[].latitude","type":"number | null","description":"WGS84 latitude."},{"name":"results[].longitude","type":"number | null","description":"WGS84 longitude."},{"name":"results[].aliases","type":"string[]","description":"Known alternate names and codes."},{"name":"results[].is_major","type":"boolean","description":"Whether the station is considered a major junction or hub."},{"name":"results[].confidence","type":"number","description":"Match confidence from 0 to 1."}],"response_example":{"success":true,"data":{"query":"bhusaval","limit":5,"enriched":false,"results":[{"station_code":"BSL","station_name":"Bhusaval Jn","display_name":"Bhusaval Jn","city":"Bhusawal","state":"Maharashtra","country":"IN","latitude":21.048194,"longitude":75.788607,"aliases":["Bhusaval Junction"],"is_major":true,"confidence":0.98}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.605Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.605Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/search-stations","markdown_url":"https://railcore.tech/docs/api/search-stations.md","markdown":"# Search stations\n\nFind stations by code, city, name, or alias.\n\n`GET /v1/stations/search`\n\n- **Scope:** `stations:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nSearches the RailCore reference index and returns ranked canonical station records suitable for autocomplete and station resolution.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/stations/search?q=bhusaval&limit=5\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"query\": \"bhusaval\",\n    \"limit\": 5,\n    \"enriched\": false,\n    \"results\": [\n      {\n        \"station_code\": \"BSL\",\n        \"station_name\": \"Bhusaval Jn\",\n        \"display_name\": \"Bhusaval Jn\",\n        \"city\": \"Bhusawal\",\n        \"state\": \"Maharashtra\",\n        \"country\": \"IN\",\n        \"latitude\": 21.048194,\n        \"longitude\": 75.788607,\n        \"aliases\": [\"Bhusaval Junction\"],\n        \"is_major\": true,\n        \"confidence\": 0.98\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.605Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.605Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `stations:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `q` string required Search text, station code, city, or alias. 1 to 80 characters. Example bhusaval\n- `limit` integer optional Maximum results. Example 5 Default 10 Range 1 to 50\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `query` string Normalized query.\n- `limit` integer Applied result limit.\n- `enriched` boolean Whether some results' city, state or position were filled in from a second station source. false when every result comes from RailCore's own station reference, as it does today.\n- `results[]` Station[] Ranked station records.\n  - `station_code` string Canonical station code.\n  - `station_name` string Canonical station name.\n  - `display_name` string Name formatted for user interfaces.\n  - `city` string | null Associated city when available.\n  - `state` string | null Indian state or union territory when available.\n  - `country` string ISO country code, normally IN.\n  - `latitude` number | null WGS84 latitude.\n  - `longitude` number | null WGS84 longitude.\n  - `aliases` string[] Known alternate names and codes.\n  - `is_major` boolean Whether the station is considered a major junction or hub.\n  - `confidence` number Match confidence from 0 to 1.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/search-stations\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/stations/search?q=bhusaval&limit=5\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/stations/search?q=bhusaval&limit=5\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/stations/search?q=bhusaval&limit=5\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/stations/search?q=bhusaval&limit=5\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/stations/search?q=bhusaval&limit=5\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/stations/search?q=bhusaval&limit=5\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/stations/search\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"limit=5&q=bhusaval\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/stations/search\";\nconst params = [\n  [\"q\", \"bhusaval\"],\n  [\"limit\", \"5\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/stations/search\"\nparams = [\n    (\"q\", \"bhusaval\"),\n    (\"limit\", \"5\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/stations/search\";\n$params = [\n    [\"q\", \"bhusaval\"],\n    [\"limit\", \"5\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/stations/search\"\n\tparams := [][2]string{\n\t\t{\"q\", \"bhusaval\"},\n\t\t{\"limit\", \"5\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/stations/search\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"q\", \"bhusaval\"},\n            new String[] {\"limit\", \"5\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"get-station","category":"Stations","method":"GET","path":"/stations/{station_code}","url_template":"https://ir.railcore.tech/v1/stations/{station_code}","title":"Get station","summary":"Resolve one canonical station record.","description":"Returns reference and geographic metadata for one station code.","scope":"stations:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"station_code","in":"path","type":"string","required":true,"description":"Indian Railways station code, 1 to 6 uppercase letters or digits.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"}],"body_fields":[],"response_fields":[{"name":"station_code","type":"string","description":"Canonical station code."},{"name":"station_name","type":"string","description":"Canonical station name."},{"name":"display_name","type":"string","description":"Name formatted for user interfaces."},{"name":"city","type":"string | null","description":"Associated city when available."},{"name":"state","type":"string | null","description":"Indian state or union territory when available."},{"name":"country","type":"string","description":"ISO country code, normally IN."},{"name":"latitude","type":"number | null","description":"WGS84 latitude."},{"name":"longitude","type":"number | null","description":"WGS84 longitude."},{"name":"aliases","type":"string[]","description":"Known alternate names and codes."},{"name":"is_major","type":"boolean","description":"Whether the station is considered a major junction or hub."},{"name":"confidence","type":"number","description":"Match confidence from 0 to 1."}],"response_example":{"success":true,"data":{"station_code":"BSL","station_name":"Bhusaval Jn","display_name":"Bhusaval Jn","city":"Bhusawal","state":"Maharashtra","country":"IN","latitude":21.048194,"longitude":75.788607,"aliases":["Bhusaval Junction"],"is_major":true,"confidence":0.98},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.605Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.605Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":404,"code":"STATION_NOT_FOUND","description":"No station has that code. error.message names it: Station ZZZZ not found. Check the station code. Not counted.","retryable":false,"category":"NOT_FOUND","fix":"Check the station code. Find it by name with GET /stations/search."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/get-station","markdown_url":"https://railcore.tech/docs/api/get-station.md","markdown":"# Get station\n\nResolve one canonical station record.\n\n`GET /v1/stations/{station_code}`\n\n- **Scope:** `stations:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns reference and geographic metadata for one station code.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/stations/BSL\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"station_code\": \"BSL\",\n    \"station_name\": \"Bhusaval Jn\",\n    \"display_name\": \"Bhusaval Jn\",\n    \"city\": \"Bhusawal\",\n    \"state\": \"Maharashtra\",\n    \"country\": \"IN\",\n    \"latitude\": 21.048194,\n    \"longitude\": 75.788607,\n    \"aliases\": [\"Bhusaval Junction\"],\n    \"is_major\": true,\n    \"confidence\": 0.98\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.605Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.605Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `stations:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `station_code` string required Indian Railways station code, 1 to 6 uppercase letters or digits. Example BSL\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `station_code` string Canonical station code.\n- `station_name` string Canonical station name.\n- `display_name` string Name formatted for user interfaces.\n- `city` string | null Associated city when available.\n- `state` string | null Indian state or union territory when available.\n- `country` string ISO country code, normally IN.\n- `latitude` number | null WGS84 latitude.\n- `longitude` number | null WGS84 longitude.\n- `aliases` string[] Known alternate names and codes.\n- `is_major` boolean Whether the station is considered a major junction or hub.\n- `confidence` number Match confidence from 0 to 1.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [STATION_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-STATION_NOT_FOUND) Do not retry unchanged No station has that code. error.message names it: Station ZZZZ not found. Check the station code. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/get-station\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/stations/BSL\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/stations/BSL\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/stations/BSL\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/stations/BSL\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/stations/BSL\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/stations/BSL\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/stations/BSL\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/stations/BSL\";\nconst params = [];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/stations/BSL\"\nparams = []\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/stations/BSL\";\n$params = [];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/stations/BSL\"\n\tparams := [][2]string{}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/stations/BSL\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"live-station-board","category":"Stations","method":"GET","path":"/stations/{station_code}/live","url_template":"https://ir.railcore.tech/v1/stations/{station_code}/live","title":"Live station board","summary":"Arrivals and departures from 2 hours ago to 4 or 8 hours ahead.","description":"Returns one canonical station board for trains arriving at, departing from, starting at, or terminating at the station, with schedule, estimate, platform, delay, state, confidence, and report time. A train is listed when its expected or booked time at the station, arriving or leaving, falls inside the window: from 2 hours ago to window_hours ahead.","scope":"live:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"station_code","in":"path","type":"string","required":true,"description":"Indian Railways station code, 1 to 6 uppercase letters or digits.","example":"NDLS","pattern":"^[A-Z0-9]{1,6}$"},{"name":"window_hours","in":"query","type":"integer","required":false,"description":"How far ahead the board looks. It lists trains due at the station from 2 hours ago until this many hours later, by expected or booked time. 4 or 8; any other value is read as 8.","example":"8","default":"8","allowed":["4","8"]}],"body_fields":[],"response_fields":[{"name":"station_code","type":"string","description":"Board station."},{"name":"window_hours","type":"integer","description":"How far ahead the board looks, in hours from now: 4 or 8. Check it when you send anything other than 4 or 8."},{"name":"window.from / window.to","type":"string(date-time)","description":"The bounds the board was cut to, as India-time instants with their +05:30 offset: 2 hours before the request and window_hours after it."},{"name":"window.hours_back / window.hours_ahead","type":"integer","description":"How far back (always 2) and how far ahead (window_hours) the board looks."},{"name":"trains[].train_number / train_name","type":"string","description":"Train number, and the name the live feed gives, often abbreviated (GKP DR EXP). When the feed named other first or last stations than RailCore's train catalog has for that number, the feed's row was for another train with the same number, and train_name is the catalog's name."},{"name":"trains[].extended_train_name","type":"string","description":"The train's full name from RailCore's train catalog (Dadar Central Express). The same as train_name for a train the catalog does not list."},{"name":"trains[].source_station_code / destination_station_code","type":"string","description":"The train's first and last stations, from RailCore's train catalog when it lists the train: the catalog wins over the live feed, which reuses numbers for other local trains. A train the catalog does not list keeps the feed's."},{"name":"trains[].source_station_name / destination_station_name","type":"string","description":"The train's first and last stations, named in full: Chhatrapati Shivaji Maharaj Terminus, not the booking name C SHIVAJI MAH T."},{"name":"trains[].train_type","type":"string","description":"Canonical train category."},{"name":"trains[].scheduled_arrival / scheduled_departure","type":"string(date-time)","description":"Booked times at the station, India time with +05:30. A departure that crosses midnight is dated the next day. The origin has no arrival and the destination no departure; notes.arrival and notes.departure say so."},{"name":"trains[].estimated_arrival / estimated_departure","type":"string(date-time)","description":"Latest expected times. Before the live feed forecasts the train, the booked times, with timing_basis scheduled."},{"name":"trains[].timing_basis","type":"string","description":"live: the expected times come from the live feed. scheduled: no forecast yet, so they are the booked times, with a delay of 0.","allowed":["live","scheduled"]},{"name":"trains[].platform_basis","type":"string","description":"platform_basis says where the platform comes from: announced (the live station board names it), expected (not on the board yet; the railway's running status of this run names it) or usual (neither does; the train's usual platform from the timetable, not confirmed for today). They can differ: on 2026-11-12 64114's usual platform at NDLS was 11 and its expected one 10."},{"name":"trains[].rescheduled_minutes","type":"integer","description":"How far the railway moved a train that has not started, in minutes, 15 or more: the gap between its booked and expected times that its delay does not explain. Its delay counts from the new time. Left out for a train that was not moved."},{"name":"trains[].platform_number","type":"string","description":"Reported platform. Left out until one is announced; notes.platform says so."},{"name":"trains[].arrival_delay_minutes / departure_delay_minutes","type":"integer","description":"Minutes late. 0 when the expected time is the booked one (timing_basis scheduled). For a rescheduled train, counted from the new time."},{"name":"trains[].scheduled_halt_minutes / actual_halt_minutes","type":"integer","description":"Booked and observed halt duration. actual_halt_minutes is left out until observed; notes.halt says why."},{"name":"trains[].start_date","type":"string(date)","description":"Origin departure date identifying this train run."},{"name":"trains[].status","type":"string","description":"NOT_STARTED, ON_ROUTE, AT_STATION, ARRIVED, DEPARTED, SEVERELY_DELAYED, CANCELLED, DIVERTED, or UNKNOWN."},{"name":"trains[].confidence / last_reported_at","type":"string","description":"Freshness confidence and source report time. last_reported_at is left out before the train has been reported; notes.last_reported says so."},{"name":"trains[].current_station_code / departed_current_station","type":"string / boolean","description":"Where the train is and whether it has left there. A train that has not started is at its first station, with departed_current_station false. Left out only when a running train's position is not reported."},{"name":"trains[].notes","type":"object","description":"In place of a field that has no value, why not. A time field only ever holds a real time; when one is missing, the note for its group says why. Present only with at least one note. Keys: arrival (Starts at New Delhi: departs only, no arrival), departure (Ends at New Delhi: arrives only, no departure), halt (Starts at …: no halt, Ends at …: no halt, or Has not stopped here yet), platform (Platform not announced yet; or, with platform_basis expected or usual, where the platform came from), last_reported (Not reported yet, or Not reported yet: the train has not started), position (Not started yet: at its first station, <name>, or Position not reported yet), expected (No live forecast yet: the expected times are the booked ones) and rescheduled (Rescheduled by 6 h 20 min: now departs at 01:30 on 13 Nov)."},{"name":"trains[].stop_type","type":"string","description":"ORIGIN, INTERMEDIATE, or DESTINATION at the requested station."},{"name":"trains[].cancellation","type":"object","description":"Always an object. cancellation.status is NOT_CANCELLED, PARTIALLY_CANCELLED or CANCELLED; fully_cancelled and message say the same, and from_station_code and to_station_code name the cancelled part of the route (left out when nothing is cancelled)."}],"response_example":{"success":true,"data":{"station_code":"NDLS","window_hours":8,"window":{"from":"{{date:today_ist}}T16:01:40+05:30","to":"2026-11-21T02:01:40+05:30","hours_back":2,"hours_ahead":8},"trains":[{"train_number":"14004","train_name":"Malda Town Express","extended_train_name":"Malda Town Express","source_station_code":"NDLS","destination_station_code":"MLDT","source_station_name":"New Delhi","destination_station_name":"Malda Town","train_type":"MAIL_EXPRESS","scheduled_departure":"{{date:today_ist}}T18:00:00+05:30","estimated_departure":"{{date:today_ist}}T18:00:00+05:30","departure_delay_minutes":0,"timing_basis":"live","platform_number":"15","platform_basis":"announced","start_date":"{{date:today_ist}}","status":"NOT_STARTED","current_station_code":"NDLS","departed_current_station":false,"stop_type":"ORIGIN","cancellation":{"status":"NOT_CANCELLED","fully_cancelled":false,"message":"No cancellation reported for this train"},"confidence":"high","last_reported_at":"{{date:today_ist}}T18:00:54+05:30","notes":{"arrival":"Starts at New Delhi: departs only, no arrival","halt":"Starts at New Delhi: no halt"}},{"train_number":"64426","train_name":"New Delhi - Ghaziabad EMU","extended_train_name":"New Delhi - Ghaziabad EMU","source_station_code":"NDLS","destination_station_code":"GZB","source_station_name":"New Delhi","destination_station_name":"Ghaziabad","train_type":"SUBURBAN","scheduled_departure":"{{date:today_ist}}T18:15:00+05:30","estimated_departure":"{{date:today_ist}}T18:15:00+05:30","departure_delay_minutes":0,"timing_basis":"scheduled","platform_number":"6","platform_basis":"usual","start_date":"{{date:today_ist}}","status":"NOT_STARTED","current_station_code":"NDLS","departed_current_station":false,"stop_type":"ORIGIN","cancellation":{"status":"NOT_CANCELLED","fully_cancelled":false,"message":"No cancellation reported for this train"},"confidence":"medium","notes":{"arrival":"Starts at New Delhi: departs only, no arrival","halt":"Starts at New Delhi: no halt","expected":"No live forecast yet: the expected times are the booked ones","position":"Not started yet: at its first station, New Delhi","platform":"Usual platform from the timetable: not announced for today yet","last_reported":"Not reported yet: the train has not started"}},{"train_number":"22362","train_name":"Rajendra Nagar Terminal Amrit Bharat Express","extended_train_name":"Rajendra Nagar Terminal Amrit Bharat Express","source_station_code":"NDLS","destination_station_code":"RJPB","source_station_name":"New Delhi","destination_station_name":"Rajendra Nagar Terminal","train_type":"MAIL_EXPRESS","scheduled_departure":"{{date:today_ist}}T19:10:00+05:30","estimated_departure":"2026-11-21T01:30:00+05:30","departure_delay_minutes":0,"timing_basis":"live","rescheduled_minutes":380,"platform_number":"16","platform_basis":"announced","start_date":"{{date:today_ist}}","status":"NOT_STARTED","current_station_code":"NDLS","departed_current_station":false,"stop_type":"ORIGIN","cancellation":{"status":"NOT_CANCELLED","fully_cancelled":false,"message":"No cancellation reported for this train"},"confidence":"medium","notes":{"arrival":"Starts at New Delhi: departs only, no arrival","halt":"Starts at New Delhi: no halt","position":"Not started yet: at its first station, New Delhi","rescheduled":"Rescheduled by 6 h 20 min: now departs at 01:30 on 21 Nov","last_reported":"Not reported yet: the train has not started"}},{"train_number":"64433","train_name":"Ghaziabad - New Delhi EMU","extended_train_name":"Ghaziabad - New Delhi EMU","source_station_code":"GZB","destination_station_code":"NDLS","source_station_name":"Ghaziabad","destination_station_name":"New Delhi","train_type":"SUBURBAN","scheduled_arrival":"{{date:today_ist}}T17:40:00+05:30","estimated_arrival":"{{date:today_ist}}T17:56:00+05:30","arrival_delay_minutes":16,"timing_basis":"live","platform_number":"10","platform_basis":"announced","start_date":"{{date:today_ist}}","status":"ARRIVED","current_station_code":"NDLS","stop_type":"DESTINATION","cancellation":{"status":"NOT_CANCELLED","fully_cancelled":false,"message":"No cancellation reported for this train"},"confidence":"high","last_reported_at":"{{date:today_ist}}T17:56:27+05:30","notes":{"departure":"Ends at New Delhi: arrives only, no departure","halt":"Ends at New Delhi: no halt"}}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.605Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.605Z","sources":[{"confidence":"high"}]}}},"notes":["The window runs from 2 hours before your request to window_hours after it, and window gives both ends. A train is listed when any of its times at the station, expected or booked, arriving or leaving, falls inside it, so a train that left a few minutes ago is still on the board.","NOT_STARTED means the train has not departed its origin. Scheduled timestamps alone never imply movement.","When the scheduled origin departure has passed but no live movement can be established, status is UNKNOWN rather than ON_ROUTE.","No field is null, and a time field only ever holds a real time. Where a field has no value it is left out, and the train's notes says why: a first station has no arrival, a platform is not announced yet, the train has not been reported yet. Read notes before treating a missing field as an error.","A train that has not started and has no live forecast yet shows its booked times as the expected ones, with a delay of 0 and timing_basis scheduled, and stands at its first station (current_station_code, departed_current_station false). Once the live feed forecasts it, timing_basis is live.","A train the railway has moved before it starts carries rescheduled_minutes and notes.rescheduled, and its delay counts from the new time. 22362 at NDLS was booked to leave at 19:10, expected at 01:30 the next day with a delay of 0: rescheduled_minutes 380, as the railway's own notice said (Rescheduled by 6 hr 20 min).","RailCore's train catalog wins over the live feed for a train it lists: the first and last stations come from the catalog, and so does the name when the feed named other ends. The feeds reuse numbers for other local trains: 64034 came through as SHAKURBASTI - GHAZIABAD Local, where the catalog's 64034 is the Shamli - Delhi MEMU, SMQL to DLI. Internal data-source identities and routing details are never part of the public response."],"errors":[{"status":404,"code":"STATION_NOT_FOUND","description":"No station has that code. error.message names it: Station ZZZZ not found. Check the station code. Not counted.","retryable":false,"category":"NOT_FOUND","fix":"Check the station code. Find it by name with GET /stations/search."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/live-station-board","markdown_url":"https://railcore.tech/docs/api/live-station-board.md","markdown":"# Live station board\n\nArrivals and departures from 2 hours ago to 4 or 8 hours ahead.\n\n`GET /v1/stations/{station_code}/live`\n\n- **Scope:** `live:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns one canonical station board for trains arriving at, departing from, starting at, or terminating at the station, with schedule, estimate, platform, delay, state, confidence, and report time. A train is listed when its expected or booked time at the station, arriving or leaving, falls inside the window: from 2 hours ago to window_hours ahead.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/stations/NDLS/live?window_hours=8\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"station_code\": \"NDLS\",\n    \"window_hours\": 8,\n    \"window\": {\n      \"from\": \"2026-11-20T16:01:40+05:30\",\n      \"to\": \"2026-11-21T02:01:40+05:30\",\n      \"hours_back\": 2,\n      \"hours_ahead\": 8\n    },\n    \"trains\": [\n      {\n        \"train_number\": \"14004\",\n        \"train_name\": \"Malda Town Express\",\n        \"extended_train_name\": \"Malda Town Express\",\n        \"source_station_code\": \"NDLS\",\n        \"destination_station_code\": \"MLDT\",\n        \"source_station_name\": \"New Delhi\",\n        \"destination_station_name\": \"Malda Town\",\n        \"train_type\": \"MAIL_EXPRESS\",\n        \"scheduled_departure\": \"2026-11-20T18:00:00+05:30\",\n        \"estimated_departure\": \"2026-11-20T18:00:00+05:30\",\n        \"departure_delay_minutes\": 0,\n        \"timing_basis\": \"live\",\n        \"platform_number\": \"15\",\n        \"platform_basis\": \"announced\",\n        \"start_date\": \"2026-11-20\",\n        \"status\": \"NOT_STARTED\",\n        \"current_station_code\": \"NDLS\",\n        \"departed_current_station\": false,\n        \"stop_type\": \"ORIGIN\",\n        \"cancellation\": {\n          \"status\": \"NOT_CANCELLED\",\n          \"fully_cancelled\": false,\n          \"message\": \"No cancellation reported for this train\"\n        },\n        \"confidence\": \"high\",\n        \"last_reported_at\": \"2026-11-20T18:00:54+05:30\",\n        \"notes\": {\n          \"arrival\": \"Starts at New Delhi: departs only, no arrival\",\n          \"halt\": \"Starts at New Delhi: no halt\"\n        }\n      },\n      {\n        \"train_number\": \"64426\",\n        \"train_name\": \"New Delhi - Ghaziabad EMU\",\n        \"extended_train_name\": \"New Delhi - Ghaziabad EMU\",\n        \"source_station_code\": \"NDLS\",\n        \"destination_station_code\": \"GZB\",\n        \"source_station_name\": \"New Delhi\",\n        \"destination_station_name\": \"Ghaziabad\",\n        \"train_type\": \"SUBURBAN\",\n        \"scheduled_departure\": \"2026-11-20T18:15:00+05:30\",\n        \"estimated_departure\": \"2026-11-20T18:15:00+05:30\",\n        \"departure_delay_minutes\": 0,\n        \"timing_basis\": \"scheduled\",\n        \"platform_number\": \"6\",\n        \"platform_basis\": \"usual\",\n        \"start_date\": \"2026-11-20\",\n        \"status\": \"NOT_STARTED\",\n        \"current_station_code\": \"NDLS\",\n        \"departed_current_station\": false,\n        \"stop_type\": \"ORIGIN\",\n        \"cancellation\": {\n          \"status\": \"NOT_CANCELLED\",\n          \"fully_cancelled\": false,\n          \"message\": \"No cancellation reported for this train\"\n        },\n        \"confidence\": \"medium\",\n        \"notes\": {\n          \"arrival\": \"Starts at New Delhi: departs only, no arrival\",\n          \"halt\": \"Starts at New Delhi: no halt\",\n          \"expected\": \"No live forecast yet: the expected times are the booked ones\",\n          \"position\": \"Not started yet: at its first station, New Delhi\",\n          \"platform\": \"Usual platform from the timetable: not announced for today yet\",\n          \"last_reported\": \"Not reported yet: the train has not started\"\n        }\n      },\n      {\n        \"train_number\": \"22362\",\n        \"train_name\": \"Rajendra Nagar Terminal Amrit Bharat Express\",\n        \"extended_train_name\": \"Rajendra Nagar Terminal Amrit Bharat Express\",\n        \"source_station_code\": \"NDLS\",\n        \"destination_station_code\": \"RJPB\",\n        \"source_station_name\": \"New Delhi\",\n        \"destination_station_name\": \"Rajendra Nagar Terminal\",\n        \"train_type\": \"MAIL_EXPRESS\",\n        \"scheduled_departure\": \"2026-11-20T19:10:00+05:30\",\n        \"estimated_departure\": \"2026-11-21T01:30:00+05:30\",\n        \"departure_delay_minutes\": 0,\n        \"timing_basis\": \"live\",\n        \"rescheduled_minutes\": 380,\n        \"platform_number\": \"16\",\n        \"platform_basis\": \"announced\",\n        \"start_date\": \"2026-11-20\",\n        \"status\": \"NOT_STARTED\",\n        \"current_station_code\": \"NDLS\",\n        \"departed_current_station\": false,\n        \"stop_type\": \"ORIGIN\",\n        \"cancellation\": {\n          \"status\": \"NOT_CANCELLED\",\n          \"fully_cancelled\": false,\n          \"message\": \"No cancellation reported for this train\"\n        },\n        \"confidence\": \"medium\",\n        \"notes\": {\n          \"arrival\": \"Starts at New Delhi: departs only, no arrival\",\n          \"halt\": \"Starts at New Delhi: no halt\",\n          \"position\": \"Not started yet: at its first station, New Delhi\",\n          \"rescheduled\": \"Rescheduled by 6 h 20 min: now departs at 01:30 on 21 Nov\",\n          \"last_reported\": \"Not reported yet: the train has not started\"\n        }\n      },\n      {\n        \"train_number\": \"64433\",\n        \"train_name\": \"Ghaziabad - New Delhi EMU\",\n        \"extended_train_name\": \"Ghaziabad - New Delhi EMU\",\n        \"source_station_code\": \"GZB\",\n        \"destination_station_code\": \"NDLS\",\n        \"source_station_name\": \"Ghaziabad\",\n        \"destination_station_name\": \"New Delhi\",\n        \"train_type\": \"SUBURBAN\",\n        \"scheduled_arrival\": \"2026-11-20T17:40:00+05:30\",\n        \"estimated_arrival\": \"2026-11-20T17:56:00+05:30\",\n        \"arrival_delay_minutes\": 16,\n        \"timing_basis\": \"live\",\n        \"platform_number\": \"10\",\n        \"platform_basis\": \"announced\",\n        \"start_date\": \"2026-11-20\",\n        \"status\": \"ARRIVED\",\n        \"current_station_code\": \"NDLS\",\n        \"stop_type\": \"DESTINATION\",\n        \"cancellation\": {\n          \"status\": \"NOT_CANCELLED\",\n          \"fully_cancelled\": false,\n          \"message\": \"No cancellation reported for this train\"\n        },\n        \"confidence\": \"high\",\n        \"last_reported_at\": \"2026-11-20T17:56:27+05:30\",\n        \"notes\": {\n          \"departure\": \"Ends at New Delhi: arrives only, no departure\",\n          \"halt\": \"Ends at New Delhi: no halt\"\n        }\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.605Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.605Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `live:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `station_code` string required Indian Railways station code, 1 to 6 uppercase letters or digits. Example NDLS\n\n## Query parameters\n\n- `window_hours` integer optional How far ahead the board looks. It lists trains due at the station from 2 hours ago until this many hours later, by expected or booked time. 4 or 8; any other value is read as 8. Example 8 Default 8 4 8\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `station_code` string Board station.\n- `window_hours` integer How far ahead the board looks, in hours from now: 4 or 8. Check it when you send anything other than 4 or 8.\n- `window.from / window.to` string(date-time) The bounds the board was cut to, as India-time instants with their +05:30 offset: 2 hours before the request and window_hours after it.\n- `window.hours_back / window.hours_ahead` integer How far back (always 2) and how far ahead (window_hours) the board looks.\n- `trains[].train_number / train_name` string Train number, and the name the live feed gives, often abbreviated (GKP DR EXP). When the feed named other first or last stations than RailCore's train catalog has for that number, the feed's row was for another train with the same number, and train_name is the catalog's name.\n- `trains[].extended_train_name` string The train's full name from RailCore's train catalog (Dadar Central Express). The same as train_name for a train the catalog does not list.\n- `trains[].source_station_code / destination_station_code` string The train's first and last stations, from RailCore's train catalog when it lists the train: the catalog wins over the live feed, which reuses numbers for other local trains. A train the catalog does not list keeps the feed's.\n- `trains[].source_station_name / destination_station_name` string The train's first and last stations, named in full: Chhatrapati Shivaji Maharaj Terminus, not the booking name C SHIVAJI MAH T.\n- `trains[].train_type` string Canonical train category.\n- `trains[].scheduled_arrival / scheduled_departure` string(date-time) Booked times at the station, India time with +05:30. A departure that crosses midnight is dated the next day. The origin has no arrival and the destination no departure; notes.arrival and notes.departure say so.\n- `trains[].estimated_arrival / estimated_departure` string(date-time) Latest expected times. Before the live feed forecasts the train, the booked times, with timing_basis scheduled.\n- `trains[].timing_basis` string live: the expected times come from the live feed. scheduled: no forecast yet, so they are the booked times, with a delay of 0. live scheduled\n- `trains[].platform_basis` string platform_basis says where the platform comes from: announced (the live station board names it), expected (not on the board yet; the railway's running status of this run names it) or usual (neither does; the train's usual platform from the timetable, not confirmed for today). They can differ: on 2026-11-12 64114's usual platform at NDLS was 11 and its expected one 10.\n- `trains[].rescheduled_minutes` integer How far the railway moved a train that has not started, in minutes, 15 or more: the gap between its booked and expected times that its delay does not explain. Its delay counts from the new time. Left out for a train that was not moved.\n- `trains[].platform_number` string Reported platform. Left out until one is announced; notes.platform says so.\n- `trains[].arrival_delay_minutes / departure_delay_minutes` integer Minutes late. 0 when the expected time is the booked one (timing_basis scheduled). For a rescheduled train, counted from the new time.\n- `trains[].scheduled_halt_minutes / actual_halt_minutes` integer Booked and observed halt duration. actual_halt_minutes is left out until observed; notes.halt says why.\n- `trains[].start_date` string(date) Origin departure date identifying this train run.\n- `trains[].status` string NOT_STARTED, ON_ROUTE, AT_STATION, ARRIVED, DEPARTED, SEVERELY_DELAYED, CANCELLED, DIVERTED, or UNKNOWN.\n- `trains[].confidence / last_reported_at` string Freshness confidence and source report time. last_reported_at is left out before the train has been reported; notes.last_reported says so.\n- `trains[].current_station_code / departed_current_station` string / boolean Where the train is and whether it has left there. A train that has not started is at its first station, with departed_current_station false. Left out only when a running train's position is not reported.\n- `trains[].notes` object In place of a field that has no value, why not. A time field only ever holds a real time; when one is missing, the note for its group says why. Present only with at least one note. Keys: arrival (Starts at New Delhi: departs only, no arrival), departure (Ends at New Delhi: arrives only, no departure), halt (Starts at …: no halt, Ends at …: no halt, or Has not stopped here yet), platform (Platform not announced yet; or, with platform_basis expected or usual, where the platform came from), last_reported (Not reported yet, or Not reported yet: the train has not started), position (Not started yet: at its first station, \\<name>, or Position not reported yet), expected (No live forecast yet: the expected times are the booked ones) and rescheduled (Rescheduled by 6 h 20 min: now departs at 01:30 on 13 Nov).\n- `trains[].stop_type` string ORIGIN, INTERMEDIATE, or DESTINATION at the requested station.\n- `trains[].cancellation` object Always an object. cancellation.status is NOT_CANCELLED, PARTIALLY_CANCELLED or CANCELLED; fully_cancelled and message say the same, and from_station_code and to_station_code name the cancelled part of the route (left out when nothing is cancelled).\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [STATION_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-STATION_NOT_FOUND) Do not retry unchanged No station has that code. error.message names it: Station ZZZZ not found. Check the station code. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- The window runs from 2 hours before your request to window_hours after it, and window gives both ends. A train is listed when any of its times at the station, expected or booked, arriving or leaving, falls inside it, so a train that left a few minutes ago is still on the board.\n- NOT_STARTED means the train has not departed its origin. Scheduled timestamps alone never imply movement.\n- When the scheduled origin departure has passed but no live movement can be established, status is UNKNOWN rather than ON_ROUTE.\n- No field is null, and a time field only ever holds a real time. Where a field has no value it is left out, and the train's notes says why: a first station has no arrival, a platform is not announced yet, the train has not been reported yet. Read notes before treating a missing field as an error.\n- A train that has not started and has no live forecast yet shows its booked times as the expected ones, with a delay of 0 and timing_basis scheduled, and stands at its first station (current_station_code, departed_current_station false). Once the live feed forecasts it, timing_basis is live.\n- A train the railway has moved before it starts carries rescheduled_minutes and notes.rescheduled, and its delay counts from the new time. 22362 at NDLS was booked to leave at 19:10, expected at 01:30 the next day with a delay of 0: rescheduled_minutes 380, as the railway's own notice said (Rescheduled by 6 hr 20 min).\n- RailCore's train catalog wins over the live feed for a train it lists: the first and last stations come from the catalog, and so does the name when the feed named other ends. The feeds reuse numbers for other local trains: 64034 came through as SHAKURBASTI - GHAZIABAD Local, where the catalog's 64034 is the Shamli - Delhi MEMU, SMQL to DLI. Internal data-source identities and routing details are never part of the public response.\n\nSource: https://railcore.tech/docs/api/live-station-board\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/stations/NDLS/live?window_hours=8\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/stations/NDLS/live?window_hours=8\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/stations/NDLS/live?window_hours=8\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/stations/NDLS/live?window_hours=8\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/stations/NDLS/live?window_hours=8\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/stations/NDLS/live?window_hours=8\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/stations/NDLS/live\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"window_hours=8\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/stations/NDLS/live\";\nconst params = [\n  [\"window_hours\", \"8\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/stations/NDLS/live\"\nparams = [\n    (\"window_hours\", \"8\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/stations/NDLS/live\";\n$params = [\n    [\"window_hours\", \"8\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/stations/NDLS/live\"\n\tparams := [][2]string{\n\t\t{\"window_hours\", \"8\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/stations/NDLS/live\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"window_hours\", \"8\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"search-trains","category":"Trains","method":"GET","path":"/trains/search","url_template":"https://ir.railcore.tech/v1/trains/search","title":"Search trains","summary":"Search trains by name or number.","description":"Queries RailCore's train catalog — about 13,700 trains including suburban locals, refreshed every 15 minutes — and returns ranked canonical trains. A live lookup is made only when the catalog has fewer matches than the limit, such as for a train newer than the last refresh.","scope":"trains:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"q","in":"query","type":"string","required":true,"description":"Train number or name, 1 to 80 characters.","example":"navjeevan"},{"name":"limit","in":"query","type":"integer","required":false,"description":"Maximum results.","example":"5","default":"10","minimum":1,"maximum":50}],"body_fields":[],"response_fields":[{"name":"query","type":"string","description":"Normalized query."},{"name":"limit","type":"integer","description":"Applied result limit."},{"name":"results[]","type":"Train[]","description":"Ranked train records."},{"name":"results[].train_number","type":"string","description":"Canonical train number."},{"name":"results[].train_name","type":"string","description":"Canonical train name."},{"name":"results[].display_name","type":"string","description":"Name formatted for user interfaces."},{"name":"results[].source_station_code","type":"string","description":"Origin station code."},{"name":"results[].destination_station_code","type":"string","description":"Final destination station code."},{"name":"results[].train_type","type":"string","description":"Normalized train category."},{"name":"results[].running_days","type":"RunningDay[]","description":"MON through SUN values on which the train runs."}],"response_example":{"success":true,"data":{"query":"navjeevan","limit":5,"results":[{"train_number":"12656","train_name":"Navjeevan SF Express","display_name":"12656 - Navjeevan SF Express","source_station_code":"MAS","destination_station_code":"ADI","train_type":"SF","running_days":["MON","TUE","WED","THU","FRI","SAT","SUN"]}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.605Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.605Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/search-trains","markdown_url":"https://railcore.tech/docs/api/search-trains.md","markdown":"# Search trains\n\nSearch trains by name or number.\n\n`GET /v1/trains/search`\n\n- **Scope:** `trains:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nQueries RailCore's train catalog — about 13,700 trains including suburban locals, refreshed every 15 minutes — and returns ranked canonical trains. A live lookup is made only when the catalog has fewer matches than the limit, such as for a train newer than the last refresh.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/search?q=navjeevan&limit=5\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"query\": \"navjeevan\",\n    \"limit\": 5,\n    \"results\": [\n      {\n        \"train_number\": \"12656\",\n        \"train_name\": \"Navjeevan SF Express\",\n        \"display_name\": \"12656 - Navjeevan SF Express\",\n        \"source_station_code\": \"MAS\",\n        \"destination_station_code\": \"ADI\",\n        \"train_type\": \"SF\",\n        \"running_days\": [\"MON\", \"TUE\", \"WED\", \"THU\", \"FRI\", \"SAT\", \"SUN\"]\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.605Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.605Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `trains:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `q` string required Train number or name, 1 to 80 characters. Example navjeevan\n- `limit` integer optional Maximum results. Example 5 Default 10 Range 1 to 50\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `query` string Normalized query.\n- `limit` integer Applied result limit.\n- `results[]` Train[] Ranked train records.\n  - `train_number` string Canonical train number.\n  - `train_name` string Canonical train name.\n  - `display_name` string Name formatted for user interfaces.\n  - `source_station_code` string Origin station code.\n  - `destination_station_code` string Final destination station code.\n  - `train_type` string Normalized train category.\n  - `running_days` RunningDay[] MON through SUN values on which the train runs.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/search-trains\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/search?q=navjeevan&limit=5\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/trains/search?q=navjeevan&limit=5\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/trains/search?q=navjeevan&limit=5\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/trains/search?q=navjeevan&limit=5\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/trains/search?q=navjeevan&limit=5\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/trains/search?q=navjeevan&limit=5\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/trains/search\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"limit=5&q=navjeevan\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/trains/search\";\nconst params = [\n  [\"q\", \"navjeevan\"],\n  [\"limit\", \"5\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/trains/search\"\nparams = [\n    (\"q\", \"navjeevan\"),\n    (\"limit\", \"5\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/trains/search\";\n$params = [\n    [\"q\", \"navjeevan\"],\n    [\"limit\", \"5\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/trains/search\"\n\tparams := [][2]string{\n\t\t{\"q\", \"navjeevan\"},\n\t\t{\"limit\", \"5\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/trains/search\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"q\", \"navjeevan\"},\n            new String[] {\"limit\", \"5\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"get-train","category":"Trains","method":"GET","path":"/trains/{train_number}","url_template":"https://ir.railcore.tech/v1/trains/{train_number}","title":"Get train","summary":"Resolve one canonical train record.","description":"Returns static train identity, endpoints, category, and weekly running pattern.","scope":"trains:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"path","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"}],"body_fields":[],"response_fields":[{"name":"train_number","type":"string","description":"Canonical train number."},{"name":"train_name","type":"string","description":"Canonical train name."},{"name":"display_name","type":"string","description":"Name formatted for user interfaces."},{"name":"source_station_code","type":"string","description":"Origin station code."},{"name":"destination_station_code","type":"string","description":"Final destination station code."},{"name":"train_type","type":"string","description":"Normalized train category."},{"name":"running_days","type":"RunningDay[]","description":"MON through SUN values on which the train runs."}],"response_example":{"success":true,"data":{"train_number":"12656","train_name":"Navjeevan SF Express","display_name":"12656 - Navjeevan SF Express","source_station_code":"MAS","destination_station_code":"ADI","train_type":"SF","running_days":["MON","TUE","WED","THU","FRI","SAT","SUN"]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.605Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.605Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":404,"code":"TRAIN_NOT_FOUND","description":"No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.","retryable":false,"category":"NOT_FOUND","fix":"Check the train number. Find the right one by name or number with GET /trains/search."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/get-train","markdown_url":"https://railcore.tech/docs/api/get-train.md","markdown":"# Get train\n\nResolve one canonical train record.\n\n`GET /v1/trains/{train_number}`\n\n- **Scope:** `trains:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns static train identity, endpoints, category, and weekly running pattern.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12656\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"train_name\": \"Navjeevan SF Express\",\n    \"display_name\": \"12656 - Navjeevan SF Express\",\n    \"source_station_code\": \"MAS\",\n    \"destination_station_code\": \"ADI\",\n    \"train_type\": \"SF\",\n    \"running_days\": [\"MON\", \"TUE\", \"WED\", \"THU\", \"FRI\", \"SAT\", \"SUN\"]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.605Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.605Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `trains:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number` string Canonical train number.\n- `train_name` string Canonical train name.\n- `display_name` string Name formatted for user interfaces.\n- `source_station_code` string Origin station code.\n- `destination_station_code` string Final destination station code.\n- `train_type` string Normalized train category.\n- `running_days` RunningDay[] MON through SUN values on which the train runs.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [TRAIN_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-TRAIN_NOT_FOUND) Do not retry unchanged No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/get-train\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12656\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/trains/12656\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/trains/12656\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/trains/12656\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/trains/12656\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/trains/12656\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/trains/12656\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/trains/12656\";\nconst params = [];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/trains/12656\"\nparams = []\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/trains/12656\";\n$params = [];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/trains/12656\"\n\tparams := [][2]string{}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/trains/12656\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"train-schedule","category":"Trains","method":"GET","path":"/trains/{train_number}/schedule","url_template":"https://ir.railcore.tech/v1/trains/{train_number}/schedule","title":"Train schedule","summary":"Get the full scheduled train movement.","description":"Returns route points, timings, halt data, coordinates, classes, running days, duration, and distance.","scope":"schedule:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"path","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"},{"name":"include_intermediate","in":"query","type":"boolean","required":false,"description":"Include non-stop pass-through route points.","example":"false","default":"false","allowed":["true","false"]}],"body_fields":[],"response_fields":[{"name":"train_number","type":"string","description":"Canonical train number."},{"name":"train_name","type":"string","description":"Canonical train name."},{"name":"source_station_code","type":"string","description":"Origin station code."},{"name":"destination_station_code","type":"string","description":"Final destination station code."},{"name":"running_days","type":"RunningDay[]","description":"MON through SUN values on which the train runs."},{"name":"classes","type":"ClassCode[]","description":"Classes the train carries, highest first, from RailCore's train catalog: 1A, 2A, 3A, 3E, EC, CC, FC, SL, 2S, and GS for unreserved general. Empty only for a train the catalog has no classes for."},{"name":"total_duration_minutes","type":"integer","description":"End-to-end scheduled duration."},{"name":"distance_km","type":"number","description":"End-to-end distance."},{"name":"catering / pantry","type":"boolean","description":"Whether food can be ordered on the train, and whether it carries a pantry car. Left out until RailCore has read the train's extras: the next request has them."},{"name":"rake_type","type":"string","description":"Coach build, such as LHB or ICF. Left out until RailCore has read the train's extras."},{"name":"valid_from / valid_to","type":"string(date)","description":"First and last day this timetable applies. Each is present only when the railway dated it; most timetables have no end date, so valid_to is usually left out."},{"name":"stops[].sequence","type":"integer","description":"Position in the route, starting at 1."},{"name":"stops[].station_code","type":"string","description":"Stop station code."},{"name":"stops[].station_name","type":"string","description":"Stop station name, written as the RailCore site writes it (New Delhi, Mumbai Central), not the upper-case booking name."},{"name":"stops[].stop_type","type":"string","description":"What the station is to the train. ORIGIN is where it starts and DESTINATION where it ends; HALT is a station it stops at; PASSING is one it runs through without stopping.","allowed":["ORIGIN","HALT","PASSING","DESTINATION"]},{"name":"stops[].notes","type":"object","description":"At the first and last stations only, in place of the time the train does not have there: notes.arrival at the ORIGIN (Starts at Mumbai Central: departs only, no arrival), notes.departure at the DESTINATION (Ends at New Delhi: arrives only, no departure). Left out at every other stop."},{"name":"stops[].arrival_time","type":"string","description":"Scheduled arrival in HH:mm. Left out at the ORIGIN: a train does not arrive where it starts. notes.arrival says so."},{"name":"stops[].departure_time","type":"string","description":"Scheduled departure in HH:mm. Left out at the DESTINATION: a train does not leave where it ends. notes.departure says so."},{"name":"stops[].halt_minutes","type":"integer","description":"Scheduled halt duration. 0 at the origin, the destination and a passing station."},{"name":"stops[].day","type":"integer","description":"Journey day number."},{"name":"stops[].distance_km","type":"number","description":"Distance from the origin in km. At a halt, the railway timetable's whole kilometres; at a passing station, worked out to 0.1 km."},{"name":"stops[].platform_number","type":"string","description":"Platform the train is booked on. Left out where the timetable names none, and at a station it passes without stopping."},{"name":"stops[].latitude / longitude","type":"number","description":"Station coordinates."},{"name":"stops[].typical_arrival_delay_minutes / typical_departure_delay_minutes","type":"integer","description":"Typical delay at this stop in minutes, from a fixed delay profile: the same on every date and every request, never a live reading. Left out when there is no profile for the stop, and at a station the train passes without stopping. For how late a run is now, call live train status."},{"name":"stops[].arrival_delay_minutes / departure_delay_minutes","type":"integer","deprecated":true,"description":"Deprecated aliases of typical_arrival_delay_minutes and typical_departure_delay_minutes, with the same values, and left out with them. They are not live delay. Removed no earlier than December 7, 2026, 30 days after the November 7, 2026 notice."},{"name":"stops[].is_stop","type":"boolean","description":"False for pass-through route points."}],"response_example":{"success":true,"data":{"train_number":"12656","train_name":"Navjeevan SF Express","source_station_code":"MAS","destination_station_code":"ADI","running_days":["MON","TUE","WED","THU","FRI","SAT","SUN"],"classes":["1A","2A","3A","3E","SL","GS"],"total_duration_minutes":1865,"distance_km":1880,"catering":true,"pantry":true,"rake_type":"LHB","stops":[{"sequence":1,"station_code":"MAS","station_name":"MGR Chennai Central","stop_type":"ORIGIN","notes":{"arrival":"Starts at MGR Chennai Central: departs only, no arrival"},"departure_time":"10:10","halt_minutes":0,"day":1,"distance_km":0,"platform_number":"6","is_stop":true,"typical_arrival_delay_minutes":0,"typical_departure_delay_minutes":0},{"sequence":2,"station_code":"SPE","station_name":"Sullurupeta","stop_type":"HALT","arrival_time":"11:23","departure_time":"11:25","halt_minutes":2,"day":1,"distance_km":83,"platform_number":"1","is_stop":true,"typical_arrival_delay_minutes":8,"typical_departure_delay_minutes":11},{"sequence":45,"station_code":"ADI","station_name":"Ahmedabad Junction","stop_type":"DESTINATION","notes":{"departure":"Ends at Ahmedabad Junction: arrives only, no departure"},"arrival_time":"18:00","halt_minutes":0,"day":2,"distance_km":1892,"platform_number":"5","is_stop":true,"typical_arrival_delay_minutes":19,"typical_departure_delay_minutes":0}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.605Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.605Z","sources":[{"confidence":"high"}]}}},"notes":["No field is null. One the timetable has no value for is left out: read a missing platform_number or typical delay as not known.","The ORIGIN has no arrival_time and the DESTINATION no departure_time: a train does not arrive where it starts or leave where it ends. stop_type says which a stop is.","distance_km at a halt is the railway timetable's whole kilometres. At a passing station RailCore works it out, to 0.1 km."],"errors":[{"status":404,"code":"TRAIN_NOT_FOUND","description":"No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.","retryable":false,"category":"NOT_FOUND","fix":"Check the train number. Find the right one by name or number with GET /trains/search."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/train-schedule","markdown_url":"https://railcore.tech/docs/api/train-schedule.md","markdown":"# Train schedule\n\nGet the full scheduled train movement.\n\n`GET /v1/trains/{train_number}/schedule`\n\n- **Scope:** `schedule:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns route points, timings, halt data, coordinates, classes, running days, duration, and distance.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12656/schedule?include_intermediate=false\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"train_name\": \"Navjeevan SF Express\",\n    \"source_station_code\": \"MAS\",\n    \"destination_station_code\": \"ADI\",\n    \"running_days\": [\"MON\", \"TUE\", \"WED\", \"THU\", \"FRI\", \"SAT\", \"SUN\"],\n    \"classes\": [\"1A\", \"2A\", \"3A\", \"3E\", \"SL\", \"GS\"],\n    \"total_duration_minutes\": 1865,\n    \"distance_km\": 1880,\n    \"catering\": true,\n    \"pantry\": true,\n    \"rake_type\": \"LHB\",\n    \"stops\": [\n      {\n        \"sequence\": 1,\n        \"station_code\": \"MAS\",\n        \"station_name\": \"MGR Chennai Central\",\n        \"stop_type\": \"ORIGIN\",\n        \"notes\": {\n          \"arrival\": \"Starts at MGR Chennai Central: departs only, no arrival\"\n        },\n        \"departure_time\": \"10:10\",\n        \"halt_minutes\": 0,\n        \"day\": 1,\n        \"distance_km\": 0,\n        \"platform_number\": \"6\",\n        \"is_stop\": true,\n        \"typical_arrival_delay_minutes\": 0,\n        \"typical_departure_delay_minutes\": 0\n      },\n      {\n        \"sequence\": 2,\n        \"station_code\": \"SPE\",\n        \"station_name\": \"Sullurupeta\",\n        \"stop_type\": \"HALT\",\n        \"arrival_time\": \"11:23\",\n        \"departure_time\": \"11:25\",\n        \"halt_minutes\": 2,\n        \"day\": 1,\n        \"distance_km\": 83,\n        \"platform_number\": \"1\",\n        \"is_stop\": true,\n        \"typical_arrival_delay_minutes\": 8,\n        \"typical_departure_delay_minutes\": 11\n      },\n      {\n        \"sequence\": 45,\n        \"station_code\": \"ADI\",\n        \"station_name\": \"Ahmedabad Junction\",\n        \"stop_type\": \"DESTINATION\",\n        \"notes\": {\n          \"departure\": \"Ends at Ahmedabad Junction: arrives only, no departure\"\n        },\n        \"arrival_time\": \"18:00\",\n        \"halt_minutes\": 0,\n        \"day\": 2,\n        \"distance_km\": 1892,\n        \"platform_number\": \"5\",\n        \"is_stop\": true,\n        \"typical_arrival_delay_minutes\": 19,\n        \"typical_departure_delay_minutes\": 0\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.605Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.605Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `schedule:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n\n## Query parameters\n\n- `include_intermediate` boolean optional Include non-stop pass-through route points. Example false Default false true false\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number` string Canonical train number.\n- `train_name` string Canonical train name.\n- `source_station_code` string Origin station code.\n- `destination_station_code` string Final destination station code.\n- `running_days` RunningDay[] MON through SUN values on which the train runs.\n- `classes` ClassCode[] Classes the train carries, highest first, from RailCore's train catalog: 1A, 2A, 3A, 3E, EC, CC, FC, SL, 2S, and GS for unreserved general. Empty only for a train the catalog has no classes for.\n- `total_duration_minutes` integer End-to-end scheduled duration.\n- `distance_km` number End-to-end distance.\n- `catering / pantry` boolean Whether food can be ordered on the train, and whether it carries a pantry car. Left out until RailCore has read the train's extras: the next request has them.\n- `rake_type` string Coach build, such as LHB or ICF. Left out until RailCore has read the train's extras.\n- `valid_from / valid_to` string(date) First and last day this timetable applies. Each is present only when the railway dated it; most timetables have no end date, so valid_to is usually left out.\n- `stops[].sequence` integer Position in the route, starting at 1.\n- `stops[].station_code` string Stop station code.\n- `stops[].station_name` string Stop station name, written as the RailCore site writes it (New Delhi, Mumbai Central), not the upper-case booking name.\n- `stops[].stop_type` string What the station is to the train. ORIGIN is where it starts and DESTINATION where it ends; HALT is a station it stops at; PASSING is one it runs through without stopping. ORIGIN HALT PASSING DESTINATION\n- `stops[].notes` object At the first and last stations only, in place of the time the train does not have there: notes.arrival at the ORIGIN (Starts at Mumbai Central: departs only, no arrival), notes.departure at the DESTINATION (Ends at New Delhi: arrives only, no departure). Left out at every other stop.\n- `stops[].arrival_time` string Scheduled arrival in HH:mm. Left out at the ORIGIN: a train does not arrive where it starts. notes.arrival says so.\n- `stops[].departure_time` string Scheduled departure in HH:mm. Left out at the DESTINATION: a train does not leave where it ends. notes.departure says so.\n- `stops[].halt_minutes` integer Scheduled halt duration. 0 at the origin, the destination and a passing station.\n- `stops[].day` integer Journey day number.\n- `stops[].distance_km` number Distance from the origin in km. At a halt, the railway timetable's whole kilometres; at a passing station, worked out to 0.1 km.\n- `stops[].platform_number` string Platform the train is booked on. Left out where the timetable names none, and at a station it passes without stopping.\n- `stops[].latitude / longitude` number Station coordinates.\n- `stops[].typical_arrival_delay_minutes / typical_departure_delay_minutes` integer Typical delay at this stop in minutes, from a fixed delay profile: the same on every date and every request, never a live reading. Left out when there is no profile for the stop, and at a station the train passes without stopping. For how late a run is now, call live train status.\n- `stops[].arrival_delay_minutes / departure_delay_minutes` integer deprecated Deprecated aliases of typical_arrival_delay_minutes and typical_departure_delay_minutes, with the same values, and left out with them. They are not live delay. Removed no earlier than December 7, 2026, 30 days after the November 7, 2026 notice.\n- `stops[].is_stop` boolean False for pass-through route points.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [TRAIN_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-TRAIN_NOT_FOUND) Do not retry unchanged No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- No field is null. One the timetable has no value for is left out: read a missing platform_number or typical delay as not known.\n- The ORIGIN has no arrival_time and the DESTINATION no departure_time: a train does not arrive where it starts or leave where it ends. stop_type says which a stop is.\n- distance_km at a halt is the railway timetable's whole kilometres. At a passing station RailCore works it out, to 0.1 km.\n\nSource: https://railcore.tech/docs/api/train-schedule\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12656/schedule?include_intermediate=false\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/trains/12656/schedule?include_intermediate=false\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/trains/12656/schedule?include_intermediate=false\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/trains/12656/schedule?include_intermediate=false\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/trains/12656/schedule?include_intermediate=false\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/trains/12656/schedule?include_intermediate=false\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/trains/12656/schedule\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"include_intermediate=false\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/trains/12656/schedule\";\nconst params = [\n  [\"include_intermediate\", \"false\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/trains/12656/schedule\"\nparams = [\n    (\"include_intermediate\", \"false\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/trains/12656/schedule\";\n$params = [\n    [\"include_intermediate\", \"false\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/trains/12656/schedule\"\n\tparams := [][2]string{\n\t\t{\"include_intermediate\", \"false\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/trains/12656/schedule\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"include_intermediate\", \"false\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"train-stops","category":"Trains","method":"GET","path":"/trains/{train_number}/stops","url_template":"https://ir.railcore.tech/v1/trains/{train_number}/stops","title":"Booking stops","summary":"Get booking-relevant stops only.","description":"Returns the schedule subset where is_stop is true.","scope":"schedule:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"path","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"}],"body_fields":[],"response_fields":[{"name":"train_number","type":"string","description":"Canonical train number."},{"name":"train_name","type":"string","description":"Canonical train name."},{"name":"source_station_code","type":"string","description":"Origin station code."},{"name":"destination_station_code","type":"string","description":"Final destination station code."},{"name":"running_days","type":"RunningDay[]","description":"MON through SUN values on which the train runs."},{"name":"classes","type":"ClassCode[]","description":"Classes the train carries, highest first, from RailCore's train catalog: 1A, 2A, 3A, 3E, EC, CC, FC, SL, 2S, and GS for unreserved general. Empty only for a train the catalog has no classes for."},{"name":"total_duration_minutes","type":"integer","description":"End-to-end scheduled duration."},{"name":"distance_km","type":"number","description":"End-to-end distance."},{"name":"catering / pantry","type":"boolean","description":"Whether food can be ordered on the train, and whether it carries a pantry car. Left out until RailCore has read the train's extras: the next request has them."},{"name":"rake_type","type":"string","description":"Coach build, such as LHB or ICF. Left out until RailCore has read the train's extras."},{"name":"valid_from / valid_to","type":"string(date)","description":"First and last day this timetable applies. Each is present only when the railway dated it; most timetables have no end date, so valid_to is usually left out."},{"name":"stops[].sequence","type":"integer","description":"Position in the route, starting at 1."},{"name":"stops[].station_code","type":"string","description":"Stop station code."},{"name":"stops[].station_name","type":"string","description":"Stop station name, written as the RailCore site writes it (New Delhi, Mumbai Central), not the upper-case booking name."},{"name":"stops[].stop_type","type":"string","description":"What the station is to the train. ORIGIN is where it starts and DESTINATION where it ends; HALT is a station it stops at; PASSING is one it runs through without stopping.","allowed":["ORIGIN","HALT","PASSING","DESTINATION"]},{"name":"stops[].notes","type":"object","description":"At the first and last stations only, in place of the time the train does not have there: notes.arrival at the ORIGIN (Starts at Mumbai Central: departs only, no arrival), notes.departure at the DESTINATION (Ends at New Delhi: arrives only, no departure). Left out at every other stop."},{"name":"stops[].arrival_time","type":"string","description":"Scheduled arrival in HH:mm. Left out at the ORIGIN: a train does not arrive where it starts. notes.arrival says so."},{"name":"stops[].departure_time","type":"string","description":"Scheduled departure in HH:mm. Left out at the DESTINATION: a train does not leave where it ends. notes.departure says so."},{"name":"stops[].halt_minutes","type":"integer","description":"Scheduled halt duration. 0 at the origin, the destination and a passing station."},{"name":"stops[].day","type":"integer","description":"Journey day number."},{"name":"stops[].distance_km","type":"number","description":"Distance from the origin in km. At a halt, the railway timetable's whole kilometres; at a passing station, worked out to 0.1 km."},{"name":"stops[].platform_number","type":"string","description":"Platform the train is booked on. Left out where the timetable names none, and at a station it passes without stopping."},{"name":"stops[].latitude / longitude","type":"number","description":"Station coordinates."},{"name":"stops[].typical_arrival_delay_minutes / typical_departure_delay_minutes","type":"integer","description":"Typical delay at this stop in minutes, from a fixed delay profile: the same on every date and every request, never a live reading. Left out when there is no profile for the stop, and at a station the train passes without stopping. For how late a run is now, call live train status."},{"name":"stops[].arrival_delay_minutes / departure_delay_minutes","type":"integer","deprecated":true,"description":"Deprecated aliases of typical_arrival_delay_minutes and typical_departure_delay_minutes, with the same values, and left out with them. They are not live delay. Removed no earlier than December 7, 2026, 30 days after the November 7, 2026 notice."},{"name":"stops[].is_stop","type":"boolean","description":"False for pass-through route points."}],"response_example":{"success":true,"data":{"train_number":"12656","train_name":"Navjeevan SF Express","classes":["1A","2A","3A","3E","SL","GS"],"catering":true,"pantry":true,"rake_type":"LHB","stops":[{"sequence":1,"station_code":"MAS","station_name":"MGR Chennai Central","stop_type":"ORIGIN","notes":{"arrival":"Starts at MGR Chennai Central: departs only, no arrival"},"departure_time":"10:10","halt_minutes":0,"day":1,"distance_km":0,"platform_number":"6","is_stop":true}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.605Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.605Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":404,"code":"TRAIN_NOT_FOUND","description":"No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.","retryable":false,"category":"NOT_FOUND","fix":"Check the train number. Find the right one by name or number with GET /trains/search."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/train-stops","markdown_url":"https://railcore.tech/docs/api/train-stops.md","markdown":"# Booking stops\n\nGet booking-relevant stops only.\n\n`GET /v1/trains/{train_number}/stops`\n\n- **Scope:** `schedule:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns the schedule subset where is_stop is true.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12656/stops\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"train_name\": \"Navjeevan SF Express\",\n    \"classes\": [\"1A\", \"2A\", \"3A\", \"3E\", \"SL\", \"GS\"],\n    \"catering\": true,\n    \"pantry\": true,\n    \"rake_type\": \"LHB\",\n    \"stops\": [\n      {\n        \"sequence\": 1,\n        \"station_code\": \"MAS\",\n        \"station_name\": \"MGR Chennai Central\",\n        \"stop_type\": \"ORIGIN\",\n        \"notes\": {\n          \"arrival\": \"Starts at MGR Chennai Central: departs only, no arrival\"\n        },\n        \"departure_time\": \"10:10\",\n        \"halt_minutes\": 0,\n        \"day\": 1,\n        \"distance_km\": 0,\n        \"platform_number\": \"6\",\n        \"is_stop\": true\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.605Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.605Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `schedule:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number` string Canonical train number.\n- `train_name` string Canonical train name.\n- `source_station_code` string Origin station code.\n- `destination_station_code` string Final destination station code.\n- `running_days` RunningDay[] MON through SUN values on which the train runs.\n- `classes` ClassCode[] Classes the train carries, highest first, from RailCore's train catalog: 1A, 2A, 3A, 3E, EC, CC, FC, SL, 2S, and GS for unreserved general. Empty only for a train the catalog has no classes for.\n- `total_duration_minutes` integer End-to-end scheduled duration.\n- `distance_km` number End-to-end distance.\n- `catering / pantry` boolean Whether food can be ordered on the train, and whether it carries a pantry car. Left out until RailCore has read the train's extras: the next request has them.\n- `rake_type` string Coach build, such as LHB or ICF. Left out until RailCore has read the train's extras.\n- `valid_from / valid_to` string(date) First and last day this timetable applies. Each is present only when the railway dated it; most timetables have no end date, so valid_to is usually left out.\n- `stops[].sequence` integer Position in the route, starting at 1.\n- `stops[].station_code` string Stop station code.\n- `stops[].station_name` string Stop station name, written as the RailCore site writes it (New Delhi, Mumbai Central), not the upper-case booking name.\n- `stops[].stop_type` string What the station is to the train. ORIGIN is where it starts and DESTINATION where it ends; HALT is a station it stops at; PASSING is one it runs through without stopping. ORIGIN HALT PASSING DESTINATION\n- `stops[].notes` object At the first and last stations only, in place of the time the train does not have there: notes.arrival at the ORIGIN (Starts at Mumbai Central: departs only, no arrival), notes.departure at the DESTINATION (Ends at New Delhi: arrives only, no departure). Left out at every other stop.\n- `stops[].arrival_time` string Scheduled arrival in HH:mm. Left out at the ORIGIN: a train does not arrive where it starts. notes.arrival says so.\n- `stops[].departure_time` string Scheduled departure in HH:mm. Left out at the DESTINATION: a train does not leave where it ends. notes.departure says so.\n- `stops[].halt_minutes` integer Scheduled halt duration. 0 at the origin, the destination and a passing station.\n- `stops[].day` integer Journey day number.\n- `stops[].distance_km` number Distance from the origin in km. At a halt, the railway timetable's whole kilometres; at a passing station, worked out to 0.1 km.\n- `stops[].platform_number` string Platform the train is booked on. Left out where the timetable names none, and at a station it passes without stopping.\n- `stops[].latitude / longitude` number Station coordinates.\n- `stops[].typical_arrival_delay_minutes / typical_departure_delay_minutes` integer Typical delay at this stop in minutes, from a fixed delay profile: the same on every date and every request, never a live reading. Left out when there is no profile for the stop, and at a station the train passes without stopping. For how late a run is now, call live train status.\n- `stops[].arrival_delay_minutes / departure_delay_minutes` integer deprecated Deprecated aliases of typical_arrival_delay_minutes and typical_departure_delay_minutes, with the same values, and left out with them. They are not live delay. Removed no earlier than December 7, 2026, 30 days after the November 7, 2026 notice.\n- `stops[].is_stop` boolean False for pass-through route points.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [TRAIN_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-TRAIN_NOT_FOUND) Do not retry unchanged No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/train-stops\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12656/stops\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/trains/12656/stops\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/trains/12656/stops\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/trains/12656/stops\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/trains/12656/stops\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/trains/12656/stops\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/trains/12656/stops\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/trains/12656/stops\";\nconst params = [];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/trains/12656/stops\"\nparams = []\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/trains/12656/stops\";\n$params = [];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/trains/12656/stops\"\n\tparams := [][2]string{}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/trains/12656/stops\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"train-route","category":"Trains","method":"GET","path":"/trains/{train_number}/route","url_template":"https://ir.railcore.tech/v1/trains/{train_number}/route","title":"Full train route","summary":"Get stops and pass-through stations.","description":"Returns the complete route, including points where the train does not stop. A passing point (stop_type PASSING) has its booked times, distance and coordinates; it has no platform or typical delay, so those fields are left out there. Train-level fields (classes, catering, pantry, rake type) and each halt's platform and typical delays are the same as on the schedule.","scope":"schedule:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"path","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"}],"body_fields":[],"response_fields":[{"name":"train_number","type":"string","description":"Canonical train number."},{"name":"train_name","type":"string","description":"Canonical train name."},{"name":"source_station_code","type":"string","description":"Origin station code."},{"name":"destination_station_code","type":"string","description":"Final destination station code."},{"name":"running_days","type":"RunningDay[]","description":"MON through SUN values on which the train runs."},{"name":"classes","type":"ClassCode[]","description":"Classes the train carries, highest first, from RailCore's train catalog: 1A, 2A, 3A, 3E, EC, CC, FC, SL, 2S, and GS for unreserved general. Empty only for a train the catalog has no classes for."},{"name":"total_duration_minutes","type":"integer","description":"End-to-end scheduled duration."},{"name":"distance_km","type":"number","description":"End-to-end distance."},{"name":"catering / pantry","type":"boolean","description":"Whether food can be ordered on the train, and whether it carries a pantry car. Left out until RailCore has read the train's extras: the next request has them."},{"name":"rake_type","type":"string","description":"Coach build, such as LHB or ICF. Left out until RailCore has read the train's extras."},{"name":"valid_from / valid_to","type":"string(date)","description":"First and last day this timetable applies. Each is present only when the railway dated it; most timetables have no end date, so valid_to is usually left out."},{"name":"stops[].sequence","type":"integer","description":"Position in the route, starting at 1."},{"name":"stops[].station_code","type":"string","description":"Stop station code."},{"name":"stops[].station_name","type":"string","description":"Stop station name, written as the RailCore site writes it (New Delhi, Mumbai Central), not the upper-case booking name."},{"name":"stops[].stop_type","type":"string","description":"What the station is to the train. ORIGIN is where it starts and DESTINATION where it ends; HALT is a station it stops at; PASSING is one it runs through without stopping.","allowed":["ORIGIN","HALT","PASSING","DESTINATION"]},{"name":"stops[].notes","type":"object","description":"At the first and last stations only, in place of the time the train does not have there: notes.arrival at the ORIGIN (Starts at Mumbai Central: departs only, no arrival), notes.departure at the DESTINATION (Ends at New Delhi: arrives only, no departure). Left out at every other stop."},{"name":"stops[].arrival_time","type":"string","description":"Scheduled arrival in HH:mm. Left out at the ORIGIN: a train does not arrive where it starts. notes.arrival says so."},{"name":"stops[].departure_time","type":"string","description":"Scheduled departure in HH:mm. Left out at the DESTINATION: a train does not leave where it ends. notes.departure says so."},{"name":"stops[].halt_minutes","type":"integer","description":"Scheduled halt duration. 0 at the origin, the destination and a passing station."},{"name":"stops[].day","type":"integer","description":"Journey day number."},{"name":"stops[].distance_km","type":"number","description":"Distance from the origin in km. At a halt, the railway timetable's whole kilometres; at a passing station, worked out to 0.1 km."},{"name":"stops[].platform_number","type":"string","description":"Platform the train is booked on. Left out where the timetable names none, and at a station it passes without stopping."},{"name":"stops[].latitude / longitude","type":"number","description":"Station coordinates."},{"name":"stops[].typical_arrival_delay_minutes / typical_departure_delay_minutes","type":"integer","description":"Typical delay at this stop in minutes, from a fixed delay profile: the same on every date and every request, never a live reading. Left out when there is no profile for the stop, and at a station the train passes without stopping. For how late a run is now, call live train status."},{"name":"stops[].arrival_delay_minutes / departure_delay_minutes","type":"integer","deprecated":true,"description":"Deprecated aliases of typical_arrival_delay_minutes and typical_departure_delay_minutes, with the same values, and left out with them. They are not live delay. Removed no earlier than December 7, 2026, 30 days after the November 7, 2026 notice."},{"name":"stops[].is_stop","type":"boolean","description":"False for pass-through route points."}],"response_example":{"success":true,"data":{"train_number":"12656","train_name":"Navjeevan SF Express","classes":["1A","2A","3A","3E","SL","GS"],"catering":true,"pantry":true,"rake_type":"LHB","stops":[{"sequence":1,"station_code":"MAS","station_name":"MGR Chennai Central","stop_type":"ORIGIN","notes":{"arrival":"Starts at MGR Chennai Central: departs only, no arrival"},"departure_time":"10:10","halt_minutes":0,"day":1,"distance_km":0,"platform_number":"6","is_stop":true},{"sequence":2,"station_code":"BBQ","station_name":"Basin Bridge Junction","stop_type":"PASSING","arrival_time":"10:11","departure_time":"10:11","halt_minutes":0,"day":1,"distance_km":2.1,"latitude":13.102361,"longitude":80.271221,"is_stop":false}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.605Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.605Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":404,"code":"TRAIN_NOT_FOUND","description":"No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.","retryable":false,"category":"NOT_FOUND","fix":"Check the train number. Find the right one by name or number with GET /trains/search."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/train-route","markdown_url":"https://railcore.tech/docs/api/train-route.md","markdown":"# Full train route\n\nGet stops and pass-through stations.\n\n`GET /v1/trains/{train_number}/route`\n\n- **Scope:** `schedule:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns the complete route, including points where the train does not stop. A passing point (stop_type PASSING) has its booked times, distance and coordinates; it has no platform or typical delay, so those fields are left out there. Train-level fields (classes, catering, pantry, rake type) and each halt's platform and typical delays are the same as on the schedule.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12656/route\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"train_name\": \"Navjeevan SF Express\",\n    \"classes\": [\"1A\", \"2A\", \"3A\", \"3E\", \"SL\", \"GS\"],\n    \"catering\": true,\n    \"pantry\": true,\n    \"rake_type\": \"LHB\",\n    \"stops\": [\n      {\n        \"sequence\": 1,\n        \"station_code\": \"MAS\",\n        \"station_name\": \"MGR Chennai Central\",\n        \"stop_type\": \"ORIGIN\",\n        \"notes\": {\n          \"arrival\": \"Starts at MGR Chennai Central: departs only, no arrival\"\n        },\n        \"departure_time\": \"10:10\",\n        \"halt_minutes\": 0,\n        \"day\": 1,\n        \"distance_km\": 0,\n        \"platform_number\": \"6\",\n        \"is_stop\": true\n      },\n      {\n        \"sequence\": 2,\n        \"station_code\": \"BBQ\",\n        \"station_name\": \"Basin Bridge Junction\",\n        \"stop_type\": \"PASSING\",\n        \"arrival_time\": \"10:11\",\n        \"departure_time\": \"10:11\",\n        \"halt_minutes\": 0,\n        \"day\": 1,\n        \"distance_km\": 2.1,\n        \"latitude\": 13.102361,\n        \"longitude\": 80.271221,\n        \"is_stop\": false\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.605Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.605Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `schedule:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number` string Canonical train number.\n- `train_name` string Canonical train name.\n- `source_station_code` string Origin station code.\n- `destination_station_code` string Final destination station code.\n- `running_days` RunningDay[] MON through SUN values on which the train runs.\n- `classes` ClassCode[] Classes the train carries, highest first, from RailCore's train catalog: 1A, 2A, 3A, 3E, EC, CC, FC, SL, 2S, and GS for unreserved general. Empty only for a train the catalog has no classes for.\n- `total_duration_minutes` integer End-to-end scheduled duration.\n- `distance_km` number End-to-end distance.\n- `catering / pantry` boolean Whether food can be ordered on the train, and whether it carries a pantry car. Left out until RailCore has read the train's extras: the next request has them.\n- `rake_type` string Coach build, such as LHB or ICF. Left out until RailCore has read the train's extras.\n- `valid_from / valid_to` string(date) First and last day this timetable applies. Each is present only when the railway dated it; most timetables have no end date, so valid_to is usually left out.\n- `stops[].sequence` integer Position in the route, starting at 1.\n- `stops[].station_code` string Stop station code.\n- `stops[].station_name` string Stop station name, written as the RailCore site writes it (New Delhi, Mumbai Central), not the upper-case booking name.\n- `stops[].stop_type` string What the station is to the train. ORIGIN is where it starts and DESTINATION where it ends; HALT is a station it stops at; PASSING is one it runs through without stopping. ORIGIN HALT PASSING DESTINATION\n- `stops[].notes` object At the first and last stations only, in place of the time the train does not have there: notes.arrival at the ORIGIN (Starts at Mumbai Central: departs only, no arrival), notes.departure at the DESTINATION (Ends at New Delhi: arrives only, no departure). Left out at every other stop.\n- `stops[].arrival_time` string Scheduled arrival in HH:mm. Left out at the ORIGIN: a train does not arrive where it starts. notes.arrival says so.\n- `stops[].departure_time` string Scheduled departure in HH:mm. Left out at the DESTINATION: a train does not leave where it ends. notes.departure says so.\n- `stops[].halt_minutes` integer Scheduled halt duration. 0 at the origin, the destination and a passing station.\n- `stops[].day` integer Journey day number.\n- `stops[].distance_km` number Distance from the origin in km. At a halt, the railway timetable's whole kilometres; at a passing station, worked out to 0.1 km.\n- `stops[].platform_number` string Platform the train is booked on. Left out where the timetable names none, and at a station it passes without stopping.\n- `stops[].latitude / longitude` number Station coordinates.\n- `stops[].typical_arrival_delay_minutes / typical_departure_delay_minutes` integer Typical delay at this stop in minutes, from a fixed delay profile: the same on every date and every request, never a live reading. Left out when there is no profile for the stop, and at a station the train passes without stopping. For how late a run is now, call live train status.\n- `stops[].arrival_delay_minutes / departure_delay_minutes` integer deprecated Deprecated aliases of typical_arrival_delay_minutes and typical_departure_delay_minutes, with the same values, and left out with them. They are not live delay. Removed no earlier than December 7, 2026, 30 days after the November 7, 2026 notice.\n- `stops[].is_stop` boolean False for pass-through route points.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [TRAIN_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-TRAIN_NOT_FOUND) Do not retry unchanged No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/train-route\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12656/route\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/trains/12656/route\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/trains/12656/route\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/trains/12656/route\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/trains/12656/route\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/trains/12656/route\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/trains/12656/route\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/trains/12656/route\";\nconst params = [];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/trains/12656/route\"\nparams = []\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/trains/12656/route\";\n$params = [];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/trains/12656/route\"\n\tparams := [][2]string{}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/trains/12656/route\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"coach-position","category":"Trains","method":"GET","path":"/trains/{train_number}/coach-position","url_template":"https://ir.railcore.tech/v1/trains/{train_number}/coach-position","title":"Coach position","summary":"Get the rake from the front: the locomotive, then every coach, with the train's name, formation and class counts.","description":"Returns the train's rake in order from the front, with the train's name, its first and last stations, the number of coaches, the formation written out, the coaches counted by class, and the stations where the rake reverses. A loco-hauled train's list always starts with the locomotive, and its coaches count from 2; every coach follows with its label, its class in code and in words, what kind of vehicle it is, and its place. A self-propelled set (Vande Bharat, MEMU, DEMU, EMU) has no separate locomotive, so its list starts with the first coach at position 1. A push-pull train (an Amrit Bharat Express, for one) has a locomotive at each end: its list ends with a second locomotive row, and push_pull is true. Power cars (LPR, EOG) are listed in their places, so positions run without a gap.","scope":"schedule:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"path","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"}],"body_fields":[],"response_fields":[{"name":"train_number","type":"string","description":"Train number."},{"name":"train_name / train_type","type":"string","description":"The train's name and category code, such as SF or RAJDHANI, from RailCore's train catalog."},{"name":"source_station / destination_station","type":"object","description":"The train's first and last stations, each as { code, name }, with the name written out in full."},{"name":"rake_type","type":"string","description":"Coach build. TRAINSET for a self-propelled set.","allowed":["LHB","ICF","TRAINSET"]},{"name":"has_locomotive","type":"boolean","description":"True for a loco-hauled train, whose list starts with the locomotive. False for a self-propelled set, which has no locomotive row."},{"name":"locomotives","type":"integer","description":"Locomotive rows in the list: 0 for a self-propelled set, 1 for a loco-hauled train, 2 for a push-pull train.","allowed":["0","1","2"]},{"name":"push_pull","type":"boolean","description":"True for a push-pull train: a locomotive at each end of the rake, so the list starts and ends with a locomotive row. Indian Railways publishes no list of such trains; RailCore marks one on evidence and says which in push_pull_basis. A train that is not marked may still be worked push-pull."},{"name":"push_pull_basis","type":"string","description":"Present when push_pull is true: what the mark rests on. train_design: the train is an Amrit Bharat Express, built as a push-pull rake. railway_announcement: the railway announced push-pull working for this train. rake_composition: the train's coach composition lists a locomotive at each end.","allowed":["train_design","railway_announcement","rake_composition"]},{"name":"composition_basis","type":"string","description":"Where the coach list comes from. primary: RailCore's main coach-composition source. secondary: the main source publishes no composition for this train, so the list is a second source's; it can lag a recent change to the rake, and the answer's confidence is medium.","allowed":["primary","secondary"]},{"name":"total_coaches","type":"integer","description":"Coaches in the list, not counting locomotives or power cars."},{"name":"power_cars","type":"integer","description":"Power cars in the list (LPR, EOG), each a row with coach_type POWER_CAR. 0 on a train with none."},{"name":"total_vehicles","type":"integer","description":"Every row in the list: locomotives, coaches and power cars."},{"name":"formation","type":"string","description":"The rake written out from the front, for example ENG-SLRD-GEN-S5-S4-PC-B1-A1-H1-GEN."},{"name":"class_summary[]","type":"object[]","description":"The rake counted by class, in rake order: class_code, class_name, coach_type and coaches (how many). On a loco-hauled train the first entry is the locomotive (class_code LOCO, coaches 1; 2 on a push-pull train). Power cars are counted too, so the counts add up to total_vehicles."},{"name":"reversal_stations[]","type":"object[]","description":"Stations where the engine changes ends, so the coach order runs the other way from there on: station_code and station_name. Empty when RailCore knows of none."},{"name":"coach_position[].sequence","type":"integer","description":"Row number in the list, from 1."},{"name":"coach_position[].coach_name","type":"string","description":"Coach label such as B1. ENG for the locomotive."},{"name":"coach_position[].class_code","type":"string","description":"The coach's class (a ClassCode value such as 3A, SL or GS), LOCO for the locomotive, or the vehicle's own code where it has no travel class (LPR or EOG for a power car, VP for a parcel van)."},{"name":"coach_position[].class_name","type":"string","description":"The class or vehicle in words: Third AC, Sleeper, General (unreserved), Pantry car, Power car, Generator car, Locomotive."},{"name":"coach_position[].coach_type","type":"string","description":"What the vehicle is for. RESERVED is a coach whose seats or berths are booked in a class; UNRESERVED is a general coach.","allowed":["LOCOMOTIVE","RESERVED","UNRESERVED","PANTRY","LUGGAGE_BRAKE","POWER_CAR","PARCEL","OTHER"]},{"name":"coach_position[].position_from_engine","type":"integer","description":"Place in the rake counted from the front. The locomotive is 1, the vehicle behind it 2. Every vehicle is listed, power cars included, so the numbers run without a gap."},{"name":"coach_position[].is_locomotive","type":"boolean","description":"True for a locomotive row, false for a coach."},{"name":"coach_position[].locomotive_end","type":"string","description":"On a locomotive row only: which end of the rake it is at. A push-pull train has one of each.","allowed":["FRONT","REAR"]}],"response_example":{"success":true,"data":{"train_number":"12656","train_name":"Navjeevan SF Express","train_type":"SF","source_station":{"code":"MAS","name":"MGR Chennai Central"},"destination_station":{"code":"ADI","name":"Ahmedabad Junction"},"rake_type":"LHB","has_locomotive":true,"locomotives":1,"push_pull":false,"composition_basis":"primary","total_coaches":21,"power_cars":0,"total_vehicles":22,"formation":"ENG-SLRD-GEN-GEN-S5-S4-S3-PC-S2-S1-M3-M2-M1-B4-B3-B2-B1-A2-A1-H1-GEN-GEN","class_summary":[{"class_code":"LOCO","class_name":"Locomotive","coach_type":"LOCOMOTIVE","coaches":1},{"class_code":"SLR","class_name":"Luggage, brake & Divyangjan van","coach_type":"LUGGAGE_BRAKE","coaches":1},{"class_code":"GS","class_name":"General (unreserved)","coach_type":"UNRESERVED","coaches":4},{"class_code":"SL","class_name":"Sleeper","coach_type":"RESERVED","coaches":5},{"class_code":"PC","class_name":"Pantry car","coach_type":"PANTRY","coaches":1},{"class_code":"3E","class_name":"AC Economy","coach_type":"RESERVED","coaches":3},{"class_code":"3A","class_name":"Third AC","coach_type":"RESERVED","coaches":4},{"class_code":"2A","class_name":"Second AC","coach_type":"RESERVED","coaches":2},{"class_code":"1A","class_name":"First AC","coach_type":"RESERVED","coaches":1}],"reversal_stations":[],"coach_position":[{"sequence":1,"coach_name":"ENG","class_code":"LOCO","class_name":"Locomotive","coach_type":"LOCOMOTIVE","position_from_engine":1,"is_locomotive":true,"locomotive_end":"FRONT"},{"sequence":2,"coach_name":"SLRD","class_code":"SLR","class_name":"Luggage, brake & Divyangjan van","coach_type":"LUGGAGE_BRAKE","position_from_engine":2,"is_locomotive":false},{"sequence":3,"coach_name":"GEN","class_code":"GS","class_name":"General (unreserved)","coach_type":"UNRESERVED","position_from_engine":3,"is_locomotive":false},{"sequence":4,"coach_name":"GEN","class_code":"GS","class_name":"General (unreserved)","coach_type":"UNRESERVED","position_from_engine":4,"is_locomotive":false},{"sequence":5,"coach_name":"S5","class_code":"SL","class_name":"Sleeper","coach_type":"RESERVED","position_from_engine":5,"is_locomotive":false}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.605Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.605Z","sources":[{"confidence":"high"}]}}},"notes":["To draw only the passenger coaches, skip the rows where is_locomotive is true or coach_type is POWER_CAR.","A power car row reads { class_code: \"LPR\", class_name: \"Power car\", coach_type: \"POWER_CAR\" }, or EOG and Generator car. Until November 12, 2026 power cars were left out, leaving a gap in position_from_engine.","A push-pull train answers push_pull: true, locomotives: 2 and a formation that ends with ENG; its last row is { coach_name: \"ENG\", is_locomotive: true, locomotive_end: \"REAR\" }.","The train's own details (train_name, train_type, the two stations, rake_type) are left out on the rare request where RailCore could not read its catalog in time; the rake is complete either way.","Berth counts and berth layouts are not part of this answer.","A train with no coach composition at any source RailCore reads is a 404 COACH_POSITION_NOT_FOUND, not counted and not worth retrying soon. A composition from the second source says composition_basis: \"secondary\"."],"errors":[{"status":404,"code":"TRAIN_NOT_FOUND","description":"No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.","retryable":false,"category":"NOT_FOUND","fix":"Check the train number. Find the right one by name or number with GET /trains/search."},{"status":404,"code":"COACH_POSITION_NOT_FOUND","description":"The train exists, but no source RailCore reads publishes its coach composition. error.message names it: No coach composition is published for train 12345. Not counted.","retryable":false,"category":"NOT_FOUND","fix":"No source publishes this train's coach composition. Retrying soon will not help; try again on another day."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/coach-position","markdown_url":"https://railcore.tech/docs/api/coach-position.md","markdown":"# Coach position\n\nGet the rake from the front: the locomotive, then every coach, with the train's name, formation and class counts.\n\n`GET /v1/trains/{train_number}/coach-position`\n\n- **Scope:** `schedule:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns the train's rake in order from the front, with the train's name, its first and last stations, the number of coaches, the formation written out, the coaches counted by class, and the stations where the rake reverses. A loco-hauled train's list always starts with the locomotive, and its coaches count from 2; every coach follows with its label, its class in code and in words, what kind of vehicle it is, and its place. A self-propelled set (Vande Bharat, MEMU, DEMU, EMU) has no separate locomotive, so its list starts with the first coach at position 1. A push-pull train (an Amrit Bharat Express, for one) has a locomotive at each end: its list ends with a second locomotive row, and push_pull is true. Power cars (LPR, EOG) are listed in their places, so positions run without a gap.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12656/coach-position\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"train_name\": \"Navjeevan SF Express\",\n    \"train_type\": \"SF\",\n    \"source_station\": {\n      \"code\": \"MAS\",\n      \"name\": \"MGR Chennai Central\"\n    },\n    \"destination_station\": {\n      \"code\": \"ADI\",\n      \"name\": \"Ahmedabad Junction\"\n    },\n    \"rake_type\": \"LHB\",\n    \"has_locomotive\": true,\n    \"locomotives\": 1,\n    \"push_pull\": false,\n    \"composition_basis\": \"primary\",\n    \"total_coaches\": 21,\n    \"power_cars\": 0,\n    \"total_vehicles\": 22,\n    \"formation\": \"ENG-SLRD-GEN-GEN-S5-S4-S3-PC-S2-S1-M3-M2-M1-B4-B3-B2-B1-A2-A1-H1-GEN-GEN\",\n    \"class_summary\": [\n      {\n        \"class_code\": \"LOCO\",\n        \"class_name\": \"Locomotive\",\n        \"coach_type\": \"LOCOMOTIVE\",\n        \"coaches\": 1\n      },\n      {\n        \"class_code\": \"SLR\",\n        \"class_name\": \"Luggage, brake & Divyangjan van\",\n        \"coach_type\": \"LUGGAGE_BRAKE\",\n        \"coaches\": 1\n      },\n      {\n        \"class_code\": \"GS\",\n        \"class_name\": \"General (unreserved)\",\n        \"coach_type\": \"UNRESERVED\",\n        \"coaches\": 4\n      },\n      {\n        \"class_code\": \"SL\",\n        \"class_name\": \"Sleeper\",\n        \"coach_type\": \"RESERVED\",\n        \"coaches\": 5\n      },\n      {\n        \"class_code\": \"PC\",\n        \"class_name\": \"Pantry car\",\n        \"coach_type\": \"PANTRY\",\n        \"coaches\": 1\n      },\n      {\n        \"class_code\": \"3E\",\n        \"class_name\": \"AC Economy\",\n        \"coach_type\": \"RESERVED\",\n        \"coaches\": 3\n      },\n      {\n        \"class_code\": \"3A\",\n        \"class_name\": \"Third AC\",\n        \"coach_type\": \"RESERVED\",\n        \"coaches\": 4\n      },\n      {\n        \"class_code\": \"2A\",\n        \"class_name\": \"Second AC\",\n        \"coach_type\": \"RESERVED\",\n        \"coaches\": 2\n      },\n      {\n        \"class_code\": \"1A\",\n        \"class_name\": \"First AC\",\n        \"coach_type\": \"RESERVED\",\n        \"coaches\": 1\n      }\n    ],\n    \"reversal_stations\": [],\n    \"coach_position\": [\n      {\n        \"sequence\": 1,\n        \"coach_name\": \"ENG\",\n        \"class_code\": \"LOCO\",\n        \"class_name\": \"Locomotive\",\n        \"coach_type\": \"LOCOMOTIVE\",\n        \"position_from_engine\": 1,\n        \"is_locomotive\": true,\n        \"locomotive_end\": \"FRONT\"\n      },\n      {\n        \"sequence\": 2,\n        \"coach_name\": \"SLRD\",\n        \"class_code\": \"SLR\",\n        \"class_name\": \"Luggage, brake & Divyangjan van\",\n        \"coach_type\": \"LUGGAGE_BRAKE\",\n        \"position_from_engine\": 2,\n        \"is_locomotive\": false\n      },\n      {\n        \"sequence\": 3,\n        \"coach_name\": \"GEN\",\n        \"class_code\": \"GS\",\n        \"class_name\": \"General (unreserved)\",\n        \"coach_type\": \"UNRESERVED\",\n        \"position_from_engine\": 3,\n        \"is_locomotive\": false\n      },\n      {\n        \"sequence\": 4,\n        \"coach_name\": \"GEN\",\n        \"class_code\": \"GS\",\n        \"class_name\": \"General (unreserved)\",\n        \"coach_type\": \"UNRESERVED\",\n        \"position_from_engine\": 4,\n        \"is_locomotive\": false\n      },\n      {\n        \"sequence\": 5,\n        \"coach_name\": \"S5\",\n        \"class_code\": \"SL\",\n        \"class_name\": \"Sleeper\",\n        \"coach_type\": \"RESERVED\",\n        \"position_from_engine\": 5,\n        \"is_locomotive\": false\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.605Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.605Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `schedule:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number` string Train number.\n- `train_name / train_type` string The train's name and category code, such as SF or RAJDHANI, from RailCore's train catalog.\n- `source_station / destination_station` object The train's first and last stations, each as { code, name }, with the name written out in full.\n- `rake_type` string Coach build. TRAINSET for a self-propelled set. LHB ICF TRAINSET\n- `has_locomotive` boolean True for a loco-hauled train, whose list starts with the locomotive. False for a self-propelled set, which has no locomotive row.\n- `locomotives` integer Locomotive rows in the list: 0 for a self-propelled set, 1 for a loco-hauled train, 2 for a push-pull train. 0 1 2\n- `push_pull` boolean True for a push-pull train: a locomotive at each end of the rake, so the list starts and ends with a locomotive row. Indian Railways publishes no list of such trains; RailCore marks one on evidence and says which in push_pull_basis. A train that is not marked may still be worked push-pull.\n- `push_pull_basis` string Present when push_pull is true: what the mark rests on. train_design: the train is an Amrit Bharat Express, built as a push-pull rake. railway_announcement: the railway announced push-pull working for this train. rake_composition: the train's coach composition lists a locomotive at each end. train_design railway_announcement rake_composition\n- `composition_basis` string Where the coach list comes from. primary: RailCore's main coach-composition source. secondary: the main source publishes no composition for this train, so the list is a second source's; it can lag a recent change to the rake, and the answer's confidence is medium. primary secondary\n- `total_coaches` integer Coaches in the list, not counting locomotives or power cars.\n- `power_cars` integer Power cars in the list (LPR, EOG), each a row with coach_type POWER_CAR. 0 on a train with none.\n- `total_vehicles` integer Every row in the list: locomotives, coaches and power cars.\n- `formation` string The rake written out from the front, for example ENG-SLRD-GEN-S5-S4-PC-B1-A1-H1-GEN.\n- `class_summary[]` object[] The rake counted by class, in rake order: class_code, class_name, coach_type and coaches (how many). On a loco-hauled train the first entry is the locomotive (class_code LOCO, coaches 1; 2 on a push-pull train). Power cars are counted too, so the counts add up to total_vehicles.\n- `reversal_stations[]` object[] Stations where the engine changes ends, so the coach order runs the other way from there on: station_code and station_name. Empty when RailCore knows of none.\n- `coach_position[].sequence` integer Row number in the list, from 1.\n- `coach_position[].coach_name` string Coach label such as B1. ENG for the locomotive.\n- `coach_position[].class_code` string The coach's class (a ClassCode value such as 3A, SL or GS), LOCO for the locomotive, or the vehicle's own code where it has no travel class (LPR or EOG for a power car, VP for a parcel van).\n- `coach_position[].class_name` string The class or vehicle in words: Third AC, Sleeper, General (unreserved), Pantry car, Power car, Generator car, Locomotive.\n- `coach_position[].coach_type` string What the vehicle is for. RESERVED is a coach whose seats or berths are booked in a class; UNRESERVED is a general coach. LOCOMOTIVE RESERVED UNRESERVED PANTRY LUGGAGE_BRAKE POWER_CAR PARCEL OTHER\n- `coach_position[].position_from_engine` integer Place in the rake counted from the front. The locomotive is 1, the vehicle behind it 2. Every vehicle is listed, power cars included, so the numbers run without a gap.\n- `coach_position[].is_locomotive` boolean True for a locomotive row, false for a coach.\n- `coach_position[].locomotive_end` string On a locomotive row only: which end of the rake it is at. A push-pull train has one of each. FRONT REAR\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [TRAIN_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-TRAIN_NOT_FOUND) Do not retry unchanged No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.\n- 404 [COACH_POSITION_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-COACH_POSITION_NOT_FOUND) Do not retry unchanged The train exists, but no source RailCore reads publishes its coach composition. error.message names it: No coach composition is published for train 12345. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- To draw only the passenger coaches, skip the rows where is_locomotive is true or coach_type is POWER_CAR.\n- A power car row reads { class_code: \"LPR\", class_name: \"Power car\", coach_type: \"POWER_CAR\" }, or EOG and Generator car. Until November 12, 2026 power cars were left out, leaving a gap in position_from_engine.\n- A push-pull train answers push_pull: true, locomotives: 2 and a formation that ends with ENG; its last row is { coach_name: \"ENG\", is_locomotive: true, locomotive_end: \"REAR\" }.\n- The train's own details (train_name, train_type, the two stations, rake_type) are left out on the rare request where RailCore could not read its catalog in time; the rake is complete either way.\n- Berth counts and berth layouts are not part of this answer.\n- A train with no coach composition at any source RailCore reads is a 404 COACH_POSITION_NOT_FOUND, not counted and not worth retrying soon. A composition from the second source says composition_basis: \"secondary\".\n\nSource: https://railcore.tech/docs/api/coach-position\nLast updated: 13 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12656/coach-position\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/trains/12656/coach-position\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/trains/12656/coach-position\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/trains/12656/coach-position\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/trains/12656/coach-position\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/trains/12656/coach-position\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/trains/12656/coach-position\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/trains/12656/coach-position\";\nconst params = [];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/trains/12656/coach-position\"\nparams = []\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/trains/12656/coach-position\";\n$params = [];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/trains/12656/coach-position\"\n\tparams := [][2]string{}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/trains/12656/coach-position\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"live-train","category":"Trains","method":"GET","path":"/trains/{train_number}/live","url_template":"https://ir.railcore.tech/v1/trains/{train_number}/live","title":"Live train status","summary":"Where a train is right now, how late it is, and its times at every station on the route.","description":"Returns one run of a train: its status and position, its delay, when it should reach its last station, and the scheduled, expected and actual times at every station on its route, including the ones it passes without stopping. Answers are at most 10 seconds older than the live feed, and say exactly how old they are.","scope":"live:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"path","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12723","pattern":"^[0-9A-Z]{4,6}$"},{"name":"date","in":"query","type":"string(date)","required":false,"description":"The day the train leaves its first station, as YYYY-MM-DD in IST. A train that left late last night is still running under last night's date. Leave it out for the run on its way now (one that has left its first station and is not more than 3 hours past its booked arrival at the last; with two on the way, the one that left most recently), or else the next run to leave. journey_date in the answer says which run it is.","example":"{{date:today_ist}}"},{"name":"from","in":"query","type":"string","required":false,"description":"The run's first station. Leave it out: RailCore uses the train's own first station. Needed only for a train missing from the train catalog.","example":"","pattern":"^[A-Za-z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":false,"description":"The run's last station. Leave it out: RailCore uses the train's own last station. Needed only for a train missing from the train catalog.","example":"","pattern":"^[A-Za-z0-9]{1,6}$"},{"name":"max_age","in":"query","type":"integer","required":false,"description":"The oldest RailCore read of this run, in seconds, you accept. 0 asks for a fresh read of the live feed.","example":"","default":"10","minimum":0,"maximum":10}],"body_fields":[],"response_fields":[{"group":"The run","name":"train_number / train_name","type":"string","required":true,"description":"The train and its published name."},{"group":"The run","name":"journey_date","type":"string(date)","required":true,"description":"The day the run left, or leaves, its first station: the date you asked for, or, without date, the run RailCore picked."},{"group":"The run","name":"source_station_code / destination_station_code","type":"string","description":"First and last station of this run."},{"group":"The run","name":"train_type / train_type_label","type":"string","description":"The train's category code, such as SF or RAJDHANI, and its readable label, such as superfast: the live feed's, else RailCore's train catalog's. Left out only for a train the catalog does not have."},{"group":"The run","name":"travel_classes","type":"string[]","description":"Classes the train carries, such as 3A and SL: the live feed's, else the train catalog's."},{"group":"The run","name":"scheduled_duration_minutes","type":"integer","description":"Timetabled time from first to last station."},{"group":"The run","name":"started_at / start_date","type":"string","description":"When the train actually left its first station, and that date as the live feed gives it. started_at is left out before it leaves."},{"group":"Where it is now","name":"status","type":"string","required":true,"description":"Where the run stands. CANCELLED means the whole run is cancelled; a train cancelled for only part of its route stays RUNNING or AT_STATION and the part is in cancellation.","allowed":["NOT_STARTED","RUNNING","AT_STATION","COMPLETED","CANCELLED","DIVERTED","UNKNOWN"]},{"group":"Where it is now","name":"status_text","type":"string","description":"A ready-to-show line, for example Running 22 minutes late."},{"group":"Where it is now","name":"current_station_code / current_station_name","type":"string","description":"The station the train is at, or the last one it passed. Names are written as the RailCore site writes them (New Delhi, Mumbai Central), not the upper-case booking names."},{"group":"Where it is now","name":"previous_station_code / next_station_code","type":"string","description":"The booked halts behind and ahead of the train."},{"group":"Where it is now","name":"previous_station_name","type":"string","description":"The name of the halt behind the train, written as the RailCore site writes it. Left out when the live feed names none."},{"group":"Where it is now","name":"approaching_station_code / approaching_station_name","type":"string","description":"The next station on the line ahead, even one the train will pass without stopping."},{"group":"Where it is now","name":"distance_from_current_station_km / distance_to_approaching_station_km","type":"number","description":"How far the train is past the current station and short of the approaching one. Left out when the position is not precise enough."},{"group":"Where it is now","name":"latitude / longitude","type":"number","description":"The train's last reported position."},{"group":"Where it is now","name":"position_anchor_station_code","type":"string","description":"The station the live feed measured the position from. It can trail current_station_code by a station or two."},{"group":"Where it is now","name":"progress_percent","type":"number","description":"Share of the route covered, from 0 to 100."},{"group":"Where it is now","name":"distance_covered_km / total_distance_km","type":"number","description":"Distance covered so far, and the length of the route."},{"group":"Where it is now","name":"speed_kmph","type":"number","description":"RailCore's own estimate, not a locomotive reading: the speed where the train was last reported, from its coaches and type, the timetable and how it has run, never above what the train may run at and lower as it leaves a halt or nears the next. The estimate is rounded to 5 km/h and the figure moves within 5 km/h of it every 2 seconds, the same for every caller at the same moment, so a train that keeps running reads like a moving one. 0 while it stands at a station, before it starts and after it ends. Left out only when speed_basis is unavailable."},{"group":"Where it is now","name":"speed_basis","type":"string","description":"How speed_kmph was worked out: estimated while the train runs, stationary for 0, unavailable when the report is over 15 minutes old or does not place the train on its route.","allowed":["estimated","stationary","unavailable"]},{"group":"Delay and arrival","name":"delay_minutes","type":"integer","description":"How late the train is at the last station it reached. Negative when early."},{"group":"Delay and arrival","name":"eta_destination_at","type":"string","description":"Expected arrival at the last station; the actual time once the run is complete. Left out for a cancelled run."},{"group":"Delay and arrival","name":"rescheduled_minutes","type":"integer","description":"How far the railway moved the run's start, in minutes. 0 when the start was not moved."},{"group":"Changes to the run","name":"cancellation","type":"object","required":true,"description":"Whether the run is cancelled. Always an object: read its status."},{"group":"Changes to the run","name":"cancellation.status","type":"string","required":true,"description":"NOT_CANCELLED when nothing is cancelled, PARTIALLY_CANCELLED when a section does not run, CANCELLED for the whole run.","allowed":["NOT_CANCELLED","PARTIALLY_CANCELLED","CANCELLED"]},{"group":"Changes to the run","name":"cancellation.fully_cancelled / message","type":"boolean / string","required":true,"description":"True only when the whole run is cancelled, and the same in words, for example No cancellation reported for this run."},{"group":"Changes to the run","name":"cancellation.from_station_code / to_station_code","type":"string","description":"The section that does not run, on a part cancellation. Left out when nothing is cancelled."},{"group":"Changes to the run","name":"official_notice","type":"object","description":"What the railway's own running status says differs from the timetable: reason and message, new first or last station, new departure or arrival time, and whether the train is diverted. Present only when the railway reports a difference."},{"group":"Stations","name":"next_stop","type":"object","description":"The next station the train halts at, with the same fields as a stations[] entry. Left out once there is none."},{"group":"Stations","name":"stations[]","type":"object[]","required":true,"description":"Every station on the route in order, including the ones the train passes without stopping."},{"group":"Stations","name":"stations[].sequence / station_code / station_name","type":"integer / string","description":"Position on the route, from 1, and the station. The name is written as the RailCore site writes it (New Delhi), not the upper-case booking name."},{"group":"Stations","name":"stations[].notes","type":"object","description":"At the first and last stations only, in place of the time the train does not have there: notes.arrival at the ORIGIN (Starts at Hyderabad Deccan: departs only, no arrival), notes.departure at the DESTINATION (Ends at New Delhi: arrives only, no departure)."},{"group":"Stations","name":"stations[].stop_type","type":"string","description":"What the station is to this run. ORIGIN is where the run starts, so it has no arrival fields; DESTINATION is where it ends, so it has no departure fields. PASSING is a station the train runs through: it has booked times and a worked-out time, but no platform.","allowed":["ORIGIN","HALT","PASSING","DESTINATION"]},{"group":"Stations","name":"stations[].scheduled_arrival / scheduled_departure","type":"string","description":"Timetabled times. At a passing station, the booked time the train runs through. The ORIGIN has no scheduled_arrival and the DESTINATION no scheduled_departure."},{"group":"Stations","name":"stations[].eta / etd","type":"string","description":"When the train reaches and leaves the station: the expected times while it is ahead, the actual times once the train has been there. Every station has both except the ORIGIN, which has no eta, and the DESTINATION, which has no etd; timing_basis says where they come from."},{"group":"Stations","name":"stations[].timing_basis","type":"string","description":"Where eta and etd come from. reported: the train was reported at the station. predicted: the live feed's forecast. estimated: RailCore worked at least one of the two out from the delay at the timed stations either side, because the feed times halts only and not always both ends of one. scheduled: nothing on the run is timed yet, so the booked time stands. cancelled: the run is cancelled, and the station has no eta, etd or delay.","allowed":["reported","predicted","estimated","scheduled","cancelled"]},{"group":"Stations","name":"stations[].actual_arrival / actual_departure","type":"string","description":"Reported arrival and departure. Each is present once the train has been reported arriving or leaving there; never actual_arrival at the ORIGIN or actual_departure at the DESTINATION."},{"group":"Stations","name":"stations[].delay_arrival_minutes / delay_departure_minutes","type":"integer","description":"Minutes late arriving and leaving: eta and etd against the booked times. Negative when early. Left out with eta at the ORIGIN and with etd at the DESTINATION."},{"group":"Stations","name":"stations[].platform_number","type":"string","description":"Expected platform. Platforms can change at short notice. Left out where none is named, and at a station the train runs through."},{"group":"Stations","name":"stations[].halt_minutes / day / distance_km","type":"integer | number","description":"Booked halt in minutes, day of the run (1 is the day it starts), and distance from the first station in km."},{"group":"Stations","name":"stations[].is_stopping / is_diverted","type":"boolean","description":"Whether the train halts here, and whether the station is on a diversion rather than the booked route."},{"group":"Stations","name":"stations[].has_arrived / has_departed / travelled","type":"boolean","description":"Whether the train has reached, left and covered this station."},{"group":"Stations","name":"stations[].latitude / longitude / last_reported_at","type":"number | string","description":"The station's position, and when the train was last reported there (present once it has been)."},{"group":"Freshness","name":"last_reported_at","type":"string","description":"When the live feed last reported this train. Left out before the run has been reported."},{"group":"Freshness","name":"freshness","type":"object","required":true,"description":"How fresh this answer is, in the fields below."},{"group":"Freshness","name":"confidence","type":"string","required":true,"description":"How far to trust the answer, from its age and source. A finished run whose arrival at its last station was reported is high. The X-RailCore-Confidence header says the same.","allowed":["high","medium","low"]},{"group":"Freshness","name":"freshness.state / age_seconds","type":"string / integer","description":"The report's age in seconds, and the state that age puts it in.","allowed":["fresh","aging","stale","unknown"]},{"group":"Freshness","name":"freshness.retrieved_at / last_reported_at","type":"string","description":"When RailCore read the live feed, and the report time it got back."},{"group":"Freshness","name":"freshness.railcore_cache","type":"string","description":"bypassed when this request read the live feed; reused when RailCore answered from its own read of the same run made within max_age seconds, at freshness.retrieved_at.","allowed":["bypassed","reused"]},{"group":"Freshness","name":"freshness.upstream_served_from_cache","type":"boolean","description":"True when the live feed said it answered from its own cache. Present only when the feed says; it is usually left out."}],"response_example":{"success":true,"data":{"train_number":"12723","train_name":"Telangana Express","journey_date":"{{date:today_ist}}","train_type":"SF","train_type_label":"superfast","travel_classes":["1A","2A","3A","SL","GS"],"source_station_code":"HYB","destination_station_code":"NDLS","start_date":"{{date:today_ist}}","started_at":"{{date:today_ist}}T06:43:14+05:30","scheduled_duration_minutes":1560,"status":"RUNNING","status_text":"Running 23 minutes late","cancellation":{"status":"NOT_CANCELLED","fully_cancelled":false,"message":"No cancellation reported for this run"},"current_station_code":"MKDI","current_station_name":"Makudi","previous_station_code":"SKZR","previous_station_name":"Sirpur Kaghaznagar","next_station_code":"BPQ","approaching_station_code":"WIRR","approaching_station_name":"Wirur","position_anchor_station_code":"MKDI","distance_from_current_station_km":1.4,"distance_to_approaching_station_km":11.5,"latitude":19.551,"longitude":79.476,"progress_percent":20.04,"distance_covered_km":335.7,"total_distance_km":1675,"speed_kmph":107,"speed_basis":"estimated","delay_minutes":23,"eta_destination_at":"2026-11-21T08:07:00+05:30","rescheduled_minutes":0,"last_reported_at":"{{date:today_ist}}T11:34:11+05:30","confidence":"high","next_stop":{"sequence":65,"station_code":"BPQ","station_name":"Balharshah","stop_type":"HALT","scheduled_arrival":"{{date:today_ist}}T11:55:00+05:30","scheduled_departure":"{{date:today_ist}}T12:00:00+05:30","eta":"{{date:today_ist}}T12:01:00+05:30","etd":"{{date:today_ist}}T12:06:00+05:30","delay_arrival_minutes":6,"delay_departure_minutes":6,"platform_number":"4","halt_minutes":5,"day":1,"distance_km":375,"is_stopping":true,"is_diverted":false,"has_arrived":false,"has_departed":false,"travelled":false,"latitude":19.849,"longitude":79.349,"timing_basis":"predicted"},"stations":[{"sequence":1,"station_code":"HYB","station_name":"Hyderabad Deccan","stop_type":"ORIGIN","notes":{"arrival":"Starts at Hyderabad Deccan: departs only, no arrival"},"scheduled_departure":"{{date:today_ist}}T06:00:00+05:30","etd":"{{date:today_ist}}T06:43:14+05:30","actual_departure":"{{date:today_ist}}T06:43:14+05:30","delay_departure_minutes":43,"platform_number":"5","halt_minutes":0,"day":1,"distance_km":0,"is_stopping":true,"is_diverted":false,"has_arrived":true,"has_departed":true,"travelled":true,"latitude":17.393,"longitude":78.467,"last_reported_at":"{{date:today_ist}}T06:43:14+05:30","timing_basis":"reported"},{"sequence":2,"station_code":"LKPL","station_name":"Lakdi Ka Pul","stop_type":"PASSING","scheduled_arrival":"{{date:today_ist}}T06:03:00+05:30","scheduled_departure":"{{date:today_ist}}T06:03:00+05:30","eta":"{{date:today_ist}}T06:46:10+05:30","etd":"{{date:today_ist}}T06:46:10+05:30","delay_arrival_minutes":43,"delay_departure_minutes":43,"halt_minutes":0,"day":1,"distance_km":1.4,"is_stopping":false,"is_diverted":false,"has_arrived":true,"has_departed":true,"travelled":true,"latitude":17.404,"longitude":78.464,"timing_basis":"estimated"},{"sequence":56,"station_code":"SKZR","station_name":"Sirpur Kaghaznagar","stop_type":"HALT","scheduled_arrival":"{{date:today_ist}}T10:39:00+05:30","scheduled_departure":"{{date:today_ist}}T10:40:00+05:30","eta":"{{date:today_ist}}T11:13:18+05:30","etd":"{{date:today_ist}}T11:17:07+05:30","actual_arrival":"{{date:today_ist}}T11:13:18+05:30","actual_departure":"{{date:today_ist}}T11:17:07+05:30","delay_arrival_minutes":34,"delay_departure_minutes":37,"platform_number":"1","halt_minutes":1,"day":1,"distance_km":305,"is_stopping":true,"is_diverted":false,"has_arrived":true,"has_departed":true,"travelled":true,"latitude":19.346,"longitude":79.489,"last_reported_at":"{{date:today_ist}}T11:17:07+05:30","timing_basis":"reported"},{"sequence":65,"station_code":"BPQ","station_name":"Balharshah","stop_type":"HALT","scheduled_arrival":"{{date:today_ist}}T11:55:00+05:30","scheduled_departure":"{{date:today_ist}}T12:00:00+05:30","eta":"{{date:today_ist}}T12:01:00+05:30","etd":"{{date:today_ist}}T12:06:00+05:30","delay_arrival_minutes":6,"delay_departure_minutes":6,"platform_number":"4","halt_minutes":5,"day":1,"distance_km":375,"is_stopping":true,"is_diverted":false,"has_arrived":false,"has_departed":false,"travelled":false,"latitude":19.849,"longitude":79.349,"timing_basis":"predicted"},{"sequence":150,"station_code":"NDLS","station_name":"New Delhi","stop_type":"DESTINATION","notes":{"departure":"Ends at New Delhi: arrives only, no departure"},"scheduled_arrival":"2026-11-21T07:45:00+05:30","eta":"2026-11-21T08:07:00+05:30","delay_arrival_minutes":22,"halt_minutes":0,"day":2,"distance_km":1675,"is_stopping":true,"is_diverted":false,"has_arrived":false,"has_departed":false,"travelled":false,"latitude":28.643,"longitude":77.219,"timing_basis":"predicted"}],"freshness":{"state":"fresh","age_seconds":13,"retrieved_at":"{{date:today_ist}}T11:34:24+05:30","last_reported_at":"{{date:today_ist}}T11:34:11+05:30","railcore_cache":"bypassed"}},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.605Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.605Z","sources":[{"confidence":"high"}]}}},"notes":["A train reports about once a minute, so by default RailCore may answer from its own read of the same run made up to 10 seconds earlier, labelled freshness.railcore_cache: reused. Pass max_age=0 for a fresh read. Either way it counts as 1 request.","The Server-Timing response header lists where each request spent its time, for example key, limits, credits (counting the request), upstream and total.","Ask for the date the train left its first station. An overnight train still running this morning started yesterday. Leave date out and RailCore picks the run on its way now, or else the next one to leave; journey_date says which.","Nothing live is ever guessed: a time, delay or platform RailCore cannot establish for a run is left out. What the live feed leaves out but RailCore's own catalog and timetable know (the train's type and classes, a passing station's booked time) is filled from them.","speed_kmph is RailCore's estimate, not a speedometer: it moves within 5 km/h of the estimate every 2 seconds so it reads like a moving train, but it is not measured. Label it as an estimate, and read speed_basis before showing it at all.","A station's missing fields follow from its stop_type. The origin has no scheduled_arrival, eta, delay_arrival_minutes or actual_arrival; the destination has no scheduled_departure, etd, delay_departure_minutes or actual_departure; a passing station has no platform, and no actual time unless the train was timed there. Until November 12, 2026 the origin's arrival fields copied its departure and the destination's departure fields copied its arrival.","This endpoint replaced GET /trains/{train_number}/live-status and GET /trains/{train_number}/running on November 3, 2026. The changelog lists what changed."],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"date is not a real date, a station code is malformed, or the train is missing from the train catalog and from and to were not passed. error.details[].field names the parameter.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":404,"code":"NOT_FOUND","description":"The train has no run on that date, for example a weekly train on a day it does not run.","retryable":false,"category":"NOT_FOUND","fix":"Nothing matches the request. Check the identifiers and the date (a train may not run that day), then ask again."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"The live feed could not answer for this run. Wait for Retry-After, then retry with backoff.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/live-train","markdown_url":"https://railcore.tech/docs/api/live-train.md","markdown":"# Live train status\n\nWhere a train is right now, how late it is, and its times at every station on the route.\n\n`GET /v1/trains/{train_number}/live`\n\n- **Scope:** `live:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns one run of a train: its status and position, its delay, when it should reach its last station, and the scheduled, expected and actual times at every station on its route, including the ones it passes without stopping. Answers are at most 10 seconds older than the live feed, and say exactly how old they are.\n\n```\nRUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12723/live?date=$RUN_DATE\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12723\",\n    \"train_name\": \"Telangana Express\",\n    \"journey_date\": \"2026-11-20\",\n    \"train_type\": \"SF\",\n    \"train_type_label\": \"superfast\",\n    \"travel_classes\": [\"1A\", \"2A\", \"3A\", \"SL\", \"GS\"],\n    \"source_station_code\": \"HYB\",\n    \"destination_station_code\": \"NDLS\",\n    \"start_date\": \"2026-11-20\",\n    \"started_at\": \"2026-11-20T06:43:14+05:30\",\n    \"scheduled_duration_minutes\": 1560,\n    \"status\": \"RUNNING\",\n    \"status_text\": \"Running 23 minutes late\",\n    \"cancellation\": {\n      \"status\": \"NOT_CANCELLED\",\n      \"fully_cancelled\": false,\n      \"message\": \"No cancellation reported for this run\"\n    },\n    \"current_station_code\": \"MKDI\",\n    \"current_station_name\": \"Makudi\",\n    \"previous_station_code\": \"SKZR\",\n    \"previous_station_name\": \"Sirpur Kaghaznagar\",\n    \"next_station_code\": \"BPQ\",\n    \"approaching_station_code\": \"WIRR\",\n    \"approaching_station_name\": \"Wirur\",\n    \"position_anchor_station_code\": \"MKDI\",\n    \"distance_from_current_station_km\": 1.4,\n    \"distance_to_approaching_station_km\": 11.5,\n    \"latitude\": 19.551,\n    \"longitude\": 79.476,\n    \"progress_percent\": 20.04,\n    \"distance_covered_km\": 335.7,\n    \"total_distance_km\": 1675,\n    \"speed_kmph\": 107,\n    \"speed_basis\": \"estimated\",\n    \"delay_minutes\": 23,\n    \"eta_destination_at\": \"2026-11-21T08:07:00+05:30\",\n    \"rescheduled_minutes\": 0,\n    \"last_reported_at\": \"2026-11-20T11:34:11+05:30\",\n    \"confidence\": \"high\",\n    \"next_stop\": {\n      \"sequence\": 65,\n      \"station_code\": \"BPQ\",\n      \"station_name\": \"Balharshah\",\n      \"stop_type\": \"HALT\",\n      \"scheduled_arrival\": \"2026-11-20T11:55:00+05:30\",\n      \"scheduled_departure\": \"2026-11-20T12:00:00+05:30\",\n      \"eta\": \"2026-11-20T12:01:00+05:30\",\n      \"etd\": \"2026-11-20T12:06:00+05:30\",\n      \"delay_arrival_minutes\": 6,\n      \"delay_departure_minutes\": 6,\n      \"platform_number\": \"4\",\n      \"halt_minutes\": 5,\n      \"day\": 1,\n      \"distance_km\": 375,\n      \"is_stopping\": true,\n      \"is_diverted\": false,\n      \"has_arrived\": false,\n      \"has_departed\": false,\n      \"travelled\": false,\n      \"latitude\": 19.849,\n      \"longitude\": 79.349,\n      \"timing_basis\": \"predicted\"\n    },\n    \"stations\": [\n      {\n        \"sequence\": 1,\n        \"station_code\": \"HYB\",\n        \"station_name\": \"Hyderabad Deccan\",\n        \"stop_type\": \"ORIGIN\",\n        \"notes\": {\n          \"arrival\": \"Starts at Hyderabad Deccan: departs only, no arrival\"\n        },\n        \"scheduled_departure\": \"2026-11-20T06:00:00+05:30\",\n        \"etd\": \"2026-11-20T06:43:14+05:30\",\n        \"actual_departure\": \"2026-11-20T06:43:14+05:30\",\n        \"delay_departure_minutes\": 43,\n        \"platform_number\": \"5\",\n        \"halt_minutes\": 0,\n        \"day\": 1,\n        \"distance_km\": 0,\n        \"is_stopping\": true,\n        \"is_diverted\": false,\n        \"has_arrived\": true,\n        \"has_departed\": true,\n        \"travelled\": true,\n        \"latitude\": 17.393,\n        \"longitude\": 78.467,\n        \"last_reported_at\": \"2026-11-20T06:43:14+05:30\",\n        \"timing_basis\": \"reported\"\n      },\n      {\n        \"sequence\": 2,\n        \"station_code\": \"LKPL\",\n        \"station_name\": \"Lakdi Ka Pul\",\n        \"stop_type\": \"PASSING\",\n        \"scheduled_arrival\": \"2026-11-20T06:03:00+05:30\",\n        \"scheduled_departure\": \"2026-11-20T06:03:00+05:30\",\n        \"eta\": \"2026-11-20T06:46:10+05:30\",\n        \"etd\": \"2026-11-20T06:46:10+05:30\",\n        \"delay_arrival_minutes\": 43,\n        \"delay_departure_minutes\": 43,\n        \"halt_minutes\": 0,\n        \"day\": 1,\n        \"distance_km\": 1.4,\n        \"is_stopping\": false,\n        \"is_diverted\": false,\n        \"has_arrived\": true,\n        \"has_departed\": true,\n        \"travelled\": true,\n        \"latitude\": 17.404,\n        \"longitude\": 78.464,\n        \"timing_basis\": \"estimated\"\n      },\n      {\n        \"sequence\": 56,\n        \"station_code\": \"SKZR\",\n        \"station_name\": \"Sirpur Kaghaznagar\",\n        \"stop_type\": \"HALT\",\n        \"scheduled_arrival\": \"2026-11-20T10:39:00+05:30\",\n        \"scheduled_departure\": \"2026-11-20T10:40:00+05:30\",\n        \"eta\": \"2026-11-20T11:13:18+05:30\",\n        \"etd\": \"2026-11-20T11:17:07+05:30\",\n        \"actual_arrival\": \"2026-11-20T11:13:18+05:30\",\n        \"actual_departure\": \"2026-11-20T11:17:07+05:30\",\n        \"delay_arrival_minutes\": 34,\n        \"delay_departure_minutes\": 37,\n        \"platform_number\": \"1\",\n        \"halt_minutes\": 1,\n        \"day\": 1,\n        \"distance_km\": 305,\n        \"is_stopping\": true,\n        \"is_diverted\": false,\n        \"has_arrived\": true,\n        \"has_departed\": true,\n        \"travelled\": true,\n        \"latitude\": 19.346,\n        \"longitude\": 79.489,\n        \"last_reported_at\": \"2026-11-20T11:17:07+05:30\",\n        \"timing_basis\": \"reported\"\n      },\n      {\n        \"sequence\": 65,\n        \"station_code\": \"BPQ\",\n        \"station_name\": \"Balharshah\",\n        \"stop_type\": \"HALT\",\n        \"scheduled_arrival\": \"2026-11-20T11:55:00+05:30\",\n        \"scheduled_departure\": \"2026-11-20T12:00:00+05:30\",\n        \"eta\": \"2026-11-20T12:01:00+05:30\",\n        \"etd\": \"2026-11-20T12:06:00+05:30\",\n        \"delay_arrival_minutes\": 6,\n        \"delay_departure_minutes\": 6,\n        \"platform_number\": \"4\",\n        \"halt_minutes\": 5,\n        \"day\": 1,\n        \"distance_km\": 375,\n        \"is_stopping\": true,\n        \"is_diverted\": false,\n        \"has_arrived\": false,\n        \"has_departed\": false,\n        \"travelled\": false,\n        \"latitude\": 19.849,\n        \"longitude\": 79.349,\n        \"timing_basis\": \"predicted\"\n      },\n      {\n        \"sequence\": 150,\n        \"station_code\": \"NDLS\",\n        \"station_name\": \"New Delhi\",\n        \"stop_type\": \"DESTINATION\",\n        \"notes\": {\n          \"departure\": \"Ends at New Delhi: arrives only, no departure\"\n        },\n        \"scheduled_arrival\": \"2026-11-21T07:45:00+05:30\",\n        \"eta\": \"2026-11-21T08:07:00+05:30\",\n        \"delay_arrival_minutes\": 22,\n        \"halt_minutes\": 0,\n        \"day\": 2,\n        \"distance_km\": 1675,\n        \"is_stopping\": true,\n        \"is_diverted\": false,\n        \"has_arrived\": false,\n        \"has_departed\": false,\n        \"travelled\": false,\n        \"latitude\": 28.643,\n        \"longitude\": 77.219,\n        \"timing_basis\": \"predicted\"\n      }\n    ],\n    \"freshness\": {\n      \"state\": \"fresh\",\n      \"age_seconds\": 13,\n      \"retrieved_at\": \"2026-11-20T11:34:24+05:30\",\n      \"last_reported_at\": \"2026-11-20T11:34:11+05:30\",\n      \"railcore_cache\": \"bypassed\"\n    }\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.605Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.605Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `live:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12723\n\n## Query parameters\n\n- `date` string(date) optional The day the train leaves its first station, as YYYY-MM-DD in IST. A train that left late last night is still running under last night's date. Leave it out for the run on its way now (one that has left its first station and is not more than 3 hours past its booked arrival at the last; with two on the way, the one that left most recently), or else the next run to leave. journey_date in the answer says which run it is. Example 2026-11-20\n- `from` string optional The run's first station. Leave it out: RailCore uses the train's own first station. Needed only for a train missing from the train catalog.\n- `to` string optional The run's last station. Leave it out: RailCore uses the train's own last station. Needed only for a train missing from the train catalog.\n- `max_age` integer optional The oldest RailCore read of this run, in seconds, you accept. 0 asks for a fresh read of the live feed. Default 10 Range 0 to 10\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n### The run\n\n- `train_number / train_name` string always present The train and its published name.\n- `journey_date` string(date) always present The day the run left, or leaves, its first station: the date you asked for, or, without date, the run RailCore picked.\n- `source_station_code / destination_station_code` string First and last station of this run.\n- `train_type / train_type_label` string The train's category code, such as SF or RAJDHANI, and its readable label, such as superfast: the live feed's, else RailCore's train catalog's. Left out only for a train the catalog does not have.\n- `travel_classes` string[] Classes the train carries, such as 3A and SL: the live feed's, else the train catalog's.\n- `scheduled_duration_minutes` integer Timetabled time from first to last station.\n- `started_at / start_date` string When the train actually left its first station, and that date as the live feed gives it. started_at is left out before it leaves.\n\n### Where it is now\n\n- `status` string always present Where the run stands. CANCELLED means the whole run is cancelled; a train cancelled for only part of its route stays RUNNING or AT_STATION and the part is in cancellation. NOT_STARTED RUNNING AT_STATION COMPLETED CANCELLED DIVERTED UNKNOWN\n- `status_text` string A ready-to-show line, for example Running 22 minutes late.\n- `current_station_code / current_station_name` string The station the train is at, or the last one it passed. Names are written as the RailCore site writes them (New Delhi, Mumbai Central), not the upper-case booking names.\n- `previous_station_code / next_station_code` string The booked halts behind and ahead of the train.\n- `previous_station_name` string The name of the halt behind the train, written as the RailCore site writes it. Left out when the live feed names none.\n- `approaching_station_code / approaching_station_name` string The next station on the line ahead, even one the train will pass without stopping.\n- `distance_from_current_station_km / distance_to_approaching_station_km` number How far the train is past the current station and short of the approaching one. Left out when the position is not precise enough.\n- `latitude / longitude` number The train's last reported position.\n- `position_anchor_station_code` string The station the live feed measured the position from. It can trail current_station_code by a station or two.\n- `progress_percent` number Share of the route covered, from 0 to 100.\n- `distance_covered_km / total_distance_km` number Distance covered so far, and the length of the route.\n- `speed_kmph` number RailCore's own estimate, not a locomotive reading: the speed where the train was last reported, from its coaches and type, the timetable and how it has run, never above what the train may run at and lower as it leaves a halt or nears the next. The estimate is rounded to 5 km/h and the figure moves within 5 km/h of it every 2 seconds, the same for every caller at the same moment, so a train that keeps running reads like a moving one. 0 while it stands at a station, before it starts and after it ends. Left out only when speed_basis is unavailable.\n- `speed_basis` string How speed_kmph was worked out: estimated while the train runs, stationary for 0, unavailable when the report is over 15 minutes old or does not place the train on its route. estimated stationary unavailable\n\n### Delay and arrival\n\n- `delay_minutes` integer How late the train is at the last station it reached. Negative when early.\n- `eta_destination_at` string Expected arrival at the last station; the actual time once the run is complete. Left out for a cancelled run.\n- `rescheduled_minutes` integer How far the railway moved the run's start, in minutes. 0 when the start was not moved.\n\n### Changes to the run\n\n- `cancellation` object always present Whether the run is cancelled. Always an object: read its status.\n- `cancellation.status` string always present NOT_CANCELLED when nothing is cancelled, PARTIALLY_CANCELLED when a section does not run, CANCELLED for the whole run. NOT_CANCELLED PARTIALLY_CANCELLED CANCELLED\n- `cancellation.fully_cancelled / message` boolean / string always present True only when the whole run is cancelled, and the same in words, for example No cancellation reported for this run.\n- `cancellation.from_station_code / to_station_code` string The section that does not run, on a part cancellation. Left out when nothing is cancelled.\n- `official_notice` object What the railway's own running status says differs from the timetable: reason and message, new first or last station, new departure or arrival time, and whether the train is diverted. Present only when the railway reports a difference.\n\n### Stations\n\n- `next_stop` object The next station the train halts at, with the same fields as a stations[] entry. Left out once there is none.\n- `stations[]` object[] always present Every station on the route in order, including the ones the train passes without stopping.\n  - `sequence / station_code / station_name` integer / string Position on the route, from 1, and the station. The name is written as the RailCore site writes it (New Delhi), not the upper-case booking name.\n  - `notes` object At the first and last stations only, in place of the time the train does not have there: notes.arrival at the ORIGIN (Starts at Hyderabad Deccan: departs only, no arrival), notes.departure at the DESTINATION (Ends at New Delhi: arrives only, no departure).\n  - `stop_type` string What the station is to this run. ORIGIN is where the run starts, so it has no arrival fields; DESTINATION is where it ends, so it has no departure fields. PASSING is a station the train runs through: it has booked times and a worked-out time, but no platform. ORIGIN HALT PASSING DESTINATION\n  - `scheduled_arrival / scheduled_departure` string Timetabled times. At a passing station, the booked time the train runs through. The ORIGIN has no scheduled_arrival and the DESTINATION no scheduled_departure.\n  - `eta / etd` string When the train reaches and leaves the station: the expected times while it is ahead, the actual times once the train has been there. Every station has both except the ORIGIN, which has no eta, and the DESTINATION, which has no etd; timing_basis says where they come from.\n  - `timing_basis` string Where eta and etd come from. reported: the train was reported at the station. predicted: the live feed's forecast. estimated: RailCore worked at least one of the two out from the delay at the timed stations either side, because the feed times halts only and not always both ends of one. scheduled: nothing on the run is timed yet, so the booked time stands. cancelled: the run is cancelled, and the station has no eta, etd or delay. reported predicted estimated scheduled cancelled\n  - `actual_arrival / actual_departure` string Reported arrival and departure. Each is present once the train has been reported arriving or leaving there; never actual_arrival at the ORIGIN or actual_departure at the DESTINATION.\n  - `delay_arrival_minutes / delay_departure_minutes` integer Minutes late arriving and leaving: eta and etd against the booked times. Negative when early. Left out with eta at the ORIGIN and with etd at the DESTINATION.\n  - `platform_number` string Expected platform. Platforms can change at short notice. Left out where none is named, and at a station the train runs through.\n  - `halt_minutes / day / distance_km` integer | number Booked halt in minutes, day of the run (1 is the day it starts), and distance from the first station in km.\n  - `is_stopping / is_diverted` boolean Whether the train halts here, and whether the station is on a diversion rather than the booked route.\n  - `has_arrived / has_departed / travelled` boolean Whether the train has reached, left and covered this station.\n  - `latitude / longitude / last_reported_at` number | string The station's position, and when the train was last reported there (present once it has been).\n\n### Freshness\n\n- `last_reported_at` string When the live feed last reported this train. Left out before the run has been reported.\n- `freshness` object always present How fresh this answer is, in the fields below.\n- `confidence` string always present How far to trust the answer, from its age and source. A finished run whose arrival at its last station was reported is high. The X-RailCore-Confidence header says the same. high medium low\n- `freshness.state / age_seconds` string / integer The report's age in seconds, and the state that age puts it in. fresh aging stale unknown\n- `freshness.retrieved_at / last_reported_at` string When RailCore read the live feed, and the report time it got back.\n- `freshness.railcore_cache` string bypassed when this request read the live feed; reused when RailCore answered from its own read of the same run made within max_age seconds, at freshness.retrieved_at. bypassed reused\n- `freshness.upstream_served_from_cache` boolean True when the live feed said it answered from its own cache. Present only when the feed says; it is usually left out.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged date is not a real date, a station code is malformed, or the train is missing from the train catalog and from and to were not passed. error.details[].field names the parameter.\n- 404 [NOT_FOUND](https://railcore.tech/docs/errors-reference#error-NOT_FOUND) Do not retry unchanged The train has no run on that date, for example a weekly train on a day it does not run.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry The live feed could not answer for this run. Wait for Retry-After, then retry with backoff.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- A train reports about once a minute, so by default RailCore may answer from its own read of the same run made up to 10 seconds earlier, labelled freshness.railcore_cache: reused. Pass max_age=0 for a fresh read. Either way it counts as 1 request.\n- The Server-Timing response header lists where each request spent its time, for example key, limits, credits (counting the request), upstream and total.\n- Ask for the date the train left its first station. An overnight train still running this morning started yesterday. Leave date out and RailCore picks the run on its way now, or else the next one to leave; journey_date says which.\n- Nothing live is ever guessed: a time, delay or platform RailCore cannot establish for a run is left out. What the live feed leaves out but RailCore's own catalog and timetable know (the train's type and classes, a passing station's booked time) is filled from them.\n- speed_kmph is RailCore's estimate, not a speedometer: it moves within 5 km/h of the estimate every 2 seconds so it reads like a moving train, but it is not measured. Label it as an estimate, and read speed_basis before showing it at all.\n- A station's missing fields follow from its stop_type. The origin has no scheduled_arrival, eta, delay_arrival_minutes or actual_arrival; the destination has no scheduled_departure, etd, delay_departure_minutes or actual_departure; a passing station has no platform, and no actual time unless the train was timed there. Until November 12, 2026 the origin's arrival fields copied its departure and the destination's departure fields copied its arrival.\n- This endpoint replaced GET /trains/{train_number}/live-status and GET /trains/{train_number}/running on November 3, 2026. The changelog lists what changed.\n\nSource: https://railcore.tech/docs/api/live-train\nLast updated: 13 Nov 2026\n","samples":{"unsigned":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12723/live?date=$RUN_DATE\"","node":"const runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst response = await fetch(`https://ir.railcore.tech/v1/trains/12723/live?date=${runDate}`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/trains/12723/live?date={run_date}\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/trains/12723/live?date={$runDate}\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/trains/12723/live?date=\" + runDate, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/trains/12723/live?date=\" + runDate))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/trains/12723/live\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"date=${RUN_DATE}\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst method = \"GET\";\nconst path = \"/v1/trains/12723/live\";\nconst params = [\n  [\"date\", runDate],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nmethod = \"GET\"\npath = \"/v1/trains/12723/live\"\nparams = [\n    (\"date\", run_date),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$method = \"GET\";\n$path = \"/v1/trains/12723/live\";\n$params = [\n    [\"date\", $runDate],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/trains/12723/live\"\n\tparams := [][2]string{\n\t\t{\"date\", runDate},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        String method = \"GET\";\n        String path = \"/v1/trains/12723/live\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"date\", runDate}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"route-trains","category":"Journeys","method":"GET","path":"/routes/trains","url_template":"https://ir.railcore.tech/v1/routes/trains","title":"Trains between stations","summary":"Find trains serving a route on a date.","description":"Returns route-matching trains with schedule, classes, running pattern, and compact availability context.","scope":"journeys:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code.","example":"ADI","pattern":"^[A-Z0-9]{1,6}$"},{"name":"date","in":"query","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD format.","example":"{{date:days_ahead_utc:7}}"},{"name":"quota","in":"query","type":"string","required":false,"description":"Reservation quota of each train's availability_summary. Availability is given for GN (General) and TQ (Tatkal); with any other quota the trains are listed without it.","example":"GN","default":"GN","allowed":["GN","TQ"]},{"name":"match","in":"query","type":"string","required":false,"description":"city (the default) lists trains between any station of the two cities: a search from MMCT to NDLS also lists trains from BDTS to NZM. station lists only trains between the two stations you asked for. The answer's matched_by says which it is.","example":"city","default":"city","allowed":["city","station"]}],"body_fields":[],"response_fields":[{"name":"from_station_code","type":"string","description":"Resolved origin."},{"name":"to_station_code","type":"string","description":"Resolved destination."},{"name":"journey_date","type":"string(date)","description":"Requested journey date."},{"name":"quota","type":"Quota","description":"Applied reservation quota."},{"name":"matched_by","type":"string","description":"station: every train runs between the two stations you asked for. city: some trains run between other stations of the same two cities; each train's from_station_code and to_station_code say which.","allowed":["station","city"]},{"name":"trains[].train_number","type":"string","description":"Train number."},{"name":"trains[].train_name","type":"string","description":"Short name as printed on reservation charts, for example NAVJEEVAN SF EXP."},{"name":"trains[].extended_train_name","type":"string","description":"The train's full name from RailCore's train catalog, for example Navjeevan SF Express. The same as train_name for a train the catalog does not list."},{"name":"trains[].from_station_code / to_station_code","type":"string","description":"Where this train is boarded and left. With match=city they can be other stations of the two cities than the ones you asked for (BDTS and NZM on a search from MMCT to NDLS); with match=station they are always the two you asked for."},{"name":"trains[].from_station_name / to_station_name","type":"string","description":"Names of those two stations."},{"name":"trains[].departure_time / arrival_time","type":"string","description":"Scheduled segment times in HH:mm."},{"name":"trains[].duration_minutes","type":"integer","description":"Segment duration."},{"name":"trains[].distance_km","type":"number | null","description":"Segment distance."},{"name":"trains[].train_type","type":"string","description":"Normalized train type."},{"name":"trains[].classes","type":"ClassCode[]","description":"Offered travel classes."},{"name":"trains[].running_days","type":"RunningDay[]","description":"Weekly running pattern."},{"name":"trains[].has_pantry","type":"boolean | null","description":"Pantry availability when known."},{"name":"trains[].availability_summary","type":"AvailabilityMini[]","description":"Compact class-level status, fare, confidence, and update time. last_updated_at is India time with its offset, and can be days old: for a fresh figure call seat availability."}],"response_example":{"success":true,"data":{"from_station_code":"BSL","to_station_code":"ADI","journey_date":"{{date:days_ahead_utc:7}}","quota":"GN","matched_by":"station","trains":[{"train_number":"12656","from_station_code":"BSL","from_station_name":"Bhusaval Junction","to_station_code":"ADI","to_station_name":"Ahmedabad Junction","train_name":"NAVJEEVAN SF EXP","extended_train_name":"Navjeevan SF Express","departure_time":"10:25","arrival_time":"18:00","duration_minutes":455,"distance_km":563,"train_type":"SF","classes":["SL","3A","2A","1A"],"running_days":["MON","TUE","WED","THU","FRI","SAT","SUN"],"has_pantry":true,"availability_summary":[{"class_code":"3A","status":"AVAILABLE","text":"AVAILABLE-4","fare":965,"confidence":"high","last_updated_at":"{{date:today_ist}}T08:15:46.547+05:30"}]}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.608Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.608Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":404,"code":"NO_TRAINS_FOUND","description":"No train was found between the two stations on that date (with match=station, between those two stations only), or a station code does not exist. Not counted. trains is never empty.","retryable":false,"category":"NOT_FOUND","fix":"Try another date, nearby stations, or match=city to include every station in both cities."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/route-trains","markdown_url":"https://railcore.tech/docs/api/route-trains.md","markdown":"# Trains between stations\n\nFind trains serving a route on a date.\n\n`GET /v1/routes/trains`\n\n- **Scope:** `journeys:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns route-matching trains with schedule, classes, running pattern, and compact availability context.\n\n```\nJOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/routes/trains?from=BSL&to=ADI&date=$JOURNEY_DATE&quota=GN&match=city\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"from_station_code\": \"BSL\",\n    \"to_station_code\": \"ADI\",\n    \"journey_date\": \"2026-11-27\",\n    \"quota\": \"GN\",\n    \"matched_by\": \"station\",\n    \"trains\": [\n      {\n        \"train_number\": \"12656\",\n        \"from_station_code\": \"BSL\",\n        \"from_station_name\": \"Bhusaval Junction\",\n        \"to_station_code\": \"ADI\",\n        \"to_station_name\": \"Ahmedabad Junction\",\n        \"train_name\": \"NAVJEEVAN SF EXP\",\n        \"extended_train_name\": \"Navjeevan SF Express\",\n        \"departure_time\": \"10:25\",\n        \"arrival_time\": \"18:00\",\n        \"duration_minutes\": 455,\n        \"distance_km\": 563,\n        \"train_type\": \"SF\",\n        \"classes\": [\"SL\", \"3A\", \"2A\", \"1A\"],\n        \"running_days\": [\"MON\", \"TUE\", \"WED\", \"THU\", \"FRI\", \"SAT\", \"SUN\"],\n        \"has_pantry\": true,\n        \"availability_summary\": [\n          {\n            \"class_code\": \"3A\",\n            \"status\": \"AVAILABLE\",\n            \"text\": \"AVAILABLE-4\",\n            \"fare\": 965,\n            \"confidence\": \"high\",\n            \"last_updated_at\": \"2026-11-20T08:15:46.547+05:30\"\n          }\n        ]\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.608Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.608Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `journeys:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `from` string required Boarding station code. Example BSL\n- `to` string required Destination station code. Example ADI\n- `date` string(date) required Journey date in YYYY-MM-DD format. Example 2026-11-27\n- `quota` string optional Reservation quota of each train's availability_summary. Availability is given for GN (General) and TQ (Tatkal); with any other quota the trains are listed without it. Example GN Default GN GN TQ\n- `match` string optional city (the default) lists trains between any station of the two cities: a search from MMCT to NDLS also lists trains from BDTS to NZM. station lists only trains between the two stations you asked for. The answer's matched_by says which it is. Example city Default city city station\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `from_station_code` string Resolved origin.\n- `to_station_code` string Resolved destination.\n- `journey_date` string(date) Requested journey date.\n- `quota` Quota Applied reservation quota.\n- `matched_by` string station: every train runs between the two stations you asked for. city: some trains run between other stations of the same two cities; each train's from_station_code and to_station_code say which. station city\n- `trains[].train_number` string Train number.\n- `trains[].train_name` string Short name as printed on reservation charts, for example NAVJEEVAN SF EXP.\n- `trains[].extended_train_name` string The train's full name from RailCore's train catalog, for example Navjeevan SF Express. The same as train_name for a train the catalog does not list.\n- `trains[].from_station_code / to_station_code` string Where this train is boarded and left. With match=city they can be other stations of the two cities than the ones you asked for (BDTS and NZM on a search from MMCT to NDLS); with match=station they are always the two you asked for.\n- `trains[].from_station_name / to_station_name` string Names of those two stations.\n- `trains[].departure_time / arrival_time` string Scheduled segment times in HH:mm.\n- `trains[].duration_minutes` integer Segment duration.\n- `trains[].distance_km` number | null Segment distance.\n- `trains[].train_type` string Normalized train type.\n- `trains[].classes` ClassCode[] Offered travel classes.\n- `trains[].running_days` RunningDay[] Weekly running pattern.\n- `trains[].has_pantry` boolean | null Pantry availability when known.\n- `trains[].availability_summary` AvailabilityMini[] Compact class-level status, fare, confidence, and update time. last_updated_at is India time with its offset, and can be days old: for a fresh figure call seat availability.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [NO_TRAINS_FOUND](https://railcore.tech/docs/errors-reference#error-NO_TRAINS_FOUND) Do not retry unchanged No train was found between the two stations on that date (with match=station, between those two stations only), or a station code does not exist. Not counted. trains is never empty.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/route-trains\nLast updated: 19 Nov 2026\n","samples":{"unsigned":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/routes/trains?from=BSL&to=ADI&date=$JOURNEY_DATE&quota=GN&match=city\"","node":"const journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst response = await fetch(`https://ir.railcore.tech/v1/routes/trains?from=BSL&to=ADI&date=${journeyDate}&quota=GN&match=city`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/routes/trains?from=BSL&to=ADI&date={journey_date}&quota=GN&match=city\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/routes/trains?from=BSL&to=ADI&date={$journeyDate}&quota=GN&match=city\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/routes/trains?from=BSL&to=ADI&date=\" + journeyDate + \"&quota=GN&match=city\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/routes/trains?from=BSL&to=ADI&date=\" + journeyDate + \"&quota=GN&match=city\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/routes/trains\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"date=${JOURNEY_DATE}&from=BSL&match=city&quota=GN&to=ADI\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst method = \"GET\";\nconst path = \"/v1/routes/trains\";\nconst params = [\n  [\"from\", \"BSL\"],\n  [\"to\", \"ADI\"],\n  [\"date\", journeyDate],\n  [\"quota\", \"GN\"],\n  [\"match\", \"city\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nmethod = \"GET\"\npath = \"/v1/routes/trains\"\nparams = [\n    (\"from\", \"BSL\"),\n    (\"to\", \"ADI\"),\n    (\"date\", journey_date),\n    (\"quota\", \"GN\"),\n    (\"match\", \"city\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$method = \"GET\";\n$path = \"/v1/routes/trains\";\n$params = [\n    [\"from\", \"BSL\"],\n    [\"to\", \"ADI\"],\n    [\"date\", $journeyDate],\n    [\"quota\", \"GN\"],\n    [\"match\", \"city\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/routes/trains\"\n\tparams := [][2]string{\n\t\t{\"from\", \"BSL\"},\n\t\t{\"to\", \"ADI\"},\n\t\t{\"date\", journeyDate},\n\t\t{\"quota\", \"GN\"},\n\t\t{\"match\", \"city\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        String method = \"GET\";\n        String path = \"/v1/routes/trains\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"from\", \"BSL\"},\n            new String[] {\"to\", \"ADI\"},\n            new String[] {\"date\", journeyDate},\n            new String[] {\"quota\", \"GN\"},\n            new String[] {\"match\", \"city\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"journey-search","category":"Journeys","method":"GET","path":"/journeys/search","url_template":"https://ir.railcore.tech/v1/journeys/search","title":"Journey search","summary":"Search and rank route options for a journey UI.","description":"Uses the route-train contract with ranking tuned for search experiences.","scope":"journeys:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code.","example":"ADI","pattern":"^[A-Z0-9]{1,6}$"},{"name":"date","in":"query","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD format.","example":"{{date:days_ahead_utc:7}}"},{"name":"match","in":"query","type":"string","required":false,"description":"city (the default) lists trains between any station of the two cities: a search from MMCT to NDLS also lists trains from BDTS to NZM. station lists only trains between the two stations you asked for. The answer's matched_by says which it is.","example":"city","default":"city","allowed":["city","station"]}],"body_fields":[],"response_fields":[{"name":"from_station_code","type":"string","description":"Resolved origin."},{"name":"to_station_code","type":"string","description":"Resolved destination."},{"name":"journey_date","type":"string(date)","description":"Requested journey date."},{"name":"quota","type":"Quota","description":"Applied reservation quota."},{"name":"matched_by","type":"string","description":"station: every train runs between the two stations you asked for. city: some trains run between other stations of the same two cities; each train's from_station_code and to_station_code say which.","allowed":["station","city"]},{"name":"trains[].train_number","type":"string","description":"Train number."},{"name":"trains[].train_name","type":"string","description":"Short name as printed on reservation charts, for example NAVJEEVAN SF EXP."},{"name":"trains[].extended_train_name","type":"string","description":"The train's full name from RailCore's train catalog, for example Navjeevan SF Express. The same as train_name for a train the catalog does not list."},{"name":"trains[].from_station_code / to_station_code","type":"string","description":"Where this train is boarded and left. With match=city they can be other stations of the two cities than the ones you asked for (BDTS and NZM on a search from MMCT to NDLS); with match=station they are always the two you asked for."},{"name":"trains[].from_station_name / to_station_name","type":"string","description":"Names of those two stations."},{"name":"trains[].departure_time / arrival_time","type":"string","description":"Scheduled segment times in HH:mm."},{"name":"trains[].duration_minutes","type":"integer","description":"Segment duration."},{"name":"trains[].distance_km","type":"number | null","description":"Segment distance."},{"name":"trains[].train_type","type":"string","description":"Normalized train type."},{"name":"trains[].classes","type":"ClassCode[]","description":"Offered travel classes."},{"name":"trains[].running_days","type":"RunningDay[]","description":"Weekly running pattern."},{"name":"trains[].has_pantry","type":"boolean | null","description":"Pantry availability when known."},{"name":"trains[].availability_summary","type":"AvailabilityMini[]","description":"Compact class-level status, fare, confidence, and update time. last_updated_at is India time with its offset, and can be days old: for a fresh figure call seat availability."}],"response_example":{"success":true,"data":{"from_station_code":"BSL","to_station_code":"ADI","journey_date":"{{date:days_ahead_utc:7}}","quota":"GN","matched_by":"station","trains":[{"train_number":"12656","from_station_code":"BSL","from_station_name":"Bhusaval Junction","to_station_code":"ADI","to_station_name":"Ahmedabad Junction","train_name":"NAVJEEVAN SF EXP","extended_train_name":"Navjeevan SF Express","departure_time":"10:25","arrival_time":"18:00","duration_minutes":455,"distance_km":563,"train_type":"SF","classes":["SL","3A","2A","1A"],"running_days":["MON","TUE","WED","THU","FRI","SAT","SUN"],"has_pantry":true,"availability_summary":[{"class_code":"3A","status":"AVAILABLE","text":"AVAILABLE-4","fare":965,"confidence":"high","last_updated_at":"{{date:today_ist}}T08:15:46.547+05:30"}]}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.608Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.608Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":404,"code":"NO_TRAINS_FOUND","description":"No train was found between the two stations on that date (with match=station, between those two stations only), or a station code does not exist. Not counted. trains is never empty.","retryable":false,"category":"NOT_FOUND","fix":"Try another date, nearby stations, or match=city to include every station in both cities."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/journey-search","markdown_url":"https://railcore.tech/docs/api/journey-search.md","markdown":"# Journey search\n\nSearch and rank route options for a journey UI.\n\n`GET /v1/journeys/search`\n\n- **Scope:** `journeys:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nUses the route-train contract with ranking tuned for search experiences.\n\n```\nJOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/journeys/search?from=BSL&to=ADI&date=$JOURNEY_DATE&match=city\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"from_station_code\": \"BSL\",\n    \"to_station_code\": \"ADI\",\n    \"journey_date\": \"2026-11-27\",\n    \"quota\": \"GN\",\n    \"matched_by\": \"station\",\n    \"trains\": [\n      {\n        \"train_number\": \"12656\",\n        \"from_station_code\": \"BSL\",\n        \"from_station_name\": \"Bhusaval Junction\",\n        \"to_station_code\": \"ADI\",\n        \"to_station_name\": \"Ahmedabad Junction\",\n        \"train_name\": \"NAVJEEVAN SF EXP\",\n        \"extended_train_name\": \"Navjeevan SF Express\",\n        \"departure_time\": \"10:25\",\n        \"arrival_time\": \"18:00\",\n        \"duration_minutes\": 455,\n        \"distance_km\": 563,\n        \"train_type\": \"SF\",\n        \"classes\": [\"SL\", \"3A\", \"2A\", \"1A\"],\n        \"running_days\": [\"MON\", \"TUE\", \"WED\", \"THU\", \"FRI\", \"SAT\", \"SUN\"],\n        \"has_pantry\": true,\n        \"availability_summary\": [\n          {\n            \"class_code\": \"3A\",\n            \"status\": \"AVAILABLE\",\n            \"text\": \"AVAILABLE-4\",\n            \"fare\": 965,\n            \"confidence\": \"high\",\n            \"last_updated_at\": \"2026-11-20T08:15:46.547+05:30\"\n          }\n        ]\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.608Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.608Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `journeys:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `from` string required Boarding station code. Example BSL\n- `to` string required Destination station code. Example ADI\n- `date` string(date) required Journey date in YYYY-MM-DD format. Example 2026-11-27\n- `match` string optional city (the default) lists trains between any station of the two cities: a search from MMCT to NDLS also lists trains from BDTS to NZM. station lists only trains between the two stations you asked for. The answer's matched_by says which it is. Example city Default city city station\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `from_station_code` string Resolved origin.\n- `to_station_code` string Resolved destination.\n- `journey_date` string(date) Requested journey date.\n- `quota` Quota Applied reservation quota.\n- `matched_by` string station: every train runs between the two stations you asked for. city: some trains run between other stations of the same two cities; each train's from_station_code and to_station_code say which. station city\n- `trains[].train_number` string Train number.\n- `trains[].train_name` string Short name as printed on reservation charts, for example NAVJEEVAN SF EXP.\n- `trains[].extended_train_name` string The train's full name from RailCore's train catalog, for example Navjeevan SF Express. The same as train_name for a train the catalog does not list.\n- `trains[].from_station_code / to_station_code` string Where this train is boarded and left. With match=city they can be other stations of the two cities than the ones you asked for (BDTS and NZM on a search from MMCT to NDLS); with match=station they are always the two you asked for.\n- `trains[].from_station_name / to_station_name` string Names of those two stations.\n- `trains[].departure_time / arrival_time` string Scheduled segment times in HH:mm.\n- `trains[].duration_minutes` integer Segment duration.\n- `trains[].distance_km` number | null Segment distance.\n- `trains[].train_type` string Normalized train type.\n- `trains[].classes` ClassCode[] Offered travel classes.\n- `trains[].running_days` RunningDay[] Weekly running pattern.\n- `trains[].has_pantry` boolean | null Pantry availability when known.\n- `trains[].availability_summary` AvailabilityMini[] Compact class-level status, fare, confidence, and update time. last_updated_at is India time with its offset, and can be days old: for a fresh figure call seat availability.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [NO_TRAINS_FOUND](https://railcore.tech/docs/errors-reference#error-NO_TRAINS_FOUND) Do not retry unchanged No train was found between the two stations on that date (with match=station, between those two stations only), or a station code does not exist. Not counted. trains is never empty.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/journey-search\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/journeys/search?from=BSL&to=ADI&date=$JOURNEY_DATE&match=city\"","node":"const journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst response = await fetch(`https://ir.railcore.tech/v1/journeys/search?from=BSL&to=ADI&date=${journeyDate}&match=city`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/journeys/search?from=BSL&to=ADI&date={journey_date}&match=city\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/journeys/search?from=BSL&to=ADI&date={$journeyDate}&match=city\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/journeys/search?from=BSL&to=ADI&date=\" + journeyDate + \"&match=city\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/journeys/search?from=BSL&to=ADI&date=\" + journeyDate + \"&match=city\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/journeys/search\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"date=${JOURNEY_DATE}&from=BSL&match=city&to=ADI\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst method = \"GET\";\nconst path = \"/v1/journeys/search\";\nconst params = [\n  [\"from\", \"BSL\"],\n  [\"to\", \"ADI\"],\n  [\"date\", journeyDate],\n  [\"match\", \"city\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nmethod = \"GET\"\npath = \"/v1/journeys/search\"\nparams = [\n    (\"from\", \"BSL\"),\n    (\"to\", \"ADI\"),\n    (\"date\", journey_date),\n    (\"match\", \"city\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$method = \"GET\";\n$path = \"/v1/journeys/search\";\n$params = [\n    [\"from\", \"BSL\"],\n    [\"to\", \"ADI\"],\n    [\"date\", $journeyDate],\n    [\"match\", \"city\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/journeys/search\"\n\tparams := [][2]string{\n\t\t{\"from\", \"BSL\"},\n\t\t{\"to\", \"ADI\"},\n\t\t{\"date\", journeyDate},\n\t\t{\"match\", \"city\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        String method = \"GET\";\n        String path = \"/v1/journeys/search\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"from\", \"BSL\"},\n            new String[] {\"to\", \"ADI\"},\n            new String[] {\"date\", journeyDate},\n            new String[] {\"match\", \"city\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"compare-journeys","category":"Journeys","method":"POST","path":"/journeys/compare","url_template":"https://ir.railcore.tech/v1/journeys/compare","title":"Compare journeys","summary":"Compare up to 5 route queries in one request.","description":"Runs route searches in parallel and returns per-item results so one failed comparison does not discard successful ones.","scope":"journeys:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"per-unit","requests":1,"unit":"route compared","minimum":1,"text":"1 request per route compared, minimum 1 request"},"response_format":"json","parameters":[],"body_fields":[{"name":"journeys","type":"JourneyInput[]","required":true,"description":"Array with 1 to 5 journey objects. Each one counts as 1 request."},{"name":"journeys[].from","type":"string","required":true,"description":"Boarding station code."},{"name":"journeys[].to","type":"string","required":true,"description":"Destination station code."},{"name":"journeys[].date","type":"string(date)","required":true,"description":"Journey date."},{"name":"journeys[].quota","type":"Quota","description":"Optional reservation quota."}],"body_example":{"journeys":[{"from":"BSL","to":"ADI","date":"{{date:days_ahead_utc:7}}","quota":"GN"},{"from":"NDLS","to":"BCT","date":"{{date:days_ahead_utc:8}}","quota":"GN"}]},"response_fields":[{"name":"results[]","type":"RouteTrains[]","description":"One route result for each input, in order, or an inline failure with error and message: NO_TRAINS_FOUND when no train was found for that route. Each result carries matched_by; a comparison matches by city, as trains between stations does by default."},{"name":"results[].from_station_code","type":"string","description":"Resolved origin."},{"name":"results[].to_station_code","type":"string","description":"Resolved destination."},{"name":"results[].journey_date","type":"string(date)","description":"Requested journey date."},{"name":"results[].quota","type":"Quota","description":"Applied reservation quota."},{"name":"results[].matched_by","type":"string","description":"station: every train runs between the two stations you asked for. city: some trains run between other stations of the same two cities; each train's from_station_code and to_station_code say which.","allowed":["station","city"]},{"name":"results[].trains[].train_number","type":"string","description":"Train number."},{"name":"results[].trains[].train_name","type":"string","description":"Short name as printed on reservation charts, for example NAVJEEVAN SF EXP."},{"name":"results[].trains[].extended_train_name","type":"string","description":"The train's full name from RailCore's train catalog, for example Navjeevan SF Express. The same as train_name for a train the catalog does not list."},{"name":"results[].trains[].from_station_code / to_station_code","type":"string","description":"Where this train is boarded and left. With match=city they can be other stations of the two cities than the ones you asked for (BDTS and NZM on a search from MMCT to NDLS); with match=station they are always the two you asked for."},{"name":"results[].trains[].from_station_name / to_station_name","type":"string","description":"Names of those two stations."},{"name":"results[].trains[].departure_time / arrival_time","type":"string","description":"Scheduled segment times in HH:mm."},{"name":"results[].trains[].duration_minutes","type":"integer","description":"Segment duration."},{"name":"results[].trains[].distance_km","type":"number | null","description":"Segment distance."},{"name":"results[].trains[].train_type","type":"string","description":"Normalized train type."},{"name":"results[].trains[].classes","type":"ClassCode[]","description":"Offered travel classes."},{"name":"results[].trains[].running_days","type":"RunningDay[]","description":"Weekly running pattern."},{"name":"results[].trains[].has_pantry","type":"boolean | null","description":"Pantry availability when known."},{"name":"results[].trains[].availability_summary","type":"AvailabilityMini[]","description":"Compact class-level status, fare, confidence, and update time. last_updated_at is India time with its offset, and can be days old: for a fresh figure call seat availability."}],"response_example":{"success":true,"data":{"results":[{"from_station_code":"BSL","to_station_code":"ADI","journey_date":"{{date:days_ahead_utc:7}}","quota":"GN","matched_by":"station","trains":[{"train_number":"12656","from_station_code":"BSL","from_station_name":"Bhusaval Junction","to_station_code":"ADI","to_station_name":"Ahmedabad Junction","train_name":"NAVJEEVAN SF EXP","extended_train_name":"Navjeevan SF Express","departure_time":"10:25","arrival_time":"18:00","duration_minutes":455,"distance_km":563,"train_type":"SF","classes":["SL","3A","2A","1A"],"running_days":["MON","TUE","WED","THU","FRI","SAT","SUN"],"has_pantry":true,"availability_summary":[{"class_code":"3A","status":"AVAILABLE","text":"AVAILABLE-4","fare":965,"confidence":"high","last_updated_at":"{{date:today_ist}}T08:15:46.547+05:30"}]}]}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":["A request that answers 200 is counted at the size it asked for: a route that fails inside the response still counts. A request refused as a whole (4xx or 5xx) is free."],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/compare-journeys","markdown_url":"https://railcore.tech/docs/api/compare-journeys.md","markdown":"# Compare journeys\n\nCompare up to 5 route queries in one request.\n\n`POST /v1/journeys/compare`\n\n- **Scope:** `journeys:read`\n- **Cost:** 1 request per route compared, minimum 1 request\n- **Plans:** All plans\n\nRuns route searches in parallel and returns per-item results so one failed comparison does not discard successful ones.\n\n```\nJOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nJOURNEY_DATE_2=$(date -u -d \"+8 days\" +%F 2>/dev/null || date -u -v+8d +%F)\n\ncurl -sS -X POST \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  --data '{\"journeys\":[{\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$JOURNEY_DATE\"'\",\"quota\":\"GN\"},{\"from\":\"NDLS\",\"to\":\"BCT\",\"date\":\"'\"$JOURNEY_DATE_2\"'\",\"quota\":\"GN\"}]}' \\\n  \"https://ir.railcore.tech/v1/journeys/compare\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"results\": [\n      {\n        \"from_station_code\": \"BSL\",\n        \"to_station_code\": \"ADI\",\n        \"journey_date\": \"2026-11-27\",\n        \"quota\": \"GN\",\n        \"matched_by\": \"station\",\n        \"trains\": [\n          {\n            \"train_number\": \"12656\",\n            \"from_station_code\": \"BSL\",\n            \"from_station_name\": \"Bhusaval Junction\",\n            \"to_station_code\": \"ADI\",\n            \"to_station_name\": \"Ahmedabad Junction\",\n            \"train_name\": \"NAVJEEVAN SF EXP\",\n            \"extended_train_name\": \"Navjeevan SF Express\",\n            \"departure_time\": \"10:25\",\n            \"arrival_time\": \"18:00\",\n            \"duration_minutes\": 455,\n            \"distance_km\": 563,\n            \"train_type\": \"SF\",\n            \"classes\": [\"SL\", \"3A\", \"2A\", \"1A\"],\n            \"running_days\": [\"MON\", \"TUE\", \"WED\", \"THU\", \"FRI\", \"SAT\", \"SUN\"],\n            \"has_pantry\": true,\n            \"availability_summary\": [\n              {\n                \"class_code\": \"3A\",\n                \"status\": \"AVAILABLE\",\n                \"text\": \"AVAILABLE-4\",\n                \"fare\": 965,\n                \"confidence\": \"high\",\n                \"last_updated_at\": \"2026-11-20T08:15:46.547+05:30\"\n              }\n            ]\n          }\n        ]\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `journeys:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Request body\n\nSend Content-Type: application/json.\n\n- `journeys` JourneyInput[] required Array with 1 to 5 journey objects. Each one counts as 1 request.\n  - `from` string required Boarding station code.\n  - `to` string required Destination station code.\n  - `date` string(date) required Journey date.\n  - `quota` Quota optional Optional reservation quota.\n\napplication/json\n\n```\n{\n  \"journeys\": [\n    {\n      \"from\": \"BSL\",\n      \"to\": \"ADI\",\n      \"date\": \"2026-11-27\",\n      \"quota\": \"GN\"\n    },\n    {\n      \"from\": \"NDLS\",\n      \"to\": \"BCT\",\n      \"date\": \"2026-11-28\",\n      \"quota\": \"GN\"\n    }\n  ]\n}\n```\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `results[]` RouteTrains[] One route result for each input, in order, or an inline failure with error and message: NO_TRAINS_FOUND when no train was found for that route. Each result carries matched_by; a comparison matches by city, as trains between stations does by default.\n  - `from_station_code` string Resolved origin.\n  - `to_station_code` string Resolved destination.\n  - `journey_date` string(date) Requested journey date.\n  - `quota` Quota Applied reservation quota.\n  - `matched_by` string station: every train runs between the two stations you asked for. city: some trains run between other stations of the same two cities; each train's from_station_code and to_station_code say which. station city\n- `results[].trains[].train_number` string Train number.\n- `results[].trains[].train_name` string Short name as printed on reservation charts, for example NAVJEEVAN SF EXP.\n- `results[].trains[].extended_train_name` string The train's full name from RailCore's train catalog, for example Navjeevan SF Express. The same as train_name for a train the catalog does not list.\n- `results[].trains[].from_station_code / to_station_code` string Where this train is boarded and left. With match=city they can be other stations of the two cities than the ones you asked for (BDTS and NZM on a search from MMCT to NDLS); with match=station they are always the two you asked for.\n- `results[].trains[].from_station_name / to_station_name` string Names of those two stations.\n- `results[].trains[].departure_time / arrival_time` string Scheduled segment times in HH:mm.\n- `results[].trains[].duration_minutes` integer Segment duration.\n- `results[].trains[].distance_km` number | null Segment distance.\n- `results[].trains[].train_type` string Normalized train type.\n- `results[].trains[].classes` ClassCode[] Offered travel classes.\n- `results[].trains[].running_days` RunningDay[] Weekly running pattern.\n- `results[].trains[].has_pantry` boolean | null Pantry availability when known.\n- `results[].trains[].availability_summary` AvailabilityMini[] Compact class-level status, fare, confidence, and update time. last_updated_at is India time with its offset, and can be days old: for a fresh figure call seat availability.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- A request that answers 200 is counted at the size it asked for: a route that fails inside the response still counts. A request refused as a whole (4xx or 5xx) is free.\n\nSource: https://railcore.tech/docs/api/compare-journeys\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nJOURNEY_DATE_2=$(date -u -d \"+8 days\" +%F 2>/dev/null || date -u -v+8d +%F)\n\ncurl -sS -X POST \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  --data '{\"journeys\":[{\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$JOURNEY_DATE\"'\",\"quota\":\"GN\"},{\"from\":\"NDLS\",\"to\":\"BCT\",\"date\":\"'\"$JOURNEY_DATE_2\"'\",\"quota\":\"GN\"}]}' \\\n  \"https://ir.railcore.tech/v1/journeys/compare\"","node":"const journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\nconst journeyDate2 = new Date(Date.now() + 8 * 86_400_000).toISOString().slice(0, 10);\n\nconst response = await fetch(\"https://ir.railcore.tech/v1/journeys/compare\", {\n  method: \"POST\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"Content-Type\": \"application/json\",\n  },\n  body: JSON.stringify({\n  \"journeys\": [\n    {\n      \"from\": \"BSL\",\n      \"to\": \"ADI\",\n      \"date\": journeyDate,\n      \"quota\": \"GN\"\n    },\n    {\n      \"from\": \"NDLS\",\n      \"to\": \"BCT\",\n      \"date\": journeyDate2,\n      \"quota\": \"GN\"\n    }\n  ]\n}),\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\njourney_date_2 = (datetime.date.today() + datetime.timedelta(days=8)).isoformat()\n\nresponse = requests.request(\n    \"POST\",\n    \"https://ir.railcore.tech/v1/journeys/compare\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    json={\"journeys\": [{\"from\": \"BSL\", \"to\": \"ADI\", \"date\": journey_date, \"quota\": \"GN\"}, {\"from\": \"NDLS\", \"to\": \"BCT\", \"date\": journey_date_2, \"quota\": \"GN\"}]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n$journeyDate2 = gmdate(\"Y-m-d\", time() + 8 * 86400);\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/journeys/compare\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"POST\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n        \"Content-Type: application/json\",\n    ],\n    CURLOPT_POSTFIELDS => json_encode([\n        \"journeys\" => [\n            [\n                \"from\" => \"BSL\",\n                \"to\" => \"ADI\",\n                \"date\" => $journeyDate,\n                \"quota\" => \"GN\",\n            ],\n            [\n                \"from\" => \"NDLS\",\n                \"to\" => \"BCT\",\n                \"date\" => $journeyDate2,\n                \"quota\" => \"GN\",\n            ],\n        ],\n    ]),\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\tjourneyDate2 := time.Now().UTC().AddDate(0, 0, 8).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"POST\", \"https://ir.railcore.tech/v1/journeys/compare\", strings.NewReader(`{\n  \"journeys\": [\n    {\n      \"from\": \"BSL\",\n      \"to\": \"ADI\",\n      \"date\": \"` + journeyDate + `\",\n      \"quota\": \"GN\"\n    },\n    {\n      \"from\": \"NDLS\",\n      \"to\": \"BCT\",\n      \"date\": \"` + journeyDate2 + `\",\n      \"quota\": \"GN\"\n    }\n  ]\n}`))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        String journeyDate2 = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(8).toString();\n        String body = \"\"\"\n            {\n              \"journeys\": [\n                {\n                  \"from\": \"BSL\",\n                  \"to\": \"ADI\",\n                  \"date\": \"%s\",\n                  \"quota\": \"GN\"\n                },\n                {\n                  \"from\": \"NDLS\",\n                  \"to\": \"BCT\",\n                  \"date\": \"%s\",\n                  \"quota\": \"GN\"\n                }\n              ]\n            }\n            \"\"\".formatted(journeyDate, journeyDate2);\n\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/journeys/compare\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"Content-Type\", \"application/json\")\n            .POST(HttpRequest.BodyPublishers.ofString(body))\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nJOURNEY_DATE_2=$(date -u -d \"+8 days\" +%F 2>/dev/null || date -u -v+8d +%F)\nMETHOD=POST\nAPI_PATH=\"/v1/journeys/compare\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY='{\"journeys\":[{\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$JOURNEY_DATE\"'\",\"quota\":\"GN\"},{\"from\":\"NDLS\",\"to\":\"BCT\",\"date\":\"'\"$JOURNEY_DATE_2\"'\",\"quota\":\"GN\"}]}'\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  -H \"Content-Type: application/json\" \\\n  --data-binary \"$BODY\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\nconst journeyDate2 = new Date(Date.now() + 8 * 86_400_000).toISOString().slice(0, 10);\n\nconst method = \"POST\";\nconst path = \"/v1/journeys/compare\";\nconst params = [];\nconst body = JSON.stringify({\n  \"journeys\": [\n    {\n      \"from\": \"BSL\",\n      \"to\": \"ADI\",\n      \"date\": journeyDate,\n      \"quota\": \"GN\"\n    },\n    {\n      \"from\": \"NDLS\",\n      \"to\": \"BCT\",\n      \"date\": journeyDate2,\n      \"quota\": \"GN\"\n    }\n  ]\n});\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n    \"Content-Type\": \"application/json\",\n  },\n  body,\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport json\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\njourney_date_2 = (datetime.date.today() + datetime.timedelta(days=8)).isoformat()\n\nmethod = \"POST\"\npath = \"/v1/journeys/compare\"\nparams = []\nbody = json.dumps({\"journeys\": [{\"from\": \"BSL\", \"to\": \"ADI\", \"date\": journey_date, \"quota\": \"GN\"}, {\"from\": \"NDLS\", \"to\": \"BCT\", \"date\": journey_date_2, \"quota\": \"GN\"}]}, separators=(\",\", \":\"))\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n    \"Content-Type\": \"application/json\",\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    data=body.encode(\"utf-8\"),\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n$journeyDate2 = gmdate(\"Y-m-d\", time() + 8 * 86400);\n\n$method = \"POST\";\n$path = \"/v1/journeys/compare\";\n$params = [];\n$body = json_encode([\n    \"journeys\" => [\n        [\n            \"from\" => \"BSL\",\n            \"to\" => \"ADI\",\n            \"date\" => $journeyDate,\n            \"quota\" => \"GN\",\n        ],\n        [\n            \"from\" => \"NDLS\",\n            \"to\" => \"BCT\",\n            \"date\" => $journeyDate2,\n            \"quota\" => \"GN\",\n        ],\n    ],\n]);\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n    \"Content-Type: application/json\",\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\tjourneyDate2 := time.Now().UTC().AddDate(0, 0, 8).Format(\"2006-01-02\")\n\n\tmethod := \"POST\"\n\tpath := \"/v1/journeys/compare\"\n\tparams := [][2]string{}\n\tbody := `{\n  \"journeys\": [\n    {\n      \"from\": \"BSL\",\n      \"to\": \"ADI\",\n      \"date\": \"` + journeyDate + `\",\n      \"quota\": \"GN\"\n    },\n    {\n      \"from\": \"NDLS\",\n      \"to\": \"BCT\",\n      \"date\": \"` + journeyDate2 + `\",\n      \"quota\": \"GN\"\n    }\n  ]\n}`\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        String journeyDate2 = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(8).toString();\n        String method = \"POST\";\n        String path = \"/v1/journeys/compare\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"{\\\"journeys\\\":[{\\\"from\\\":\\\"BSL\\\",\\\"to\\\":\\\"ADI\\\",\\\"date\\\":\\\"\" + journeyDate + \"\\\",\\\"quota\\\":\\\"GN\\\"},{\\\"from\\\":\\\"NDLS\\\",\\\"to\\\":\\\"BCT\\\",\\\"date\\\":\\\"\" + journeyDate2 + \"\\\",\\\"quota\\\":\\\"GN\\\"}]}\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"seat-availability","category":"Availability","method":"GET","path":"/availability/seats","url_template":"https://ir.railcore.tech/v1/availability/seats","title":"Seat availability","summary":"Check availability afresh for one train and class.","description":"Asks afresh on every request, with no RailCore cache, and returns normalized availability, waitlist pool, fare, prediction, and when the figure was read.","scope":"availability:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"query","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"},{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code.","example":"ADI","pattern":"^[A-Z0-9]{1,6}$"},{"name":"date","in":"query","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD format.","example":"{{date:days_ahead_utc:7}}"},{"name":"class","in":"query","type":"string","required":true,"description":"Travel class code.","example":"3A","allowed":["1A","2A","3A","3E","CC","EC","SL","2S","GS","FC"]},{"name":"quota","in":"query","type":"string","required":false,"description":"Reservation quota. Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 QUOTA_NOT_SUPPORTED before the seat provider is asked, and is not counted.","example":"GN","default":"GN","allowed":["GN","TQ","SS","LD"]}],"body_fields":[],"response_fields":[{"name":"train_number","type":"string","description":"Train number."},{"name":"from_station_code / to_station_code","type":"string","description":"Requested segment."},{"name":"journey_date","type":"string(date)","description":"Requested journey date."},{"name":"quota","type":"Quota","description":"Applied quota."},{"name":"classes[].class_code","type":"ClassCode","description":"Travel class."},{"name":"classes[].status","type":"string","description":"AVAILABLE, RAC, WAITLIST, REGRET, NOT_AVAILABLE, TRAIN_CANCELLED, TRAIN_DEPARTED, or UNKNOWN."},{"name":"classes[].availability_text","type":"string","description":"Source availability text normalized for display."},{"name":"classes[].available_count","type":"integer | null","description":"Available berth count; null when the source reports availability without a quantity."},{"name":"classes[].waitlist_count / rac_count","type":"integer | null","description":"Current waitlist and RAC positions; null when the active status has no reported position."},{"name":"classes[].wl_pool / wl_pool_position","type":"string / integer","description":"Original booking pool and position, read from the availability text (GNWL276/WL185 gives GNWL and 276). Present only when the text names the pool; left out otherwise. They can stay after the current status becomes RAC or available. Compatibility codes are preserved exactly, without inferred quota descriptions."},{"name":"classes[].fare / total_fare","type":"integer | null","description":"Fare values in INR. total_fare is what the ticket costs; fare is total_fare less catering_charge."},{"name":"classes[].catering_charge","type":"integer","description":"Catering included in total_fare, in INR. 0 on a train without compulsory catering."},{"name":"classes[].fare_breakdown","type":"object | absent","description":"The railway's split of total_fare in INR: base_fare, reservation_charge, superfast_charge, tatkal_charge, dynamic_fare, fuel_charge, other_charge, gst, catering_charge, rounding (what the railway added to reach the next ₹5, 0 to 4) and concession (subtracted). The parts always add up to total_fare; a null part was not given. Absent when the enquiry gave no split."},{"name":"classes[].confirmation_probability","type":"object | null","description":"The chance that a ticket booked now is confirmed: percentage, a LOW/MEDIUM/HIGH label and text. 100 (Available) when seats are available; 0 with the reason in text when no ticket can be booked (Waitlist full (regret) for a REGRET class, whose waitlist is full and can reopen as tickets are cancelled; not available; train departed or cancelled); the forecast for a waitlisted or RAC ticket. Null only for a waitlisted or RAC class with no forecast."},{"name":"classes[].last_updated_at","type":"string | null","description":"When the figure was read at the source. It can be hours before your request when the upstream answers from its own cache, so use it to evaluate freshness."}],"response_example":{"success":true,"data":{"train_number":"12656","from_station_code":"BSL","to_station_code":"ADI","journey_date":"{{date:days_ahead_utc:7}}","quota":"GN","classes":[{"class_code":"3A","status":"AVAILABLE","availability_text":"AVAILABLE-4","available_count":4,"waitlist_count":0,"rac_count":0,"fare":965,"catering_charge":0,"total_fare":965,"fare_breakdown":{"base_fare":834,"reservation_charge":40,"superfast_charge":45,"tatkal_charge":0,"dynamic_fare":0,"fuel_charge":0,"other_charge":0,"gst":46,"catering_charge":0,"concession":0,"rounding":0},"confirmation_probability":{"percentage":100,"label":"HIGH","text":"Available"},"last_updated_at":"{{date:today_ist}}T08:15:46.547+05:30"}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":["Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 QUOTA_NOT_SUPPORTED before the seat provider is asked, and is not counted.","A date past the booking window (reservations open 60 days before the journey, at 8:00 AM in India) is refused with 422 BOOKING_NOT_OPEN before the seat provider is asked, and a day the train does not leave the boarding station with 422 TRAIN_NOT_RUNNING. Neither is counted.","Every request is a fresh enquiry, not a direct PRS connection. The upstream can answer with a figure it read earlier: classes[].last_updated_at says when, so check it before applying your own freshness policy. Upstream identity is intentionally not exposed.","confirmation_probability is filled whenever the status settles it: 100 for an available class, 0 with the reason for one that cannot be booked. It is a forecast only for a waitlisted or RAC class, and null only when such a class has no forecast.","The railway charges the sum of a fare's parts rounded up to the next ₹5. fare_breakdown.rounding is that difference, so the parts add up to total_fare: for example 1188 base + 50 reservation + 45 superfast + 65 GST + 2 rounding = 1350.","Tatkal (TQ) opens the day before the train leaves its origin: 10:00 AM IST for AC classes, 11:00 AM for the rest. Before that the enquiry answers 422 TATKAL_NOT_OPEN with error.opens_at, and is not counted."],"errors":[{"status":422,"code":"TATKAL_NOT_OPEN","description":"Tatkal booking has not opened for the journey yet. error.opens_at (IST) says when, if known. Not counted.","retryable":false,"category":"VALIDATION","fix":"Ask again after the time in error.opens_at (IST). Tatkal opens the day before the train leaves its origin, at 10:00 for AC classes and 11:00 for the rest."},{"status":422,"code":"QUOTA_NOT_SUPPORTED","description":"Seat availability is not offered for that quota on any train: it answers GN, TQ, SS and LD only. Premium Tatkal (PT), HP, DP, HO, YU and FT can be checked on IRCTC. RailCore refuses it before the seat provider is asked. Not counted.","retryable":false,"category":"VALIDATION","fix":"Use GN, TQ, SS or LD. Other quotas, Premium Tatkal included, cannot be checked through RailCore; check them on IRCTC."},{"status":422,"code":"QUOTA_NOT_AVAILABLE","description":"The train does not offer that quota in that class for the journey. Not counted.","retryable":false,"category":"VALIDATION","fix":"Choose another quota or class: the train does not offer this quota in this class."},{"status":422,"code":"CLASS_NOT_AVAILABLE","description":"The train does not carry that class. error.message lists the classes it does. Not counted.","retryable":false,"category":"VALIDATION","fix":"Choose one of the classes the message lists for this train."},{"status":422,"code":"TRAIN_NOT_RUNNING","description":"The train does not leave the boarding station on that date. error.message lists the days it does. Not counted.","retryable":false,"category":"VALIDATION","fix":"Choose one of the days the message lists, or check the boarding station."},{"status":422,"code":"BOOKING_NOT_OPEN","description":"The date has not opened for booking: reservations open 60 days before the journey, at 8:00 AM in India. RailCore refuses it before the seat provider is asked. error.message names the day it opens. Not counted.","retryable":false,"category":"VALIDATION","fix":"Choose a date inside the booking window: reservations open 60 days before the journey, at 08:00 IST."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/seat-availability","markdown_url":"https://railcore.tech/docs/api/seat-availability.md","markdown":"# Seat availability\n\nCheck availability afresh for one train and class.\n\n`GET /v1/availability/seats`\n\n- **Scope:** `availability:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nAsks afresh on every request, with no RailCore cache, and returns normalized availability, waitlist pool, fare, prediction, and when the figure was read.\n\n```\nJOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/availability/seats?train_number=12656&from=BSL&to=ADI&date=$JOURNEY_DATE&class=3A&quota=GN\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"from_station_code\": \"BSL\",\n    \"to_station_code\": \"ADI\",\n    \"journey_date\": \"2026-11-27\",\n    \"quota\": \"GN\",\n    \"classes\": [\n      {\n        \"class_code\": \"3A\",\n        \"status\": \"AVAILABLE\",\n        \"availability_text\": \"AVAILABLE-4\",\n        \"available_count\": 4,\n        \"waitlist_count\": 0,\n        \"rac_count\": 0,\n        \"fare\": 965,\n        \"catering_charge\": 0,\n        \"total_fare\": 965,\n        \"fare_breakdown\": {\n          \"base_fare\": 834,\n          \"reservation_charge\": 40,\n          \"superfast_charge\": 45,\n          \"tatkal_charge\": 0,\n          \"dynamic_fare\": 0,\n          \"fuel_charge\": 0,\n          \"other_charge\": 0,\n          \"gst\": 46,\n          \"catering_charge\": 0,\n          \"concession\": 0,\n          \"rounding\": 0\n        },\n        \"confirmation_probability\": {\n          \"percentage\": 100,\n          \"label\": \"HIGH\",\n          \"text\": \"Available\"\n        },\n        \"last_updated_at\": \"2026-11-20T08:15:46.547+05:30\"\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `availability:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n- `from` string required Boarding station code. Example BSL\n- `to` string required Destination station code. Example ADI\n- `date` string(date) required Journey date in YYYY-MM-DD format. Example 2026-11-27\n- `class` string required Travel class code. Example 3A 1A 2A 3A 3E CC EC SL 2S GS FC\n- `quota` string optional Reservation quota. Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 QUOTA_NOT_SUPPORTED before the seat provider is asked, and is not counted. Example GN Default GN GN TQ SS LD\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number` string Train number.\n- `from_station_code / to_station_code` string Requested segment.\n- `journey_date` string(date) Requested journey date.\n- `quota` Quota Applied quota.\n- `classes[].class_code` ClassCode Travel class.\n- `classes[].status` string AVAILABLE, RAC, WAITLIST, REGRET, NOT_AVAILABLE, TRAIN_CANCELLED, TRAIN_DEPARTED, or UNKNOWN.\n- `classes[].availability_text` string Source availability text normalized for display.\n- `classes[].available_count` integer | null Available berth count; null when the source reports availability without a quantity.\n- `classes[].waitlist_count / rac_count` integer | null Current waitlist and RAC positions; null when the active status has no reported position.\n- `classes[].wl_pool / wl_pool_position` string / integer Original booking pool and position, read from the availability text (GNWL276/WL185 gives GNWL and 276). Present only when the text names the pool; left out otherwise. They can stay after the current status becomes RAC or available. Compatibility codes are preserved exactly, without inferred quota descriptions.\n- `classes[].fare / total_fare` integer | null Fare values in INR. total_fare is what the ticket costs; fare is total_fare less catering_charge.\n- `classes[].catering_charge` integer Catering included in total_fare, in INR. 0 on a train without compulsory catering.\n- `classes[].fare_breakdown` object | absent The railway's split of total_fare in INR: base_fare, reservation_charge, superfast_charge, tatkal_charge, dynamic_fare, fuel_charge, other_charge, gst, catering_charge, rounding (what the railway added to reach the next ₹5, 0 to 4) and concession (subtracted). The parts always add up to total_fare; a null part was not given. Absent when the enquiry gave no split.\n- `classes[].confirmation_probability` object | null The chance that a ticket booked now is confirmed: percentage, a LOW/MEDIUM/HIGH label and text. 100 (Available) when seats are available; 0 with the reason in text when no ticket can be booked (Waitlist full (regret) for a REGRET class, whose waitlist is full and can reopen as tickets are cancelled; not available; train departed or cancelled); the forecast for a waitlisted or RAC ticket. Null only for a waitlisted or RAC class with no forecast.\n- `classes[].last_updated_at` string | null When the figure was read at the source. It can be hours before your request when the upstream answers from its own cache, so use it to evaluate freshness.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 422 [TATKAL_NOT_OPEN](https://railcore.tech/docs/errors-reference#error-TATKAL_NOT_OPEN) Do not retry unchanged Tatkal booking has not opened for the journey yet. error.opens_at (IST) says when, if known. Not counted.\n- 422 [QUOTA_NOT_SUPPORTED](https://railcore.tech/docs/errors-reference#error-QUOTA_NOT_SUPPORTED) Do not retry unchanged Seat availability is not offered for that quota on any train: it answers GN, TQ, SS and LD only. Premium Tatkal (PT), HP, DP, HO, YU and FT can be checked on IRCTC. RailCore refuses it before the seat provider is asked. Not counted.\n- 422 [QUOTA_NOT_AVAILABLE](https://railcore.tech/docs/errors-reference#error-QUOTA_NOT_AVAILABLE) Do not retry unchanged The train does not offer that quota in that class for the journey. Not counted.\n- 422 [CLASS_NOT_AVAILABLE](https://railcore.tech/docs/errors-reference#error-CLASS_NOT_AVAILABLE) Do not retry unchanged The train does not carry that class. error.message lists the classes it does. Not counted.\n- 422 [TRAIN_NOT_RUNNING](https://railcore.tech/docs/errors-reference#error-TRAIN_NOT_RUNNING) Do not retry unchanged The train does not leave the boarding station on that date. error.message lists the days it does. Not counted.\n- 422 [BOOKING_NOT_OPEN](https://railcore.tech/docs/errors-reference#error-BOOKING_NOT_OPEN) Do not retry unchanged The date has not opened for booking: reservations open 60 days before the journey, at 8:00 AM in India. RailCore refuses it before the seat provider is asked. error.message names the day it opens. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 QUOTA_NOT_SUPPORTED before the seat provider is asked, and is not counted.\n- A date past the booking window (reservations open 60 days before the journey, at 8:00 AM in India) is refused with 422 BOOKING_NOT_OPEN before the seat provider is asked, and a day the train does not leave the boarding station with 422 TRAIN_NOT_RUNNING. Neither is counted.\n- Every request is a fresh enquiry, not a direct PRS connection. The upstream can answer with a figure it read earlier: classes[].last_updated_at says when, so check it before applying your own freshness policy. Upstream identity is intentionally not exposed.\n- confirmation_probability is filled whenever the status settles it: 100 for an available class, 0 with the reason for one that cannot be booked. It is a forecast only for a waitlisted or RAC class, and null only when such a class has no forecast.\n- The railway charges the sum of a fare's parts rounded up to the next ₹5. fare_breakdown.rounding is that difference, so the parts add up to total_fare: for example 1188 base + 50 reservation + 45 superfast + 65 GST + 2 rounding = 1350.\n- Tatkal (TQ) opens the day before the train leaves its origin: 10:00 AM IST for AC classes, 11:00 AM for the rest. Before that the enquiry answers 422 TATKAL_NOT_OPEN with error.opens_at, and is not counted.\n\nSource: https://railcore.tech/docs/api/seat-availability\nLast updated: 19 Nov 2026\n","samples":{"unsigned":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/availability/seats?train_number=12656&from=BSL&to=ADI&date=$JOURNEY_DATE&class=3A&quota=GN\"","node":"const journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst response = await fetch(`https://ir.railcore.tech/v1/availability/seats?train_number=12656&from=BSL&to=ADI&date=${journeyDate}&class=3A&quota=GN`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/availability/seats?train_number=12656&from=BSL&to=ADI&date={journey_date}&class=3A&quota=GN\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/availability/seats?train_number=12656&from=BSL&to=ADI&date={$journeyDate}&class=3A&quota=GN\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/availability/seats?train_number=12656&from=BSL&to=ADI&date=\" + journeyDate + \"&class=3A&quota=GN\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/availability/seats?train_number=12656&from=BSL&to=ADI&date=\" + journeyDate + \"&class=3A&quota=GN\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/availability/seats\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"class=3A&date=${JOURNEY_DATE}&from=BSL&quota=GN&to=ADI&train_number=12656\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst method = \"GET\";\nconst path = \"/v1/availability/seats\";\nconst params = [\n  [\"train_number\", \"12656\"],\n  [\"from\", \"BSL\"],\n  [\"to\", \"ADI\"],\n  [\"date\", journeyDate],\n  [\"class\", \"3A\"],\n  [\"quota\", \"GN\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nmethod = \"GET\"\npath = \"/v1/availability/seats\"\nparams = [\n    (\"train_number\", \"12656\"),\n    (\"from\", \"BSL\"),\n    (\"to\", \"ADI\"),\n    (\"date\", journey_date),\n    (\"class\", \"3A\"),\n    (\"quota\", \"GN\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$method = \"GET\";\n$path = \"/v1/availability/seats\";\n$params = [\n    [\"train_number\", \"12656\"],\n    [\"from\", \"BSL\"],\n    [\"to\", \"ADI\"],\n    [\"date\", $journeyDate],\n    [\"class\", \"3A\"],\n    [\"quota\", \"GN\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/availability/seats\"\n\tparams := [][2]string{\n\t\t{\"train_number\", \"12656\"},\n\t\t{\"from\", \"BSL\"},\n\t\t{\"to\", \"ADI\"},\n\t\t{\"date\", journeyDate},\n\t\t{\"class\", \"3A\"},\n\t\t{\"quota\", \"GN\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        String method = \"GET\";\n        String path = \"/v1/availability/seats\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"train_number\", \"12656\"},\n            new String[] {\"from\", \"BSL\"},\n            new String[] {\"to\", \"ADI\"},\n            new String[] {\"date\", journeyDate},\n            new String[] {\"class\", \"3A\"},\n            new String[] {\"quota\", \"GN\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"batch-seat-availability","category":"Availability","method":"POST","path":"/availability/seats/batch","url_template":"https://ir.railcore.tech/v1/availability/seats/batch","title":"Batch seat availability","summary":"Check up to 25 train and class combinations.","description":"Returns independent availability results for every item. Each distinct class asked for on each item counts as one request. Classes are compared without regard to case or surrounding spaces, so \"SL\", \"sl\" and \"SL\" again in one item count once.","scope":"availability:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"per-unit","requests":1,"unit":"distinct class per item","minimum":1,"text":"1 request per distinct class per item, minimum 1 request"},"response_format":"json","parameters":[],"body_fields":[{"name":"items","type":"AvailabilityInput[]","required":true,"description":"Array with 1 to 25 items."},{"name":"items[].train_number","type":"string","required":true,"description":"Train number."},{"name":"items[].from","type":"string","required":true,"description":"Boarding station code."},{"name":"items[].to","type":"string","required":true,"description":"Destination station code."},{"name":"items[].date","type":"string(date)","required":true,"description":"Journey date."},{"name":"items[].classes","type":"ClassCode[]","description":"Up to 8 classes; a class repeated in one item is checked and counted once. Left out or empty, the train's own bookable classes are checked and counted (for a train RailCore does not list, 4 default classes)."},{"name":"items[].quota","type":"Quota","description":"Optional reservation quota. Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 QUOTA_NOT_SUPPORTED before the seat provider is asked, and is not counted."}],"body_example":{"items":[{"train_number":"12656","from":"BSL","to":"ADI","date":"{{date:days_ahead_utc:7}}","classes":["SL","3A"],"quota":"GN"},{"train_number":"12952","from":"NDLS","to":"BCT","date":"{{date:days_ahead_utc:8}}","classes":["2A"],"quota":"GN"}]},"response_fields":[{"name":"results[]","type":"AvailabilityResponse[]","description":"Per-input availability result."},{"name":"results[].train_number","type":"string","description":"Train number."},{"name":"results[].from_station_code / to_station_code","type":"string","description":"Requested segment."},{"name":"results[].journey_date","type":"string(date)","description":"Requested journey date."},{"name":"results[].quota","type":"Quota","description":"Applied quota."},{"name":"results[].classes[].class_code","type":"ClassCode","description":"Travel class."},{"name":"results[].classes[].status","type":"string","description":"AVAILABLE, RAC, WAITLIST, REGRET, NOT_AVAILABLE, TRAIN_CANCELLED, TRAIN_DEPARTED, or UNKNOWN."},{"name":"results[].classes[].availability_text","type":"string","description":"Source availability text normalized for display."},{"name":"results[].classes[].available_count","type":"integer | null","description":"Available berth count; null when the source reports availability without a quantity."},{"name":"results[].classes[].waitlist_count / rac_count","type":"integer | null","description":"Current waitlist and RAC positions; null when the active status has no reported position."},{"name":"results[].classes[].wl_pool / wl_pool_position","type":"string / integer","description":"Original booking pool and position, read from the availability text (GNWL276/WL185 gives GNWL and 276). Present only when the text names the pool; left out otherwise. They can stay after the current status becomes RAC or available. Compatibility codes are preserved exactly, without inferred quota descriptions."},{"name":"results[].classes[].fare / total_fare","type":"integer | null","description":"Fare values in INR. total_fare is what the ticket costs; fare is total_fare less catering_charge."},{"name":"results[].classes[].catering_charge","type":"integer","description":"Catering included in total_fare, in INR. 0 on a train without compulsory catering."},{"name":"results[].classes[].fare_breakdown","type":"object | absent","description":"The railway's split of total_fare in INR: base_fare, reservation_charge, superfast_charge, tatkal_charge, dynamic_fare, fuel_charge, other_charge, gst, catering_charge, rounding (what the railway added to reach the next ₹5, 0 to 4) and concession (subtracted). The parts always add up to total_fare; a null part was not given. Absent when the enquiry gave no split."},{"name":"results[].classes[].confirmation_probability","type":"object | null","description":"The chance that a ticket booked now is confirmed: percentage, a LOW/MEDIUM/HIGH label and text. 100 (Available) when seats are available; 0 with the reason in text when no ticket can be booked (Waitlist full (regret) for a REGRET class, whose waitlist is full and can reopen as tickets are cancelled; not available; train departed or cancelled); the forecast for a waitlisted or RAC ticket. Null only for a waitlisted or RAC class with no forecast."},{"name":"results[].classes[].last_updated_at","type":"string | null","description":"When the figure was read at the source. It can be hours before your request when the upstream answers from its own cache, so use it to evaluate freshness."}],"response_example":{"success":true,"data":{"results":[{"train_number":"12656","from_station_code":"BSL","to_station_code":"ADI","journey_date":"{{date:days_ahead_utc:7}}","quota":"GN","classes":[{"class_code":"3A","status":"AVAILABLE","availability_text":"AVAILABLE-4","available_count":4,"waitlist_count":0,"rac_count":0,"fare":965,"catering_charge":0,"total_fare":965,"fare_breakdown":{"base_fare":834,"reservation_charge":40,"superfast_charge":45,"tatkal_charge":0,"dynamic_fare":0,"fuel_charge":0,"other_charge":0,"gst":46,"catering_charge":0,"concession":0,"rounding":0},"confirmation_probability":{"percentage":100,"label":"HIGH","text":"Available"},"last_updated_at":"{{date:today_ist}}T08:15:46.547+05:30"}]}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":["An item without classes, or with an empty list, is checked and counted in the classes its train carries: two for a Shatabdi (EC and CC), four for a train with 1A, 2A, 3A and SL. A train RailCore does not list is checked in SL, 3A, 2A and 1A and counts 4. The largest batch, 25 items with 8 classes each, counts as 200 requests.","A request that answers 200 is counted at the size it asked for: an item that fails inside the response still counts. A request refused as a whole (4xx or 5xx) is free.","An item whose date is past the booking window is not asked and not counted. It comes back in its place in results as a failed item: { \"error\": \"BOOKING_NOT_OPEN\", \"message\", \"train_number\", \"from_station_code\", \"to_station_code\", \"journey_date\" }. When every item is past the window, the whole request answers 422 BOOKING_NOT_OPEN."],"errors":[{"status":422,"code":"QUOTA_NOT_SUPPORTED","description":"No item names a quota seat availability answers (GN, TQ, SS, LD). Such an item among others comes back in its place as a failed item with error QUOTA_NOT_SUPPORTED instead, and is not counted.","retryable":false,"category":"VALIDATION","fix":"Use GN, TQ, SS or LD. Other quotas, Premium Tatkal included, cannot be checked through RailCore; check them on IRCTC."},{"status":422,"code":"BOOKING_NOT_OPEN","description":"Every item's date is past the booking window: reservations open 60 days before the journey, at 8:00 AM in India. An item past the window among others comes back as a failed item instead. Not counted.","retryable":false,"category":"VALIDATION","fix":"Choose a date inside the booking window: reservations open 60 days before the journey, at 08:00 IST."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/batch-seat-availability","markdown_url":"https://railcore.tech/docs/api/batch-seat-availability.md","markdown":"# Batch seat availability\n\nCheck up to 25 train and class combinations.\n\n`POST /v1/availability/seats/batch`\n\n- **Scope:** `availability:read`\n- **Cost:** 1 request per distinct class per item, minimum 1 request\n- **Plans:** All plans\n\nReturns independent availability results for every item. Each distinct class asked for on each item counts as one request. Classes are compared without regard to case or surrounding spaces, so \"SL\", \"sl\" and \"SL\" again in one item count once.\n\n```\nJOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nJOURNEY_DATE_2=$(date -u -d \"+8 days\" +%F 2>/dev/null || date -u -v+8d +%F)\n\ncurl -sS -X POST \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  --data '{\"items\":[{\"train_number\":\"12656\",\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$JOURNEY_DATE\"'\",\"classes\":[\"SL\",\"3A\"],\"quota\":\"GN\"},{\"train_number\":\"12952\",\"from\":\"NDLS\",\"to\":\"BCT\",\"date\":\"'\"$JOURNEY_DATE_2\"'\",\"classes\":[\"2A\"],\"quota\":\"GN\"}]}' \\\n  \"https://ir.railcore.tech/v1/availability/seats/batch\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"results\": [\n      {\n        \"train_number\": \"12656\",\n        \"from_station_code\": \"BSL\",\n        \"to_station_code\": \"ADI\",\n        \"journey_date\": \"2026-11-27\",\n        \"quota\": \"GN\",\n        \"classes\": [\n          {\n            \"class_code\": \"3A\",\n            \"status\": \"AVAILABLE\",\n            \"availability_text\": \"AVAILABLE-4\",\n            \"available_count\": 4,\n            \"waitlist_count\": 0,\n            \"rac_count\": 0,\n            \"fare\": 965,\n            \"catering_charge\": 0,\n            \"total_fare\": 965,\n            \"fare_breakdown\": {\n              \"base_fare\": 834,\n              \"reservation_charge\": 40,\n              \"superfast_charge\": 45,\n              \"tatkal_charge\": 0,\n              \"dynamic_fare\": 0,\n              \"fuel_charge\": 0,\n              \"other_charge\": 0,\n              \"gst\": 46,\n              \"catering_charge\": 0,\n              \"concession\": 0,\n              \"rounding\": 0\n            },\n            \"confirmation_probability\": {\n              \"percentage\": 100,\n              \"label\": \"HIGH\",\n              \"text\": \"Available\"\n            },\n            \"last_updated_at\": \"2026-11-20T08:15:46.547+05:30\"\n          }\n        ]\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `availability:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Request body\n\nSend Content-Type: application/json.\n\n- `items` AvailabilityInput[] required Array with 1 to 25 items.\n  - `train_number` string required Train number.\n  - `from` string required Boarding station code.\n  - `to` string required Destination station code.\n  - `date` string(date) required Journey date.\n  - `classes` ClassCode[] optional Up to 8 classes; a class repeated in one item is checked and counted once. Left out or empty, the train's own bookable classes are checked and counted (for a train RailCore does not list, 4 default classes).\n  - `quota` Quota optional Optional reservation quota. Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 QUOTA_NOT_SUPPORTED before the seat provider is asked, and is not counted.\n\napplication/json\n\n```\n{\n  \"items\": [\n    {\n      \"train_number\": \"12656\",\n      \"from\": \"BSL\",\n      \"to\": \"ADI\",\n      \"date\": \"2026-11-27\",\n      \"classes\": [\n        \"SL\",\n        \"3A\"\n      ],\n      \"quota\": \"GN\"\n    },\n    {\n      \"train_number\": \"12952\",\n      \"from\": \"NDLS\",\n      \"to\": \"BCT\",\n      \"date\": \"2026-11-28\",\n      \"classes\": [\n        \"2A\"\n      ],\n      \"quota\": \"GN\"\n    }\n  ]\n}\n```\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `results[]` AvailabilityResponse[] Per-input availability result.\n  - `train_number` string Train number.\n  - `from_station_code / to_station_code` string Requested segment.\n  - `journey_date` string(date) Requested journey date.\n  - `quota` Quota Applied quota.\n- `results[].classes[].class_code` ClassCode Travel class.\n- `results[].classes[].status` string AVAILABLE, RAC, WAITLIST, REGRET, NOT_AVAILABLE, TRAIN_CANCELLED, TRAIN_DEPARTED, or UNKNOWN.\n- `results[].classes[].availability_text` string Source availability text normalized for display.\n- `results[].classes[].available_count` integer | null Available berth count; null when the source reports availability without a quantity.\n- `results[].classes[].waitlist_count / rac_count` integer | null Current waitlist and RAC positions; null when the active status has no reported position.\n- `results[].classes[].wl_pool / wl_pool_position` string / integer Original booking pool and position, read from the availability text (GNWL276/WL185 gives GNWL and 276). Present only when the text names the pool; left out otherwise. They can stay after the current status becomes RAC or available. Compatibility codes are preserved exactly, without inferred quota descriptions.\n- `results[].classes[].fare / total_fare` integer | null Fare values in INR. total_fare is what the ticket costs; fare is total_fare less catering_charge.\n- `results[].classes[].catering_charge` integer Catering included in total_fare, in INR. 0 on a train without compulsory catering.\n- `results[].classes[].fare_breakdown` object | absent The railway's split of total_fare in INR: base_fare, reservation_charge, superfast_charge, tatkal_charge, dynamic_fare, fuel_charge, other_charge, gst, catering_charge, rounding (what the railway added to reach the next ₹5, 0 to 4) and concession (subtracted). The parts always add up to total_fare; a null part was not given. Absent when the enquiry gave no split.\n- `results[].classes[].confirmation_probability` object | null The chance that a ticket booked now is confirmed: percentage, a LOW/MEDIUM/HIGH label and text. 100 (Available) when seats are available; 0 with the reason in text when no ticket can be booked (Waitlist full (regret) for a REGRET class, whose waitlist is full and can reopen as tickets are cancelled; not available; train departed or cancelled); the forecast for a waitlisted or RAC ticket. Null only for a waitlisted or RAC class with no forecast.\n- `results[].classes[].last_updated_at` string | null When the figure was read at the source. It can be hours before your request when the upstream answers from its own cache, so use it to evaluate freshness.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 422 [QUOTA_NOT_SUPPORTED](https://railcore.tech/docs/errors-reference#error-QUOTA_NOT_SUPPORTED) Do not retry unchanged No item names a quota seat availability answers (GN, TQ, SS, LD). Such an item among others comes back in its place as a failed item with error QUOTA_NOT_SUPPORTED instead, and is not counted.\n- 422 [BOOKING_NOT_OPEN](https://railcore.tech/docs/errors-reference#error-BOOKING_NOT_OPEN) Do not retry unchanged Every item's date is past the booking window: reservations open 60 days before the journey, at 8:00 AM in India. An item past the window among others comes back as a failed item instead. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- An item without classes, or with an empty list, is checked and counted in the classes its train carries: two for a Shatabdi (EC and CC), four for a train with 1A, 2A, 3A and SL. A train RailCore does not list is checked in SL, 3A, 2A and 1A and counts 4. The largest batch, 25 items with 8 classes each, counts as 200 requests.\n- A request that answers 200 is counted at the size it asked for: an item that fails inside the response still counts. A request refused as a whole (4xx or 5xx) is free.\n- An item whose date is past the booking window is not asked and not counted. It comes back in its place in results as a failed item: { \"error\": \"BOOKING_NOT_OPEN\", \"message\", \"train_number\", \"from_station_code\", \"to_station_code\", \"journey_date\" }. When every item is past the window, the whole request answers 422 BOOKING_NOT_OPEN.\n\nSource: https://railcore.tech/docs/api/batch-seat-availability\nLast updated: 19 Nov 2026\n","samples":{"unsigned":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nJOURNEY_DATE_2=$(date -u -d \"+8 days\" +%F 2>/dev/null || date -u -v+8d +%F)\n\ncurl -sS -X POST \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  --data '{\"items\":[{\"train_number\":\"12656\",\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$JOURNEY_DATE\"'\",\"classes\":[\"SL\",\"3A\"],\"quota\":\"GN\"},{\"train_number\":\"12952\",\"from\":\"NDLS\",\"to\":\"BCT\",\"date\":\"'\"$JOURNEY_DATE_2\"'\",\"classes\":[\"2A\"],\"quota\":\"GN\"}]}' \\\n  \"https://ir.railcore.tech/v1/availability/seats/batch\"","node":"const journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\nconst journeyDate2 = new Date(Date.now() + 8 * 86_400_000).toISOString().slice(0, 10);\n\nconst response = await fetch(\"https://ir.railcore.tech/v1/availability/seats/batch\", {\n  method: \"POST\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"Content-Type\": \"application/json\",\n  },\n  body: JSON.stringify({\n  \"items\": [\n    {\n      \"train_number\": \"12656\",\n      \"from\": \"BSL\",\n      \"to\": \"ADI\",\n      \"date\": journeyDate,\n      \"classes\": [\n        \"SL\",\n        \"3A\"\n      ],\n      \"quota\": \"GN\"\n    },\n    {\n      \"train_number\": \"12952\",\n      \"from\": \"NDLS\",\n      \"to\": \"BCT\",\n      \"date\": journeyDate2,\n      \"classes\": [\n        \"2A\"\n      ],\n      \"quota\": \"GN\"\n    }\n  ]\n}),\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\njourney_date_2 = (datetime.date.today() + datetime.timedelta(days=8)).isoformat()\n\nresponse = requests.request(\n    \"POST\",\n    \"https://ir.railcore.tech/v1/availability/seats/batch\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    json={\"items\": [{\"train_number\": \"12656\", \"from\": \"BSL\", \"to\": \"ADI\", \"date\": journey_date, \"classes\": [\"SL\", \"3A\"], \"quota\": \"GN\"}, {\"train_number\": \"12952\", \"from\": \"NDLS\", \"to\": \"BCT\", \"date\": journey_date_2, \"classes\": [\"2A\"], \"quota\": \"GN\"}]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n$journeyDate2 = gmdate(\"Y-m-d\", time() + 8 * 86400);\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/availability/seats/batch\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"POST\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n        \"Content-Type: application/json\",\n    ],\n    CURLOPT_POSTFIELDS => json_encode([\n        \"items\" => [\n            [\n                \"train_number\" => \"12656\",\n                \"from\" => \"BSL\",\n                \"to\" => \"ADI\",\n                \"date\" => $journeyDate,\n                \"classes\" => [\"SL\", \"3A\"],\n                \"quota\" => \"GN\",\n            ],\n            [\n                \"train_number\" => \"12952\",\n                \"from\" => \"NDLS\",\n                \"to\" => \"BCT\",\n                \"date\" => $journeyDate2,\n                \"classes\" => [\"2A\"],\n                \"quota\" => \"GN\",\n            ],\n        ],\n    ]),\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\tjourneyDate2 := time.Now().UTC().AddDate(0, 0, 8).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"POST\", \"https://ir.railcore.tech/v1/availability/seats/batch\", strings.NewReader(`{\n  \"items\": [\n    {\n      \"train_number\": \"12656\",\n      \"from\": \"BSL\",\n      \"to\": \"ADI\",\n      \"date\": \"` + journeyDate + `\",\n      \"classes\": [\n        \"SL\",\n        \"3A\"\n      ],\n      \"quota\": \"GN\"\n    },\n    {\n      \"train_number\": \"12952\",\n      \"from\": \"NDLS\",\n      \"to\": \"BCT\",\n      \"date\": \"` + journeyDate2 + `\",\n      \"classes\": [\n        \"2A\"\n      ],\n      \"quota\": \"GN\"\n    }\n  ]\n}`))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        String journeyDate2 = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(8).toString();\n        String body = \"\"\"\n            {\n              \"items\": [\n                {\n                  \"train_number\": \"12656\",\n                  \"from\": \"BSL\",\n                  \"to\": \"ADI\",\n                  \"date\": \"%s\",\n                  \"classes\": [\n                    \"SL\",\n                    \"3A\"\n                  ],\n                  \"quota\": \"GN\"\n                },\n                {\n                  \"train_number\": \"12952\",\n                  \"from\": \"NDLS\",\n                  \"to\": \"BCT\",\n                  \"date\": \"%s\",\n                  \"classes\": [\n                    \"2A\"\n                  ],\n                  \"quota\": \"GN\"\n                }\n              ]\n            }\n            \"\"\".formatted(journeyDate, journeyDate2);\n\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/availability/seats/batch\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"Content-Type\", \"application/json\")\n            .POST(HttpRequest.BodyPublishers.ofString(body))\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nJOURNEY_DATE_2=$(date -u -d \"+8 days\" +%F 2>/dev/null || date -u -v+8d +%F)\nMETHOD=POST\nAPI_PATH=\"/v1/availability/seats/batch\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY='{\"items\":[{\"train_number\":\"12656\",\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$JOURNEY_DATE\"'\",\"classes\":[\"SL\",\"3A\"],\"quota\":\"GN\"},{\"train_number\":\"12952\",\"from\":\"NDLS\",\"to\":\"BCT\",\"date\":\"'\"$JOURNEY_DATE_2\"'\",\"classes\":[\"2A\"],\"quota\":\"GN\"}]}'\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  -H \"Content-Type: application/json\" \\\n  --data-binary \"$BODY\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\nconst journeyDate2 = new Date(Date.now() + 8 * 86_400_000).toISOString().slice(0, 10);\n\nconst method = \"POST\";\nconst path = \"/v1/availability/seats/batch\";\nconst params = [];\nconst body = JSON.stringify({\n  \"items\": [\n    {\n      \"train_number\": \"12656\",\n      \"from\": \"BSL\",\n      \"to\": \"ADI\",\n      \"date\": journeyDate,\n      \"classes\": [\n        \"SL\",\n        \"3A\"\n      ],\n      \"quota\": \"GN\"\n    },\n    {\n      \"train_number\": \"12952\",\n      \"from\": \"NDLS\",\n      \"to\": \"BCT\",\n      \"date\": journeyDate2,\n      \"classes\": [\n        \"2A\"\n      ],\n      \"quota\": \"GN\"\n    }\n  ]\n});\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n    \"Content-Type\": \"application/json\",\n  },\n  body,\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport json\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\njourney_date_2 = (datetime.date.today() + datetime.timedelta(days=8)).isoformat()\n\nmethod = \"POST\"\npath = \"/v1/availability/seats/batch\"\nparams = []\nbody = json.dumps({\"items\": [{\"train_number\": \"12656\", \"from\": \"BSL\", \"to\": \"ADI\", \"date\": journey_date, \"classes\": [\"SL\", \"3A\"], \"quota\": \"GN\"}, {\"train_number\": \"12952\", \"from\": \"NDLS\", \"to\": \"BCT\", \"date\": journey_date_2, \"classes\": [\"2A\"], \"quota\": \"GN\"}]}, separators=(\",\", \":\"))\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n    \"Content-Type\": \"application/json\",\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    data=body.encode(\"utf-8\"),\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n$journeyDate2 = gmdate(\"Y-m-d\", time() + 8 * 86400);\n\n$method = \"POST\";\n$path = \"/v1/availability/seats/batch\";\n$params = [];\n$body = json_encode([\n    \"items\" => [\n        [\n            \"train_number\" => \"12656\",\n            \"from\" => \"BSL\",\n            \"to\" => \"ADI\",\n            \"date\" => $journeyDate,\n            \"classes\" => [\"SL\", \"3A\"],\n            \"quota\" => \"GN\",\n        ],\n        [\n            \"train_number\" => \"12952\",\n            \"from\" => \"NDLS\",\n            \"to\" => \"BCT\",\n            \"date\" => $journeyDate2,\n            \"classes\" => [\"2A\"],\n            \"quota\" => \"GN\",\n        ],\n    ],\n]);\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n    \"Content-Type: application/json\",\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\tjourneyDate2 := time.Now().UTC().AddDate(0, 0, 8).Format(\"2006-01-02\")\n\n\tmethod := \"POST\"\n\tpath := \"/v1/availability/seats/batch\"\n\tparams := [][2]string{}\n\tbody := `{\n  \"items\": [\n    {\n      \"train_number\": \"12656\",\n      \"from\": \"BSL\",\n      \"to\": \"ADI\",\n      \"date\": \"` + journeyDate + `\",\n      \"classes\": [\n        \"SL\",\n        \"3A\"\n      ],\n      \"quota\": \"GN\"\n    },\n    {\n      \"train_number\": \"12952\",\n      \"from\": \"NDLS\",\n      \"to\": \"BCT\",\n      \"date\": \"` + journeyDate2 + `\",\n      \"classes\": [\n        \"2A\"\n      ],\n      \"quota\": \"GN\"\n    }\n  ]\n}`\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        String journeyDate2 = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(8).toString();\n        String method = \"POST\";\n        String path = \"/v1/availability/seats/batch\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"{\\\"items\\\":[{\\\"train_number\\\":\\\"12656\\\",\\\"from\\\":\\\"BSL\\\",\\\"to\\\":\\\"ADI\\\",\\\"date\\\":\\\"\" + journeyDate + \"\\\",\\\"classes\\\":[\\\"SL\\\",\\\"3A\\\"],\\\"quota\\\":\\\"GN\\\"},{\\\"train_number\\\":\\\"12952\\\",\\\"from\\\":\\\"NDLS\\\",\\\"to\\\":\\\"BCT\\\",\\\"date\\\":\\\"\" + journeyDate2 + \"\\\",\\\"classes\\\":[\\\"2A\\\"],\\\"quota\\\":\\\"GN\\\"}]}\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"availability-calendar","category":"Availability","method":"GET","path":"/availability/calendar","url_template":"https://ir.railcore.tech/v1/availability/calendar","title":"Availability calendar","summary":"Inspect availability across upcoming dates.","description":"Finds the dates the train runs in a window of up to 30 days, then makes one seat enquiry per running date, four at a time. Returns class-level availability, fare, probability, and when each date's figure was read. Dates the train does not run on are left out.","scope":"availability:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"query","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"},{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code.","example":"ADI","pattern":"^[A-Z0-9]{1,6}$"},{"name":"class","in":"query","type":"string","required":true,"description":"Travel class code.","example":"3A","allowed":["1A","2A","3A","3E","CC","EC","SL","2S","GS","FC"]},{"name":"quota","in":"query","type":"string","required":false,"description":"Reservation quota. Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 QUOTA_NOT_SUPPORTED before the seat provider is asked, and is not counted.","example":"GN","default":"GN","allowed":["GN","TQ","SS","LD"]},{"name":"date","in":"query","type":"string(date)","required":false,"description":"First date of the window, today or later. Defaults to today in India.","example":"{{date:days_ahead_utc:7}}"},{"name":"days","in":"query","type":"integer","required":false,"description":"Number of calendar days.","example":"7","default":"7","minimum":1,"maximum":30}],"body_fields":[],"response_fields":[{"name":"train_number / from_station_code / to_station_code","type":"string","description":"Requested train and segment."},{"name":"class_code / quota","type":"string","description":"Applied class and quota."},{"name":"days[].date / day_of_week","type":"string","description":"Calendar date and running day."},{"name":"days[].status / availability_text","type":"string","description":"Normalized availability."},{"name":"days[].available_count","type":"integer | null","description":"Available berth count; null when the source supplies no quantity."},{"name":"days[].waitlist_count","type":"integer | null","description":"Current waitlist position; null when not supplied for the active waitlist status."},{"name":"days[].wl_pool / wl_pool_position","type":"string / integer","description":"Original booking pool and position, read from the availability text (GNWL276/WL185 gives GNWL and 276). Present only when the text names a pool."},{"name":"days[].fare","type":"integer | null","description":"Fare in INR without compulsory catering. Null when the day's own enquiry failed."},{"name":"days[].catering_charge / total_fare","type":"integer","description":"Catering included in the ticket, and what the ticket costs: fare plus catering_charge. Present when the day was read from its own enquiry."},{"name":"days[].confirmation_probability","type":"object | null","description":"The chance that a ticket booked now is confirmed: 100 when seats are available, 0 with the reason in text when no ticket can be booked (Waitlist full (regret) on a REGRET day), the forecast for a waitlisted or RAC day. Null only for a waitlisted or RAC day with no forecast."},{"name":"days[].last_updated_at","type":"string | null","description":"When that date's figure was read at the source; null when its own enquiry failed and the figure came from the provider's listing."}],"response_example":{"success":true,"data":{"train_number":"12656","from_station_code":"BSL","to_station_code":"ADI","class_code":"3A","quota":"GN","days":[{"date":"{{date:days_ahead_utc:7}}","day_of_week":"FRI","status":"AVAILABLE","availability_text":"AVAILABLE-4","available_count":4,"waitlist_count":0,"fare":965,"confirmation_probability":{"percentage":100,"label":"HIGH","text":"Available"},"last_updated_at":"{{date:today_ist}}T10:55:33.825+05:30"}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":["Each date's enquiry is made when you call, but the upstream can answer it from its own cache, so a figure can be hours old. days[].last_updated_at says when each one was read.","When a date's own enquiry fails, that day shows the figure from the upstream's calendar listing instead, with no fare and last_updated_at null. If every date fails, the request answers 503 and is not counted.","Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 QUOTA_NOT_SUPPORTED before the seat provider is asked, and is not counted.","Bookings open 60 days ahead, at 8:00 AM in India. A start date past that answers 422 BOOKING_NOT_OPEN and is not counted. A window that runs past the last open date stops at it, so days can hold fewer dates than you asked for."],"errors":[{"status":422,"code":"QUOTA_NOT_SUPPORTED","description":"Seat availability is not offered for that quota on any train: it answers GN, TQ, SS and LD only. Premium Tatkal (PT), HP, DP, HO, YU and FT can be checked on IRCTC. RailCore refuses it before the seat provider is asked. Not counted.","retryable":false,"category":"VALIDATION","fix":"Use GN, TQ, SS or LD. Other quotas, Premium Tatkal included, cannot be checked through RailCore; check them on IRCTC."},{"status":422,"code":"BOOKING_NOT_OPEN","description":"The date has not opened for booking: reservations open 60 days before the journey, at 8:00 AM in India. RailCore refuses it before the seat provider is asked. error.message names the day it opens. Not counted.","retryable":false,"category":"VALIDATION","fix":"Choose a date inside the booking window: reservations open 60 days before the journey, at 08:00 IST."},{"status":404,"code":"TRAIN_NOT_FOUND","description":"No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.","retryable":false,"category":"NOT_FOUND","fix":"Check the train number. Find the right one by name or number with GET /trains/search."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/availability-calendar","markdown_url":"https://railcore.tech/docs/api/availability-calendar.md","markdown":"# Availability calendar\n\nInspect availability across upcoming dates.\n\n`GET /v1/availability/calendar`\n\n- **Scope:** `availability:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nFinds the dates the train runs in a window of up to 30 days, then makes one seat enquiry per running date, four at a time. Returns class-level availability, fare, probability, and when each date's figure was read. Dates the train does not run on are left out.\n\n```\nJOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/availability/calendar?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN&date=$JOURNEY_DATE&days=7\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"from_station_code\": \"BSL\",\n    \"to_station_code\": \"ADI\",\n    \"class_code\": \"3A\",\n    \"quota\": \"GN\",\n    \"days\": [\n      {\n        \"date\": \"2026-11-27\",\n        \"day_of_week\": \"FRI\",\n        \"status\": \"AVAILABLE\",\n        \"availability_text\": \"AVAILABLE-4\",\n        \"available_count\": 4,\n        \"waitlist_count\": 0,\n        \"fare\": 965,\n        \"confirmation_probability\": {\n          \"percentage\": 100,\n          \"label\": \"HIGH\",\n          \"text\": \"Available\"\n        },\n        \"last_updated_at\": \"2026-11-20T10:55:33.825+05:30\"\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `availability:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n- `from` string required Boarding station code. Example BSL\n- `to` string required Destination station code. Example ADI\n- `class` string required Travel class code. Example 3A 1A 2A 3A 3E CC EC SL 2S GS FC\n- `quota` string optional Reservation quota. Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 QUOTA_NOT_SUPPORTED before the seat provider is asked, and is not counted. Example GN Default GN GN TQ SS LD\n- `date` string(date) optional First date of the window, today or later. Defaults to today in India. Example 2026-11-27\n- `days` integer optional Number of calendar days. Example 7 Default 7 Range 1 to 30\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number / from_station_code / to_station_code` string Requested train and segment.\n- `class_code / quota` string Applied class and quota.\n- `days[].date / day_of_week` string Calendar date and running day.\n- `days[].status / availability_text` string Normalized availability.\n- `days[].available_count` integer | null Available berth count; null when the source supplies no quantity.\n- `days[].waitlist_count` integer | null Current waitlist position; null when not supplied for the active waitlist status.\n- `days[].wl_pool / wl_pool_position` string / integer Original booking pool and position, read from the availability text (GNWL276/WL185 gives GNWL and 276). Present only when the text names a pool.\n- `days[].fare` integer | null Fare in INR without compulsory catering. Null when the day's own enquiry failed.\n- `days[].catering_charge / total_fare` integer Catering included in the ticket, and what the ticket costs: fare plus catering_charge. Present when the day was read from its own enquiry.\n- `days[].confirmation_probability` object | null The chance that a ticket booked now is confirmed: 100 when seats are available, 0 with the reason in text when no ticket can be booked (Waitlist full (regret) on a REGRET day), the forecast for a waitlisted or RAC day. Null only for a waitlisted or RAC day with no forecast.\n- `days[].last_updated_at` string | null When that date's figure was read at the source; null when its own enquiry failed and the figure came from the provider's listing.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 422 [QUOTA_NOT_SUPPORTED](https://railcore.tech/docs/errors-reference#error-QUOTA_NOT_SUPPORTED) Do not retry unchanged Seat availability is not offered for that quota on any train: it answers GN, TQ, SS and LD only. Premium Tatkal (PT), HP, DP, HO, YU and FT can be checked on IRCTC. RailCore refuses it before the seat provider is asked. Not counted.\n- 422 [BOOKING_NOT_OPEN](https://railcore.tech/docs/errors-reference#error-BOOKING_NOT_OPEN) Do not retry unchanged The date has not opened for booking: reservations open 60 days before the journey, at 8:00 AM in India. RailCore refuses it before the seat provider is asked. error.message names the day it opens. Not counted.\n- 404 [TRAIN_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-TRAIN_NOT_FOUND) Do not retry unchanged No train has that number. error.message names it: Train 99999 not found. Check the train number. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- Each date's enquiry is made when you call, but the upstream can answer it from its own cache, so a figure can be hours old. days[].last_updated_at says when each one was read.\n- When a date's own enquiry fails, that day shows the figure from the upstream's calendar listing instead, with no fare and last_updated_at null. If every date fails, the request answers 503 and is not counted.\n- Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 QUOTA_NOT_SUPPORTED before the seat provider is asked, and is not counted.\n- Bookings open 60 days ahead, at 8:00 AM in India. A start date past that answers 422 BOOKING_NOT_OPEN and is not counted. A window that runs past the last open date stops at it, so days can hold fewer dates than you asked for.\n\nSource: https://railcore.tech/docs/api/availability-calendar\nLast updated: 19 Nov 2026\n","samples":{"unsigned":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/availability/calendar?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN&date=$JOURNEY_DATE&days=7\"","node":"const journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst response = await fetch(`https://ir.railcore.tech/v1/availability/calendar?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN&date=${journeyDate}&days=7`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/availability/calendar?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN&date={journey_date}&days=7\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/availability/calendar?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN&date={$journeyDate}&days=7\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/availability/calendar?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN&date=\" + journeyDate + \"&days=7\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/availability/calendar?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN&date=\" + journeyDate + \"&days=7\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/availability/calendar\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"class=3A&date=${JOURNEY_DATE}&days=7&from=BSL&quota=GN&to=ADI&train_number=12656\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst method = \"GET\";\nconst path = \"/v1/availability/calendar\";\nconst params = [\n  [\"train_number\", \"12656\"],\n  [\"from\", \"BSL\"],\n  [\"to\", \"ADI\"],\n  [\"class\", \"3A\"],\n  [\"quota\", \"GN\"],\n  [\"date\", journeyDate],\n  [\"days\", \"7\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nmethod = \"GET\"\npath = \"/v1/availability/calendar\"\nparams = [\n    (\"train_number\", \"12656\"),\n    (\"from\", \"BSL\"),\n    (\"to\", \"ADI\"),\n    (\"class\", \"3A\"),\n    (\"quota\", \"GN\"),\n    (\"date\", journey_date),\n    (\"days\", \"7\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$method = \"GET\";\n$path = \"/v1/availability/calendar\";\n$params = [\n    [\"train_number\", \"12656\"],\n    [\"from\", \"BSL\"],\n    [\"to\", \"ADI\"],\n    [\"class\", \"3A\"],\n    [\"quota\", \"GN\"],\n    [\"date\", $journeyDate],\n    [\"days\", \"7\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/availability/calendar\"\n\tparams := [][2]string{\n\t\t{\"train_number\", \"12656\"},\n\t\t{\"from\", \"BSL\"},\n\t\t{\"to\", \"ADI\"},\n\t\t{\"class\", \"3A\"},\n\t\t{\"quota\", \"GN\"},\n\t\t{\"date\", journeyDate},\n\t\t{\"days\", \"7\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        String method = \"GET\";\n        String path = \"/v1/availability/calendar\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"train_number\", \"12656\"},\n            new String[] {\"from\", \"BSL\"},\n            new String[] {\"to\", \"ADI\"},\n            new String[] {\"class\", \"3A\"},\n            new String[] {\"quota\", \"GN\"},\n            new String[] {\"date\", journeyDate},\n            new String[] {\"days\", \"7\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"available-classes","category":"Availability","method":"GET","path":"/availability/classes","url_template":"https://ir.railcore.tech/v1/availability/classes","title":"Available classes","summary":"List classes offered by a train on a route.","description":"Projects class codes for a specific train and route/date context.","scope":"availability:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"query","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"},{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code.","example":"ADI","pattern":"^[A-Z0-9]{1,6}$"},{"name":"date","in":"query","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD format.","example":"{{date:days_ahead_utc:7}}"}],"body_fields":[],"response_fields":[{"name":"train_number","type":"string","description":"Train number."},{"name":"classes","type":"ClassCode[]","description":"Offered classes."}],"response_example":{"success":true,"data":{"train_number":"12656","classes":["SL","3A","2A","1A"]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/available-classes","markdown_url":"https://railcore.tech/docs/api/available-classes.md","markdown":"# Available classes\n\nList classes offered by a train on a route.\n\n`GET /v1/availability/classes`\n\n- **Scope:** `availability:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nProjects class codes for a specific train and route/date context.\n\n```\nJOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/availability/classes?train_number=12656&from=BSL&to=ADI&date=$JOURNEY_DATE\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"classes\": [\"SL\", \"3A\", \"2A\", \"1A\"]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `availability:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n- `from` string required Boarding station code. Example BSL\n- `to` string required Destination station code. Example ADI\n- `date` string(date) required Journey date in YYYY-MM-DD format. Example 2026-11-27\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number` string Train number.\n- `classes` ClassCode[] Offered classes.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/available-classes\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/availability/classes?train_number=12656&from=BSL&to=ADI&date=$JOURNEY_DATE\"","node":"const journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst response = await fetch(`https://ir.railcore.tech/v1/availability/classes?train_number=12656&from=BSL&to=ADI&date=${journeyDate}`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/availability/classes?train_number=12656&from=BSL&to=ADI&date={journey_date}\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/availability/classes?train_number=12656&from=BSL&to=ADI&date={$journeyDate}\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/availability/classes?train_number=12656&from=BSL&to=ADI&date=\" + journeyDate, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/availability/classes?train_number=12656&from=BSL&to=ADI&date=\" + journeyDate))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/availability/classes\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"date=${JOURNEY_DATE}&from=BSL&to=ADI&train_number=12656\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst method = \"GET\";\nconst path = \"/v1/availability/classes\";\nconst params = [\n  [\"train_number\", \"12656\"],\n  [\"from\", \"BSL\"],\n  [\"to\", \"ADI\"],\n  [\"date\", journeyDate],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nmethod = \"GET\"\npath = \"/v1/availability/classes\"\nparams = [\n    (\"train_number\", \"12656\"),\n    (\"from\", \"BSL\"),\n    (\"to\", \"ADI\"),\n    (\"date\", journey_date),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$method = \"GET\";\n$path = \"/v1/availability/classes\";\n$params = [\n    [\"train_number\", \"12656\"],\n    [\"from\", \"BSL\"],\n    [\"to\", \"ADI\"],\n    [\"date\", $journeyDate],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/availability/classes\"\n\tparams := [][2]string{\n\t\t{\"train_number\", \"12656\"},\n\t\t{\"from\", \"BSL\"},\n\t\t{\"to\", \"ADI\"},\n\t\t{\"date\", journeyDate},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        String method = \"GET\";\n        String path = \"/v1/availability/classes\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"train_number\", \"12656\"},\n            new String[] {\"from\", \"BSL\"},\n            new String[] {\"to\", \"ADI\"},\n            new String[] {\"date\", journeyDate}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"fare-estimate","category":"Fares","method":"GET","path":"/fares/estimate","url_template":"https://ir.railcore.tech/v1/fares/estimate","title":"Fare estimate","summary":"Get reserved fare by class for a train segment.","description":"Returns normalized INR fares for one or every offered class.","scope":"fares:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"query","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"},{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code.","example":"ADI","pattern":"^[A-Z0-9]{1,6}$"},{"name":"class","in":"query","type":"string","required":false,"description":"Travel class code.","example":"3A","allowed":["1A","2A","3A","3E","CC","EC","SL","2S","GS","FC"]},{"name":"quota","in":"query","type":"string","required":false,"description":"Reservation quota of the fare. Fares are given for GN (General) and TQ (Tatkal); any other quota has no fare.","example":"GN","default":"GN","allowed":["GN","TQ"]}],"body_fields":[],"response_fields":[{"name":"train_number","type":"string","description":"Train number."},{"name":"from_station_code / to_station_code","type":"string","description":"Requested segment."},{"name":"quota","type":"Quota","description":"Applied quota."},{"name":"fares[].class_code","type":"ClassCode","description":"Travel class."},{"name":"fares[].fare","type":"integer","description":"Fare in INR."},{"name":"fares[].currency","type":"INR","description":"Currency."}],"response_example":{"success":true,"data":{"train_number":"12656","from_station_code":"BSL","to_station_code":"ADI","quota":"GN","fares":[{"class_code":"3A","fare":965,"currency":"INR"}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":["class narrows the answer to one class. Left out, every class with a fare is returned. fares is never empty: when there is no fare to give, the request answers 404 and is not counted."],"errors":[{"status":404,"code":"NOT_FOUND","description":"No fare is published for this train, journey, class and quota. Not counted.","retryable":false,"category":"NOT_FOUND","fix":"Nothing matches the request. Check the identifiers and the date (a train may not run that day), then ask again."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/fare-estimate","markdown_url":"https://railcore.tech/docs/api/fare-estimate.md","markdown":"# Fare estimate\n\nGet reserved fare by class for a train segment.\n\n`GET /v1/fares/estimate`\n\n- **Scope:** `fares:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns normalized INR fares for one or every offered class.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/fares/estimate?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"from_station_code\": \"BSL\",\n    \"to_station_code\": \"ADI\",\n    \"quota\": \"GN\",\n    \"fares\": [\n      {\n        \"class_code\": \"3A\",\n        \"fare\": 965,\n        \"currency\": \"INR\"\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `fares:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n- `from` string required Boarding station code. Example BSL\n- `to` string required Destination station code. Example ADI\n- `class` string optional Travel class code. Example 3A 1A 2A 3A 3E CC EC SL 2S GS FC\n- `quota` string optional Reservation quota of the fare. Fares are given for GN (General) and TQ (Tatkal); any other quota has no fare. Example GN Default GN GN TQ\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number` string Train number.\n- `from_station_code / to_station_code` string Requested segment.\n- `quota` Quota Applied quota.\n- `fares[].class_code` ClassCode Travel class.\n- `fares[].fare` integer Fare in INR.\n- `fares[].currency` INR Currency.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [NOT_FOUND](https://railcore.tech/docs/errors-reference#error-NOT_FOUND) Do not retry unchanged No fare is published for this train, journey, class and quota. Not counted.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- class narrows the answer to one class. Left out, every class with a fare is returned. fares is never empty: when there is no fare to give, the request answers 404 and is not counted.\n\nSource: https://railcore.tech/docs/api/fare-estimate\nLast updated: 19 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/fares/estimate?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/fares/estimate?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/fares/estimate?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/fares/estimate?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/fares/estimate?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/fares/estimate?train_number=12656&from=BSL&to=ADI&class=3A&quota=GN\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/fares/estimate\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"class=3A&from=BSL&quota=GN&to=ADI&train_number=12656\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/fares/estimate\";\nconst params = [\n  [\"train_number\", \"12656\"],\n  [\"from\", \"BSL\"],\n  [\"to\", \"ADI\"],\n  [\"class\", \"3A\"],\n  [\"quota\", \"GN\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/fares/estimate\"\nparams = [\n    (\"train_number\", \"12656\"),\n    (\"from\", \"BSL\"),\n    (\"to\", \"ADI\"),\n    (\"class\", \"3A\"),\n    (\"quota\", \"GN\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/fares/estimate\";\n$params = [\n    [\"train_number\", \"12656\"],\n    [\"from\", \"BSL\"],\n    [\"to\", \"ADI\"],\n    [\"class\", \"3A\"],\n    [\"quota\", \"GN\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/fares/estimate\"\n\tparams := [][2]string{\n\t\t{\"train_number\", \"12656\"},\n\t\t{\"from\", \"BSL\"},\n\t\t{\"to\", \"ADI\"},\n\t\t{\"class\", \"3A\"},\n\t\t{\"quota\", \"GN\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/fares/estimate\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"train_number\", \"12656\"},\n            new String[] {\"from\", \"BSL\"},\n            new String[] {\"to\", \"ADI\"},\n            new String[] {\"class\", \"3A\"},\n            new String[] {\"quota\", \"GN\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"search-fares","category":"Fares","method":"GET","path":"/fares/search","url_template":"https://ir.railcore.tech/v1/fares/search","title":"Search fares","summary":"Compare fares across trains on a route.","description":"Projects class-level fare tuples for all matching route trains.","scope":"fares:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code.","example":"ADI","pattern":"^[A-Z0-9]{1,6}$"},{"name":"date","in":"query","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD format.","example":"{{date:days_ahead_utc:7}}"},{"name":"quota","in":"query","type":"string","required":false,"description":"Reservation quota of the fare. Fares are given for GN (General) and TQ (Tatkal); any other quota has no fare.","example":"GN","default":"GN","allowed":["GN","TQ"]}],"body_fields":[],"response_fields":[{"name":"from_station_code / to_station_code","type":"string","description":"The two stations asked for."},{"name":"journey_date","type":"string(date)","description":"Requested journey date."},{"name":"quota","type":"Quota","description":"Applied reservation quota."},{"name":"trains[].train_number","type":"string","description":"Train number."},{"name":"trains[].fares[].class_code","type":"ClassCode","description":"Travel class."},{"name":"trains[].fares[].fare","type":"integer","description":"Fare in INR."},{"name":"trains[].fares[].currency","type":"INR","description":"Currency."}],"response_example":{"success":true,"data":{"from_station_code":"BSL","to_station_code":"ADI","journey_date":"{{date:days_ahead_utc:7}}","quota":"GN","trains":[{"train_number":"12656","fares":[{"class_code":"3A","fare":1125,"currency":"INR"}]}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/search-fares","markdown_url":"https://railcore.tech/docs/api/search-fares.md","markdown":"# Search fares\n\nCompare fares across trains on a route.\n\n`GET /v1/fares/search`\n\n- **Scope:** `fares:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nProjects class-level fare tuples for all matching route trains.\n\n```\nJOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/fares/search?from=BSL&to=ADI&date=$JOURNEY_DATE&quota=GN\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"from_station_code\": \"BSL\",\n    \"to_station_code\": \"ADI\",\n    \"journey_date\": \"2026-11-27\",\n    \"quota\": \"GN\",\n    \"trains\": [\n      {\n        \"train_number\": \"12656\",\n        \"fares\": [\n          {\n            \"class_code\": \"3A\",\n            \"fare\": 1125,\n            \"currency\": \"INR\"\n          }\n        ]\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `fares:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `from` string required Boarding station code. Example BSL\n- `to` string required Destination station code. Example ADI\n- `date` string(date) required Journey date in YYYY-MM-DD format. Example 2026-11-27\n- `quota` string optional Reservation quota of the fare. Fares are given for GN (General) and TQ (Tatkal); any other quota has no fare. Example GN Default GN GN TQ\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `from_station_code / to_station_code` string The two stations asked for.\n- `journey_date` string(date) Requested journey date.\n- `quota` Quota Applied reservation quota.\n- `trains[].train_number` string Train number.\n- `trains[].fares[].class_code` ClassCode Travel class.\n- `trains[].fares[].fare` integer Fare in INR.\n- `trains[].fares[].currency` INR Currency.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/search-fares\nLast updated: 19 Nov 2026\n","samples":{"unsigned":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/fares/search?from=BSL&to=ADI&date=$JOURNEY_DATE&quota=GN\"","node":"const journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst response = await fetch(`https://ir.railcore.tech/v1/fares/search?from=BSL&to=ADI&date=${journeyDate}&quota=GN`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/fares/search?from=BSL&to=ADI&date={journey_date}&quota=GN\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/fares/search?from=BSL&to=ADI&date={$journeyDate}&quota=GN\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/fares/search?from=BSL&to=ADI&date=\" + journeyDate + \"&quota=GN\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/fares/search?from=BSL&to=ADI&date=\" + journeyDate + \"&quota=GN\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"JOURNEY_DATE=$(date -u -d \"+7 days\" +%F 2>/dev/null || date -u -v+7d +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/fares/search\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"date=${JOURNEY_DATE}&from=BSL&quota=GN&to=ADI\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst journeyDate = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\n\nconst method = \"GET\";\nconst path = \"/v1/fares/search\";\nconst params = [\n  [\"from\", \"BSL\"],\n  [\"to\", \"ADI\"],\n  [\"date\", journeyDate],\n  [\"quota\", \"GN\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\njourney_date = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()\n\nmethod = \"GET\"\npath = \"/v1/fares/search\"\nparams = [\n    (\"from\", \"BSL\"),\n    (\"to\", \"ADI\"),\n    (\"date\", journey_date),\n    (\"quota\", \"GN\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$journeyDate = gmdate(\"Y-m-d\", time() + 7 * 86400);\n\n$method = \"GET\";\n$path = \"/v1/fares/search\";\n$params = [\n    [\"from\", \"BSL\"],\n    [\"to\", \"ADI\"],\n    [\"date\", $journeyDate],\n    [\"quota\", \"GN\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tjourneyDate := time.Now().UTC().AddDate(0, 0, 7).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/fares/search\"\n\tparams := [][2]string{\n\t\t{\"from\", \"BSL\"},\n\t\t{\"to\", \"ADI\"},\n\t\t{\"date\", journeyDate},\n\t\t{\"quota\", \"GN\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String journeyDate = java.time.LocalDate.now(java.time.ZoneOffset.UTC).plusDays(7).toString();\n        String method = \"GET\";\n        String path = \"/v1/fares/search\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"from\", \"BSL\"},\n            new String[] {\"to\", \"ADI\"},\n            new String[] {\"date\", journeyDate},\n            new String[] {\"quota\", \"GN\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"unreserved-fare","category":"Fares","method":"GET","path":"/fares/unreserved","url_template":"https://ir.railcore.tech/v1/fares/unreserved","title":"Unreserved fare","summary":"Query UTS journey and season-ticket fares.","description":"Returns one or more unreserved fare routes for passenger counts, train category, class, and ticket duration.","scope":"fares:read","availability":"All plans","signing_plans_only":false,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code.","example":"AN","pattern":"^[A-Z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"},{"name":"date","in":"query","type":"string(date)","required":false,"description":"Journey date in YYYY-MM-DD format: today, tomorrow or the day after, in India (IST). Fares are quoted for those three days only. Defaults to today when left out. With train_type T (MMTS), today only.","example":"{{date:today_ist}}"},{"name":"class","in":"query","type":"string","required":false,"description":"II for Second Class or FC for First Class.","example":"II","default":"II","allowed":["II","FC"]},{"name":"train_type","in":"query","type":"string","required":false,"description":"O Ordinary, E Mail/Express, S Superfast, or T MMTS. MMTS fares are quoted for today only.","example":"O","default":"O","allowed":["O","E","S","T"]},{"name":"ticket_type","in":"query","type":"string","required":false,"description":"J Journey, M Monthly, Q Quarterly, H Half Yearly, or Y Yearly.","example":"J","default":"J","allowed":["J","M","Q","H","Y"]},{"name":"adult","in":"query","type":"integer","required":false,"description":"Adult passenger count.","example":"1","default":"1","minimum":1,"maximum":9},{"name":"child","in":"query","type":"integer","required":false,"description":"Child passenger count.","example":"0","default":"0","minimum":0,"maximum":9},{"name":"concession","in":"query","type":"string","required":false,"description":"Applicable UTS concession code.","example":""}],"body_fields":[],"response_fields":[{"name":"from_station_code / to_station_code","type":"string","description":"The two stations of the fare."},{"name":"from / to","type":"string","deprecated":true,"description":"Deprecated: the same codes as from_station_code and to_station_code. Still sent, and removed in a later release; read from_station_code and to_station_code instead."},{"name":"date","type":"string(date)","description":"The date the fare is quoted for."},{"name":"class / train_type / ticket_type","type":"string","description":"Applied fare categories."},{"name":"adult / child","type":"integer","description":"Passenger counts."},{"name":"routes[].route","type":"string","description":"Route including any via stations."},{"name":"routes[].fare","type":"number","description":"Fare in rupees, for example 15 or 17.5."}],"response_example":{"success":true,"data":{"from_station_code":"AN","to_station_code":"BSL","from":"AN","to":"BSL","date":"{{date:today_ist}}","class":"II","train_type":"O","ticket_type":"J","adult":1,"child":0,"routes":[{"route":"AN-JL-BSL","fare":20}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":["Fares are quoted for three days only: today, tomorrow and the day after, in India (IST). A request for any other date fails, and is not counted.","MMTS fares (train_type T) are quoted for today only. Send today's date with T, or leave date out: it defaults to today.","routes[].fare is a number of rupees. Until November 12, 2026 it was a string such as \"15.00\"."],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/unreserved-fare","markdown_url":"https://railcore.tech/docs/api/unreserved-fare.md","markdown":"# Unreserved fare\n\nQuery UTS journey and season-ticket fares.\n\n`GET /v1/fares/unreserved`\n\n- **Scope:** `fares:read`\n- **Cost:** 1 request\n- **Plans:** All plans\n\nReturns one or more unreserved fare routes for passenger counts, train category, class, and ticket duration.\n\n```\nRUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/fares/unreserved?from=AN&to=BSL&date=$RUN_DATE&class=II&train_type=O&ticket_type=J&adult=1&child=0\"\n```\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"from_station_code\": \"AN\",\n    \"to_station_code\": \"BSL\",\n    \"from\": \"AN\",\n    \"to\": \"BSL\",\n    \"date\": \"2026-11-20\",\n    \"class\": \"II\",\n    \"train_type\": \"O\",\n    \"ticket_type\": \"J\",\n    \"adult\": 1,\n    \"child\": 0,\n    \"routes\": [\n      {\n        \"route\": \"AN-JL-BSL\",\n        \"fare\": 20\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `fares:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `from` string required Boarding station code. Example AN\n- `to` string required Destination station code. Example BSL\n- `date` string(date) optional Journey date in YYYY-MM-DD format: today, tomorrow or the day after, in India (IST). Fares are quoted for those three days only. Defaults to today when left out. With train_type T (MMTS), today only. Example 2026-11-20 Range today, tomorrow or the day after (IST)\n- `class` string optional II for Second Class or FC for First Class. Example II Default II II FC\n- `train_type` string optional O Ordinary, E Mail/Express, S Superfast, or T MMTS. MMTS fares are quoted for today only. Example O Default O O E S T\n- `ticket_type` string optional J Journey, M Monthly, Q Quarterly, H Half Yearly, or Y Yearly. Example J Default J J M Q H Y\n- `adult` integer optional Adult passenger count. Example 1 Default 1 Range 1 to 9\n- `child` integer optional Child passenger count. Example 0 Default 0 Range 0 to 9\n- `concession` string optional Applicable UTS concession code.\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `from_station_code / to_station_code` string The two stations of the fare.\n- `from / to` string deprecated Deprecated: the same codes as from_station_code and to_station_code. Still sent, and removed in a later release; read from_station_code and to_station_code instead.\n- `date` string(date) The date the fare is quoted for.\n- `class / train_type / ticket_type` string Applied fare categories.\n- `adult / child` integer Passenger counts.\n- `routes[].route` string Route including any via stations.\n- `routes[].fare` number Fare in rupees, for example 15 or 17.5.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- Fares are quoted for three days only: today, tomorrow and the day after, in India (IST). A request for any other date fails, and is not counted.\n- MMTS fares (train_type T) are quoted for today only. Send today's date with T, or leave date out: it defaults to today.\n- routes[].fare is a number of rupees. Until November 12, 2026 it was a string such as \"15.00\".\n\nSource: https://railcore.tech/docs/api/unreserved-fare\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/fares/unreserved?from=AN&to=BSL&date=$RUN_DATE&class=II&train_type=O&ticket_type=J&adult=1&child=0\"","node":"const runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst response = await fetch(`https://ir.railcore.tech/v1/fares/unreserved?from=AN&to=BSL&date=${runDate}&class=II&train_type=O&ticket_type=J&adult=1&child=0`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/fares/unreserved?from=AN&to=BSL&date={run_date}&class=II&train_type=O&ticket_type=J&adult=1&child=0\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/fares/unreserved?from=AN&to=BSL&date={$runDate}&class=II&train_type=O&ticket_type=J&adult=1&child=0\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/fares/unreserved?from=AN&to=BSL&date=\" + runDate + \"&class=II&train_type=O&ticket_type=J&adult=1&child=0\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/fares/unreserved?from=AN&to=BSL&date=\" + runDate + \"&class=II&train_type=O&ticket_type=J&adult=1&child=0\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/fares/unreserved\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"adult=1&child=0&class=II&date=${RUN_DATE}&from=AN&ticket_type=J&to=BSL&train_type=O\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst method = \"GET\";\nconst path = \"/v1/fares/unreserved\";\nconst params = [\n  [\"from\", \"AN\"],\n  [\"to\", \"BSL\"],\n  [\"date\", runDate],\n  [\"class\", \"II\"],\n  [\"train_type\", \"O\"],\n  [\"ticket_type\", \"J\"],\n  [\"adult\", \"1\"],\n  [\"child\", \"0\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nmethod = \"GET\"\npath = \"/v1/fares/unreserved\"\nparams = [\n    (\"from\", \"AN\"),\n    (\"to\", \"BSL\"),\n    (\"date\", run_date),\n    (\"class\", \"II\"),\n    (\"train_type\", \"O\"),\n    (\"ticket_type\", \"J\"),\n    (\"adult\", \"1\"),\n    (\"child\", \"0\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$method = \"GET\";\n$path = \"/v1/fares/unreserved\";\n$params = [\n    [\"from\", \"AN\"],\n    [\"to\", \"BSL\"],\n    [\"date\", $runDate],\n    [\"class\", \"II\"],\n    [\"train_type\", \"O\"],\n    [\"ticket_type\", \"J\"],\n    [\"adult\", \"1\"],\n    [\"child\", \"0\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/fares/unreserved\"\n\tparams := [][2]string{\n\t\t{\"from\", \"AN\"},\n\t\t{\"to\", \"BSL\"},\n\t\t{\"date\", runDate},\n\t\t{\"class\", \"II\"},\n\t\t{\"train_type\", \"O\"},\n\t\t{\"ticket_type\", \"J\"},\n\t\t{\"adult\", \"1\"},\n\t\t{\"child\", \"0\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        String method = \"GET\";\n        String path = \"/v1/fares/unreserved\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"from\", \"AN\"},\n            new String[] {\"to\", \"BSL\"},\n            new String[] {\"date\", runDate},\n            new String[] {\"class\", \"II\"},\n            new String[] {\"train_type\", \"O\"},\n            new String[] {\"ticket_type\", \"J\"},\n            new String[] {\"adult\", \"1\"},\n            new String[] {\"child\", \"0\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"chart-status","category":"Charts","method":"GET","path":"/charts/status","url_template":"https://ir.railcore.tech/v1/charts/status","title":"Chart status","summary":"Check whether chart one or chart two is prepared.","description":"Resolves remote chart context and reports preparation flags, times, and coach vacancy counts.","scope":"charts:read","availability":"Scale and Enterprise","signing_plans_only":true,"cost":{"kind":"flat","requests":1,"text":"1 request"},"response_format":"json","parameters":[{"name":"train_number","in":"query","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"},{"name":"date","in":"query","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD format.","example":"{{date:today_ist}}"},{"name":"station","in":"query","type":"string","required":false,"description":"Station code used to resolve the remote chart.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"}],"body_fields":[],"response_fields":[{"name":"train_number / train_name","type":"string","description":"Resolved train identity."},{"name":"from_station_code / to_station_code","type":"string","description":"Requested segment."},{"name":"train_start_date","type":"string(date)","description":"Train origin start date used for chart lookup."},{"name":"remote_station_code","type":"string","description":"Remote charting station."},{"name":"chart_status","type":"object","description":"Chart one and chart two flags and preparation times."},{"name":"coach_summary[]","type":"object[]","description":"Coach, class, engine position, and vacant berth count."}],"response_example":{"success":true,"data":{"train_number":"12656","train_name":"Navjeevan SF Express","from_station_code":"BSL","to_station_code":"ADI","train_start_date":"{{date:today_ist}}","remote_station_code":"BSL","next_remote_station_code":"JL","destination_station_code":"ADI","chart_status":{"chart_one_prepared":true,"chart_two_prepared":false,"chart_one_date":"{{date:today_ist}}T06:00:00+05:30","chart_two_date":null},"coach_summary":[{"coach_name":"B1","class_code":"3A","position_from_engine":8,"vacant_berths":4}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":409,"code":"CHART_NOT_PREPARED","description":"The train exists but its chart is not ready.","retryable":true,"category":"NOT_FOUND","fix":"Ask again later: the chart is prepared a few hours before the train leaves."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/chart-status","markdown_url":"https://railcore.tech/docs/api/chart-status.md","markdown":"# Chart status\n\nCheck whether chart one or chart two is prepared.\n\n`GET /v1/charts/status`\n\n- **Scope:** `charts:read`\n- **Cost:** 1 request\n- **Plans:** Scale and Enterprise\n\nResolves remote chart context and reports preparation flags, times, and coach vacancy counts.\n\n```\nRUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/charts/status?train_number=12656&date=$RUN_DATE&station=BSL\"\n```\n\nScale and Enterprise keys must sign every request. Add the three signature headers to this sample: [HMAC signing](https://railcore.tech/docs/hmac) shows how.\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"train_name\": \"Navjeevan SF Express\",\n    \"from_station_code\": \"BSL\",\n    \"to_station_code\": \"ADI\",\n    \"train_start_date\": \"2026-11-20\",\n    \"remote_station_code\": \"BSL\",\n    \"next_remote_station_code\": \"JL\",\n    \"destination_station_code\": \"ADI\",\n    \"chart_status\": {\n      \"chart_one_prepared\": true,\n      \"chart_two_prepared\": false,\n      \"chart_one_date\": \"2026-11-20T06:00:00+05:30\",\n      \"chart_two_date\": null\n    },\n    \"coach_summary\": [\n      {\n        \"coach_name\": \"B1\",\n        \"class_code\": \"3A\",\n        \"position_from_engine\": 8,\n        \"vacant_berths\": 4\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `charts:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nThis endpoint is on the Scale and Enterprise plans, and keys on those plans must sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n- `date` string(date) required Journey date in YYYY-MM-DD format. Example 2026-11-20\n- `station` string optional Station code used to resolve the remote chart. Example BSL\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number / train_name` string Resolved train identity.\n- `from_station_code / to_station_code` string Requested segment.\n- `train_start_date` string(date) Train origin start date used for chart lookup.\n- `remote_station_code` string Remote charting station.\n- `chart_status` object Chart one and chart two flags and preparation times.\n- `coach_summary[]` object[] Coach, class, engine position, and vacant berth count.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 409 [CHART_NOT_PREPARED](https://railcore.tech/docs/errors-reference#error-CHART_NOT_PREPARED) Safe to retry The train exists but its chart is not ready.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/chart-status\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/charts/status?train_number=12656&date=$RUN_DATE&station=BSL\"","node":"const runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst response = await fetch(`https://ir.railcore.tech/v1/charts/status?train_number=12656&date=${runDate}&station=BSL`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/charts/status?train_number=12656&date={run_date}&station=BSL\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/charts/status?train_number=12656&date={$runDate}&station=BSL\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/charts/status?train_number=12656&date=\" + runDate + \"&station=BSL\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/charts/status?train_number=12656&date=\" + runDate + \"&station=BSL\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/charts/status\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"date=${RUN_DATE}&station=BSL&train_number=12656\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst method = \"GET\";\nconst path = \"/v1/charts/status\";\nconst params = [\n  [\"train_number\", \"12656\"],\n  [\"date\", runDate],\n  [\"station\", \"BSL\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nmethod = \"GET\"\npath = \"/v1/charts/status\"\nparams = [\n    (\"train_number\", \"12656\"),\n    (\"date\", run_date),\n    (\"station\", \"BSL\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$method = \"GET\";\n$path = \"/v1/charts/status\";\n$params = [\n    [\"train_number\", \"12656\"],\n    [\"date\", $runDate],\n    [\"station\", \"BSL\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/charts/status\"\n\tparams := [][2]string{\n\t\t{\"train_number\", \"12656\"},\n\t\t{\"date\", runDate},\n\t\t{\"station\", \"BSL\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        String method = \"GET\";\n        String path = \"/v1/charts/status\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"train_number\", \"12656\"},\n            new String[] {\"date\", runDate},\n            new String[] {\"station\", \"BSL\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"vacant-berths","category":"Charts","method":"GET","path":"/charts/vacant-berths","url_template":"https://ir.railcore.tech/v1/charts/vacant-berths","title":"Vacant berths","summary":"Find post-chart berth vacancies by coach and class.","description":"Returns chart state, coach summary, and individual vacant splits with requested-segment coverage.","scope":"charts:read","availability":"Scale and Enterprise","signing_plans_only":true,"cost":{"kind":"flat","requests":3,"text":"3 requests"},"response_format":"json","parameters":[{"name":"train_number","in":"query","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"},{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code.","example":"ADI","pattern":"^[A-Z0-9]{1,6}$"},{"name":"date","in":"query","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD format.","example":"{{date:today_ist}}"}],"body_fields":[],"response_fields":[{"name":"train_number / train_name","type":"string","description":"Resolved train identity."},{"name":"from_station_code / to_station_code","type":"string","description":"Requested segment."},{"name":"train_start_date","type":"string(date)","description":"Train origin start date used for chart lookup."},{"name":"remote_station_code","type":"string","description":"Remote charting station."},{"name":"chart_status","type":"object","description":"Chart one and chart two flags and preparation times."},{"name":"coach_summary[]","type":"object[]","description":"Coach, class, engine position, and vacant berth count."},{"name":"vacant_berths[]","type":"object[]","description":"Coach, class, berth, vacancy segment, split number, and segment coverage flag."}],"response_example":{"success":true,"data":{"train_number":"12656","train_name":"Navjeevan SF Express","from_station_code":"BSL","to_station_code":"ADI","train_start_date":"{{date:today_ist}}","remote_station_code":"BSL","chart_status":{"chart_one_prepared":true,"chart_two_prepared":true},"coach_summary":[{"coach_name":"B1","class_code":"3A","position_from_engine":8,"vacant_berths":4}],"vacant_berths":[{"coach_name":"B1","class_code":"3A","berth_number":17,"berth_code":"L","cabin_coupe":null,"from_station_code":"BSL","to_station_code":"ADI","split_no":1,"covers_requested_segment":true}]},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":409,"code":"CHART_NOT_PREPARED","description":"The train exists but its chart is not ready.","retryable":true,"category":"NOT_FOUND","fix":"Ask again later: the chart is prepared a few hours before the train leaves."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/vacant-berths","markdown_url":"https://railcore.tech/docs/api/vacant-berths.md","markdown":"# Vacant berths\n\nFind post-chart berth vacancies by coach and class.\n\n`GET /v1/charts/vacant-berths`\n\n- **Scope:** `charts:read`\n- **Cost:** 3 requests\n- **Plans:** Scale and Enterprise\n\nReturns chart state, coach summary, and individual vacant splits with requested-segment coverage.\n\n```\nRUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/charts/vacant-berths?train_number=12656&from=BSL&to=ADI&date=$RUN_DATE\"\n```\n\nScale and Enterprise keys must sign every request. Add the three signature headers to this sample: [HMAC signing](https://railcore.tech/docs/hmac) shows how.\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"train_name\": \"Navjeevan SF Express\",\n    \"from_station_code\": \"BSL\",\n    \"to_station_code\": \"ADI\",\n    \"train_start_date\": \"2026-11-20\",\n    \"remote_station_code\": \"BSL\",\n    \"chart_status\": {\n      \"chart_one_prepared\": true,\n      \"chart_two_prepared\": true\n    },\n    \"coach_summary\": [\n      {\n        \"coach_name\": \"B1\",\n        \"class_code\": \"3A\",\n        \"position_from_engine\": 8,\n        \"vacant_berths\": 4\n      }\n    ],\n    \"vacant_berths\": [\n      {\n        \"coach_name\": \"B1\",\n        \"class_code\": \"3A\",\n        \"berth_number\": 17,\n        \"berth_code\": \"L\",\n        \"cabin_coupe\": null,\n        \"from_station_code\": \"BSL\",\n        \"to_station_code\": \"ADI\",\n        \"split_no\": 1,\n        \"covers_requested_segment\": true\n      }\n    ]\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `charts:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nThis endpoint is on the Scale and Enterprise plans, and keys on those plans must sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n- `from` string required Boarding station code. Example BSL\n- `to` string required Destination station code. Example ADI\n- `date` string(date) required Journey date in YYYY-MM-DD format. Example 2026-11-20\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number / train_name` string Resolved train identity.\n- `from_station_code / to_station_code` string Requested segment.\n- `train_start_date` string(date) Train origin start date used for chart lookup.\n- `remote_station_code` string Remote charting station.\n- `chart_status` object Chart one and chart two flags and preparation times.\n- `coach_summary[]` object[] Coach, class, engine position, and vacant berth count.\n- `vacant_berths[]` object[] Coach, class, berth, vacancy segment, split number, and segment coverage flag.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 409 [CHART_NOT_PREPARED](https://railcore.tech/docs/errors-reference#error-CHART_NOT_PREPARED) Safe to retry The train exists but its chart is not ready.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/vacant-berths\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/charts/vacant-berths?train_number=12656&from=BSL&to=ADI&date=$RUN_DATE\"","node":"const runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst response = await fetch(`https://ir.railcore.tech/v1/charts/vacant-berths?train_number=12656&from=BSL&to=ADI&date=${runDate}`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/charts/vacant-berths?train_number=12656&from=BSL&to=ADI&date={run_date}\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/charts/vacant-berths?train_number=12656&from=BSL&to=ADI&date={$runDate}\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/charts/vacant-berths?train_number=12656&from=BSL&to=ADI&date=\" + runDate, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/charts/vacant-berths?train_number=12656&from=BSL&to=ADI&date=\" + runDate))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/charts/vacant-berths\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"date=${RUN_DATE}&from=BSL&to=ADI&train_number=12656\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst method = \"GET\";\nconst path = \"/v1/charts/vacant-berths\";\nconst params = [\n  [\"train_number\", \"12656\"],\n  [\"from\", \"BSL\"],\n  [\"to\", \"ADI\"],\n  [\"date\", runDate],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nmethod = \"GET\"\npath = \"/v1/charts/vacant-berths\"\nparams = [\n    (\"train_number\", \"12656\"),\n    (\"from\", \"BSL\"),\n    (\"to\", \"ADI\"),\n    (\"date\", run_date),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$method = \"GET\";\n$path = \"/v1/charts/vacant-berths\";\n$params = [\n    [\"train_number\", \"12656\"],\n    [\"from\", \"BSL\"],\n    [\"to\", \"ADI\"],\n    [\"date\", $runDate],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/charts/vacant-berths\"\n\tparams := [][2]string{\n\t\t{\"train_number\", \"12656\"},\n\t\t{\"from\", \"BSL\"},\n\t\t{\"to\", \"ADI\"},\n\t\t{\"date\", runDate},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        String method = \"GET\";\n        String path = \"/v1/charts/vacant-berths\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"train_number\", \"12656\"},\n            new String[] {\"from\", \"BSL\"},\n            new String[] {\"to\", \"ADI\"},\n            new String[] {\"date\", runDate}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"vacant-berths-hopping","category":"Charts","method":"GET","path":"/charts/vacant-berths/hopping","url_template":"https://ir.railcore.tech/v1/charts/vacant-berths/hopping","title":"Vacant berth hopping","summary":"Build a same-train berth chain when no berth covers the full route.","description":"Combines chart data, schedule, coach position, preferences, optional fares, alternate boarding, and multiple optimization strategies.","scope":"charts:read","availability":"Scale and Enterprise","signing_plans_only":true,"cost":{"kind":"flat","requests":4,"text":"4 requests"},"response_format":"json","parameters":[{"name":"train_number","in":"query","type":"string","required":true,"description":"Train number, 4 to 6 uppercase letters or digits.","example":"12656","pattern":"^[0-9A-Z]{4,6}$"},{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code.","example":"BSL","pattern":"^[A-Z0-9]{1,6}$"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code.","example":"ADI","pattern":"^[A-Z0-9]{1,6}$"},{"name":"date","in":"query","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD format.","example":"{{date:today_ist}}"},{"name":"via","in":"query","type":"string","required":false,"description":"Pinned intermediate station codes in journey order, comma-separated.","example":"JL,AN"},{"name":"max_hops","in":"query","type":"integer","required":false,"description":"Maximum hopping chain length.","example":"6","default":"6","minimum":1,"maximum":12},{"name":"prefer_berth","in":"query","type":"string","required":false,"description":"Preferred berth codes or aliases, comma-separated.","example":"LB,SLB"},{"name":"avoid_berth","in":"query","type":"string","required":false,"description":"Berth codes or aliases to avoid. Avoid wins on conflicts.","example":"UB,SUB"},{"name":"prefer_class","in":"query","type":"string","required":false,"description":"Preferred travel classes, comma-separated.","example":"SL,3A"},{"name":"avoid_class","in":"query","type":"string","required":false,"description":"Classes to skip entirely, comma-separated.","example":"1A"},{"name":"include_fare","in":"query","type":"boolean","required":false,"description":"Add hop and direct-option fare data.","example":"false","default":"false","allowed":["true","false"]},{"name":"include_alternate_boarding","in":"query","type":"boolean","required":false,"description":"Evaluate nearby stations as alternate boarding points.","example":"false","default":"false","allowed":["true","false"]},{"name":"strategies","in":"query","type":"string","required":false,"description":"min_hops, min_seat_changes, cheapest, or all.","example":"min_hops,cheapest","default":"min_hops"},{"name":"alternate_boarding_mode","in":"query","type":"string","required":false,"description":"lightweight or extended candidate evaluation.","example":"lightweight","default":"lightweight","allowed":["lightweight","extended"]},{"name":"alternate_boarding_max_candidates","in":"query","type":"integer","required":false,"description":"Maximum extended-mode candidates.","example":"3","default":"3","minimum":1,"maximum":5},{"name":"include_cross_class","in":"query","type":"boolean","required":false,"description":"Build one plan that can switch classes between hops.","example":"false","default":"false","allowed":["true","false"]}],"body_fields":[],"response_fields":[{"name":"train_number / train_name","type":"string","description":"Resolved train identity."},{"name":"from_station_code / to_station_code","type":"string","description":"Requested segment."},{"name":"train_start_date","type":"string(date)","description":"Train origin start date used for chart lookup."},{"name":"remote_station_code","type":"string","description":"Remote charting station."},{"name":"chart_status","type":"object","description":"Chart one and chart two flags and preparation times."},{"name":"coach_summary[]","type":"object[]","description":"Coach, class, engine position, and vacant berth count."},{"name":"vacant_berths[]","type":"object[]","description":"Coach, class, berth, vacancy segment, split number, and segment coverage flag."},{"name":"requested_segment","type":"object","description":"Resolved stop sequences, stations, and pinned via points."},{"name":"direct.available","type":"boolean","description":"True when one berth covers the full segment."},{"name":"direct.options[]","type":"object[]","description":"Direct options grouped by class, with berths and optional fare."},{"name":"hopping.disabled / disabled_reason","type":"boolean / string | null","description":"Whether schedule limitations prevented hopping analysis."},{"name":"hopping.options[]","type":"object[]","description":"Per-class coverage plan, hop count, physical seat changes, reason, fare, and strategy plans."},{"name":"hopping.options[].hops[]","type":"object[]","description":"Effective segment, coach, class, berth, stop sequence, fare, and ergonomics for each leg."},{"name":"alternate_boarding","type":"object","description":"Candidate stations, vacancy deltas, chart status, fares, notes, and recommendation scores."},{"name":"cross_class","type":"object","description":"Optional plan that allows class changes between hops."},{"name":"_meta","type":"object","description":"Chart type, classes, partial failures, enrichment status, preferences, and algorithm notes."}],"response_example":{"success":true,"data":{"train_number":"12656","train_name":"Navjeevan SF Express","from_station_code":"BSL","to_station_code":"ADI","train_start_date":"{{date:today_ist}}","chart_status":{"chart_one_prepared":true,"chart_two_prepared":true},"direct":{"available":false,"options":[]},"hopping":{"disabled":false,"disabled_reason":null,"options":[{"class_code":"3A","is_covered":true,"total_hops":2,"physical_seat_changes":1,"total_fare_inr":1190,"hops":[{"from_station_code":"BSL","to_station_code":"AN","coach_name":"B1","class_code":"3A","berth_number":17,"berth_code":"L","fare_inr":610},{"from_station_code":"AN","to_station_code":"ADI","coach_name":"B2","class_code":"3A","berth_number":28,"berth_code":"SL","fare_inr":580}]}]},"alternate_boarding":{"enabled":false,"candidates":[]},"cross_class":{"enabled":false,"plan":null},"_meta":{"classes_requested":["3A"],"max_hops":6,"partial_failures":[]}},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":["The cheapest strategy automatically enables fare lookups.","Avoid-class filters skip one upstream vacancy lookup per skipped class.","It counts as 4 requests whatever these options are; they change the upstream lookups made, not what is counted."],"errors":[{"status":409,"code":"CHART_NOT_PREPARED","description":"The chart is not ready for analysis.","retryable":true,"category":"NOT_FOUND","fix":"Ask again later: the chart is prepared a few hours before the train leaves."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/vacant-berths-hopping","markdown_url":"https://railcore.tech/docs/api/vacant-berths-hopping.md","markdown":"# Vacant berth hopping\n\nBuild a same-train berth chain when no berth covers the full route.\n\n`GET /v1/charts/vacant-berths/hopping`\n\n- **Scope:** `charts:read`\n- **Cost:** 4 requests\n- **Plans:** Scale and Enterprise\n\nCombines chart data, schedule, coach position, preferences, optional fares, alternate boarding, and multiple optimization strategies.\n\n```\nRUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/charts/vacant-berths/hopping?train_number=12656&from=BSL&to=ADI&date=$RUN_DATE&via=JL%2CAN&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=SL%2C3A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\"\n```\n\nScale and Enterprise keys must sign every request. Add the three signature headers to this sample: [HMAC signing](https://railcore.tech/docs/hmac) shows how.\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"train_number\": \"12656\",\n    \"train_name\": \"Navjeevan SF Express\",\n    \"from_station_code\": \"BSL\",\n    \"to_station_code\": \"ADI\",\n    \"train_start_date\": \"2026-11-20\",\n    \"chart_status\": {\n      \"chart_one_prepared\": true,\n      \"chart_two_prepared\": true\n    },\n    \"direct\": {\n      \"available\": false,\n      \"options\": []\n    },\n    \"hopping\": {\n      \"disabled\": false,\n      \"disabled_reason\": null,\n      \"options\": [\n        {\n          \"class_code\": \"3A\",\n          \"is_covered\": true,\n          \"total_hops\": 2,\n          \"physical_seat_changes\": 1,\n          \"total_fare_inr\": 1190,\n          \"hops\": [\n            {\n              \"from_station_code\": \"BSL\",\n              \"to_station_code\": \"AN\",\n              \"coach_name\": \"B1\",\n              \"class_code\": \"3A\",\n              \"berth_number\": 17,\n              \"berth_code\": \"L\",\n              \"fare_inr\": 610\n            },\n            {\n              \"from_station_code\": \"AN\",\n              \"to_station_code\": \"ADI\",\n              \"coach_name\": \"B2\",\n              \"class_code\": \"3A\",\n              \"berth_number\": 28,\n              \"berth_code\": \"SL\",\n              \"fare_inr\": 580\n            }\n          ]\n        }\n      ]\n    },\n    \"alternate_boarding\": {\n      \"enabled\": false,\n      \"candidates\": []\n    },\n    \"cross_class\": {\n      \"enabled\": false,\n      \"plan\": null\n    },\n    \"_meta\": {\n      \"classes_requested\": [\"3A\"],\n      \"max_hops\": 6,\n      \"partial_failures\": []\n    }\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `charts:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nThis endpoint is on the Scale and Enterprise plans, and keys on those plans must sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `train_number` string required Train number, 4 to 6 uppercase letters or digits. Example 12656\n- `from` string required Boarding station code. Example BSL\n- `to` string required Destination station code. Example ADI\n- `date` string(date) required Journey date in YYYY-MM-DD format. Example 2026-11-20\n- `via` string optional Pinned intermediate station codes in journey order, comma-separated. Example JL,AN\n- `max_hops` integer optional Maximum hopping chain length. Example 6 Default 6 Range 1 to 12\n- `prefer_berth` string optional Preferred berth codes or aliases, comma-separated. Example LB,SLB\n- `avoid_berth` string optional Berth codes or aliases to avoid. Avoid wins on conflicts. Example UB,SUB\n- `prefer_class` string optional Preferred travel classes, comma-separated. Example SL,3A\n- `avoid_class` string optional Classes to skip entirely, comma-separated. Example 1A\n- `include_fare` boolean optional Add hop and direct-option fare data. Example false Default false true false\n- `include_alternate_boarding` boolean optional Evaluate nearby stations as alternate boarding points. Example false Default false true false\n- `strategies` string optional min_hops, min_seat_changes, cheapest, or all. Example min_hops,cheapest Default min_hops\n- `alternate_boarding_mode` string optional lightweight or extended candidate evaluation. Example lightweight Default lightweight lightweight extended\n- `alternate_boarding_max_candidates` integer optional Maximum extended-mode candidates. Example 3 Default 3 Range 1 to 5\n- `include_cross_class` boolean optional Build one plan that can switch classes between hops. Example false Default false true false\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `train_number / train_name` string Resolved train identity.\n- `from_station_code / to_station_code` string Requested segment.\n- `train_start_date` string(date) Train origin start date used for chart lookup.\n- `remote_station_code` string Remote charting station.\n- `chart_status` object Chart one and chart two flags and preparation times.\n- `coach_summary[]` object[] Coach, class, engine position, and vacant berth count.\n- `vacant_berths[]` object[] Coach, class, berth, vacancy segment, split number, and segment coverage flag.\n- `requested_segment` object Resolved stop sequences, stations, and pinned via points.\n- `direct.available` boolean True when one berth covers the full segment.\n- `direct.options[]` object[] Direct options grouped by class, with berths and optional fare.\n- `hopping.disabled / disabled_reason` boolean / string | null Whether schedule limitations prevented hopping analysis.\n- `hopping.options[]` object[] Per-class coverage plan, hop count, physical seat changes, reason, fare, and strategy plans.\n  - `hops[]` object[] Effective segment, coach, class, berth, stop sequence, fare, and ergonomics for each leg.\n- `alternate_boarding` object Candidate stations, vacancy deltas, chart status, fares, notes, and recommendation scores.\n- `cross_class` object Optional plan that allows class changes between hops.\n- `_meta` object Chart type, classes, partial failures, enrichment status, preferences, and algorithm notes.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 409 [CHART_NOT_PREPARED](https://railcore.tech/docs/errors-reference#error-CHART_NOT_PREPARED) Safe to retry The chart is not ready for analysis.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- The cheapest strategy automatically enables fare lookups.\n- Avoid-class filters skip one upstream vacancy lookup per skipped class.\n- It counts as 4 requests whatever these options are; they change the upstream lookups made, not what is counted.\n\nSource: https://railcore.tech/docs/api/vacant-berths-hopping\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/charts/vacant-berths/hopping?train_number=12656&from=BSL&to=ADI&date=$RUN_DATE&via=JL%2CAN&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=SL%2C3A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\"","node":"const runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst response = await fetch(`https://ir.railcore.tech/v1/charts/vacant-berths/hopping?train_number=12656&from=BSL&to=ADI&date=${runDate}&via=JL%2CAN&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=SL%2C3A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/charts/vacant-berths/hopping?train_number=12656&from=BSL&to=ADI&date={run_date}&via=JL%2CAN&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=SL%2C3A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/charts/vacant-berths/hopping?train_number=12656&from=BSL&to=ADI&date={$runDate}&via=JL%2CAN&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=SL%2C3A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/charts/vacant-berths/hopping?train_number=12656&from=BSL&to=ADI&date=\" + runDate + \"&via=JL%2CAN&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=SL%2C3A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/charts/vacant-berths/hopping?train_number=12656&from=BSL&to=ADI&date=\" + runDate + \"&via=JL%2CAN&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=SL%2C3A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/charts/vacant-berths/hopping\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"alternate_boarding_max_candidates=3&alternate_boarding_mode=lightweight&avoid_berth=UB%2CSUB&avoid_class=1A&date=${RUN_DATE}&from=BSL&include_alternate_boarding=false&include_cross_class=false&include_fare=false&max_hops=6&prefer_berth=LB%2CSLB&prefer_class=SL%2C3A&strategies=min_hops%2Ccheapest&to=ADI&train_number=12656&via=JL%2CAN\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst method = \"GET\";\nconst path = \"/v1/charts/vacant-berths/hopping\";\nconst params = [\n  [\"train_number\", \"12656\"],\n  [\"from\", \"BSL\"],\n  [\"to\", \"ADI\"],\n  [\"date\", runDate],\n  [\"via\", \"JL,AN\"],\n  [\"max_hops\", \"6\"],\n  [\"prefer_berth\", \"LB,SLB\"],\n  [\"avoid_berth\", \"UB,SUB\"],\n  [\"prefer_class\", \"SL,3A\"],\n  [\"avoid_class\", \"1A\"],\n  [\"include_fare\", \"false\"],\n  [\"include_alternate_boarding\", \"false\"],\n  [\"strategies\", \"min_hops,cheapest\"],\n  [\"alternate_boarding_mode\", \"lightweight\"],\n  [\"alternate_boarding_max_candidates\", \"3\"],\n  [\"include_cross_class\", \"false\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nmethod = \"GET\"\npath = \"/v1/charts/vacant-berths/hopping\"\nparams = [\n    (\"train_number\", \"12656\"),\n    (\"from\", \"BSL\"),\n    (\"to\", \"ADI\"),\n    (\"date\", run_date),\n    (\"via\", \"JL,AN\"),\n    (\"max_hops\", \"6\"),\n    (\"prefer_berth\", \"LB,SLB\"),\n    (\"avoid_berth\", \"UB,SUB\"),\n    (\"prefer_class\", \"SL,3A\"),\n    (\"avoid_class\", \"1A\"),\n    (\"include_fare\", \"false\"),\n    (\"include_alternate_boarding\", \"false\"),\n    (\"strategies\", \"min_hops,cheapest\"),\n    (\"alternate_boarding_mode\", \"lightweight\"),\n    (\"alternate_boarding_max_candidates\", \"3\"),\n    (\"include_cross_class\", \"false\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$method = \"GET\";\n$path = \"/v1/charts/vacant-berths/hopping\";\n$params = [\n    [\"train_number\", \"12656\"],\n    [\"from\", \"BSL\"],\n    [\"to\", \"ADI\"],\n    [\"date\", $runDate],\n    [\"via\", \"JL,AN\"],\n    [\"max_hops\", \"6\"],\n    [\"prefer_berth\", \"LB,SLB\"],\n    [\"avoid_berth\", \"UB,SUB\"],\n    [\"prefer_class\", \"SL,3A\"],\n    [\"avoid_class\", \"1A\"],\n    [\"include_fare\", \"false\"],\n    [\"include_alternate_boarding\", \"false\"],\n    [\"strategies\", \"min_hops,cheapest\"],\n    [\"alternate_boarding_mode\", \"lightweight\"],\n    [\"alternate_boarding_max_candidates\", \"3\"],\n    [\"include_cross_class\", \"false\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/charts/vacant-berths/hopping\"\n\tparams := [][2]string{\n\t\t{\"train_number\", \"12656\"},\n\t\t{\"from\", \"BSL\"},\n\t\t{\"to\", \"ADI\"},\n\t\t{\"date\", runDate},\n\t\t{\"via\", \"JL,AN\"},\n\t\t{\"max_hops\", \"6\"},\n\t\t{\"prefer_berth\", \"LB,SLB\"},\n\t\t{\"avoid_berth\", \"UB,SUB\"},\n\t\t{\"prefer_class\", \"SL,3A\"},\n\t\t{\"avoid_class\", \"1A\"},\n\t\t{\"include_fare\", \"false\"},\n\t\t{\"include_alternate_boarding\", \"false\"},\n\t\t{\"strategies\", \"min_hops,cheapest\"},\n\t\t{\"alternate_boarding_mode\", \"lightweight\"},\n\t\t{\"alternate_boarding_max_candidates\", \"3\"},\n\t\t{\"include_cross_class\", \"false\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        String method = \"GET\";\n        String path = \"/v1/charts/vacant-berths/hopping\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"train_number\", \"12656\"},\n            new String[] {\"from\", \"BSL\"},\n            new String[] {\"to\", \"ADI\"},\n            new String[] {\"date\", runDate},\n            new String[] {\"via\", \"JL,AN\"},\n            new String[] {\"max_hops\", \"6\"},\n            new String[] {\"prefer_berth\", \"LB,SLB\"},\n            new String[] {\"avoid_berth\", \"UB,SUB\"},\n            new String[] {\"prefer_class\", \"SL,3A\"},\n            new String[] {\"avoid_class\", \"1A\"},\n            new String[] {\"include_fare\", \"false\"},\n            new String[] {\"include_alternate_boarding\", \"false\"},\n            new String[] {\"strategies\", \"min_hops,cheapest\"},\n            new String[] {\"alternate_boarding_mode\", \"lightweight\"},\n            new String[] {\"alternate_boarding_max_candidates\", \"3\"},\n            new String[] {\"include_cross_class\", \"false\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"route-vacancy-scan","category":"Charts","method":"GET","path":"/charts/vacant-berths/route-scan","url_template":"https://ir.railcore.tech/v1/charts/vacant-berths/route-scan","title":"Route vacancy scan","summary":"Rank every route train by chart vacancy and hopping coverage.","description":"Resolves station names or codes, scans route trains with bounded concurrency, scores each option, and returns plain-language recommendations.","scope":"charts:read","availability":"Scale and Enterprise","signing_plans_only":true,"cost":{"kind":"flat","requests":8,"text":"8 requests"},"response_format":"json","parameters":[{"name":"from","in":"query","type":"string","required":true,"description":"Boarding station code or name. Fuzzy station-name matching is supported.","example":"Bhusaval"},{"name":"to","in":"query","type":"string","required":true,"description":"Destination station code or name.","example":"Ahmedabad"},{"name":"date","in":"query","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD format.","example":"{{date:today_ist}}"},{"name":"quota","in":"query","type":"string","required":false,"description":"Reservation quota.","example":"GN","default":"GN","allowed":["GN","TQ","PT","LD","SS","HP","DP","HO","YU","FT"]},{"name":"max_trains","in":"query","type":"integer","required":false,"description":"Maximum trains fanned out for a full scan. Other trains remain visible as skipped.","example":"8","default":"100","minimum":1,"maximum":100},{"name":"min_score","in":"query","type":"number","required":false,"description":"Drop returned matches below this score.","example":"50","default":"0","minimum":0,"maximum":100},{"name":"only_running","in":"query","type":"boolean","required":false,"description":"Include only trains scheduled to run on the requested date.","example":"true","default":"true","allowed":["true","false"]},{"name":"only_chart_prepared","in":"query","type":"boolean","required":false,"description":"Include only trains with at least one prepared chart.","example":"false","default":"false","allowed":["true","false"]},{"name":"sort_by","in":"query","type":"string","required":false,"description":"Order matches by departure, latest departure, duration, score, or chart readiness.","example":"score","default":"departure","allowed":["departure","departure_desc","duration","score","chart_ready"]},{"name":"include_detail","in":"query","type":"boolean","required":false,"description":"Include full hopping_detail for every scanned train.","example":"true","default":"true","allowed":["true","false"]},{"name":"train_types","in":"query","type":"string","required":false,"description":"Comma-separated train-type allow list.","example":"SF,RAJDHANI,VANDE_BHARAT"},{"name":"avoid_train_types","in":"query","type":"string","required":false,"description":"Comma-separated train-type deny list. Deny wins over allow.","example":"PASSENGER,MEMU,DEMU"},{"name":"max_hops","in":"query","type":"integer","required":false,"description":"Maximum hopping chain length per train.","example":"6","default":"6","minimum":1,"maximum":12},{"name":"prefer_berth","in":"query","type":"string","required":false,"description":"Preferred berth codes or aliases, comma-separated.","example":"LB,SLB"},{"name":"avoid_berth","in":"query","type":"string","required":false,"description":"Berth codes or aliases to avoid. Avoid wins on conflicts.","example":"UB,SUB"},{"name":"prefer_class","in":"query","type":"string","required":false,"description":"Preferred travel classes, comma-separated.","example":"3A,2A"},{"name":"avoid_class","in":"query","type":"string","required":false,"description":"Classes to skip entirely, comma-separated.","example":"1A"},{"name":"include_fare","in":"query","type":"boolean","required":false,"description":"Add fare lookups to direct and hopping options.","example":"false","default":"false","allowed":["true","false"]},{"name":"include_alternate_boarding","in":"query","type":"boolean","required":false,"description":"Evaluate nearby boarding points on the same train.","example":"false","default":"false","allowed":["true","false"]},{"name":"strategies","in":"query","type":"string","required":false,"description":"Comma-separated strategy list: min_hops, min_seat_changes, cheapest, or all.","example":"min_hops,cheapest","default":"min_hops"},{"name":"alternate_boarding_mode","in":"query","type":"string","required":false,"description":"lightweight reuses fetched data; extended performs fresh candidate lookups.","example":"lightweight","default":"lightweight","allowed":["lightweight","extended"]},{"name":"alternate_boarding_max_candidates","in":"query","type":"integer","required":false,"description":"Maximum extended-mode candidates.","example":"3","default":"3","minimum":1,"maximum":5},{"name":"include_cross_class","in":"query","type":"boolean","required":false,"description":"Build one plan that can switch travel classes between hops.","example":"false","default":"false","allowed":["true","false"]}],"body_fields":[],"response_fields":[{"name":"from / to","type":"ResolvedStation","description":"Canonical station match, input, confidence, and alternates."},{"name":"journey_date / quota","type":"string","description":"Applied search context."},{"name":"route_summary","type":"object","description":"Route totals, scanned counts, coverage counts, and the best result."},{"name":"matches[].train_number / train_name / train_type","type":"string","description":"Train identity."},{"name":"matches[].departure_time / arrival_time / duration_minutes","type":"string / integer","description":"Segment schedule."},{"name":"matches[].runs_on_date / chart_prepared","type":"boolean","description":"Eligibility and chart state."},{"name":"matches[].recommendation / urgency_hint","type":"string | null","description":"Display-ready booking guidance."},{"name":"matches[].score / score_breakdown","type":"integer / object","description":"0 to 100 ranking and auditable components."},{"name":"matches[].classes_summary","type":"ClassSummary[]","description":"Compact direct and hopping coverage per class."},{"name":"matches[].hopping_detail","type":"VacantBerthsHoppingResponse | null","description":"Full analysis when include_detail is true."},{"name":"matches[].scan_status / scan_status_reason","type":"string | null","description":"OK, chart state, upstream failure, or skip reason."},{"name":"_meta","type":"object","description":"Partial failures, filters, cap decisions, sort, preferences, and upstream summary."}],"response_example":{"success":true,"data":{"from":{"station_code":"BSL","station_name":"Bhusaval Jn","resolved_from":"name","input":"Bhusaval","confidence":0.98,"alternates":[]},"to":{"station_code":"ADI","station_name":"Ahmedabad Jn","resolved_from":"name","input":"Ahmedabad","confidence":0.99,"alternates":[]},"journey_date":"{{date:today_ist}}","quota":"GN","route_summary":{"total_trains_on_route":12,"trains_running_on_date":10,"trains_scanned":8,"trains_with_direct_vacancy":2,"trains_with_hopping_coverage":4,"best_train_number":"12656","best_recommendation":"Direct berth available in 3A","best_score":92},"matches":[{"train_number":"12656","train_name":"Navjeevan SF Express","departure_time":"10:25","arrival_time":"18:00","duration_minutes":455,"runs_on_date":true,"chart_prepared":true,"recommendation":"Direct berth available in 3A","urgency_hint":"Chart 2 prepared. Vacancy is authoritative.","score":92,"classes_summary":[{"class_code":"3A","direct_available":true,"direct_berth_count":4}],"hopping_detail":null,"scan_status":"OK","scan_status_reason":null}],"_meta":{"trains_dispatched":8,"partial_failures":[],"sort_by":"score"}},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":["This is the widest synchronous operation and does the most upstream work. Use the async job for long scans or user-facing workflows.","It counts as 8 requests whatever these options are; they change the upstream lookups made, not what is counted."],"errors":[{"status":404,"code":"STATION_NOT_FOUND","description":"A station input could not be resolved above the confidence threshold.","retryable":false,"category":"NOT_FOUND","fix":"Check the station code. Find it by name with GET /stations/search."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/route-vacancy-scan","markdown_url":"https://railcore.tech/docs/api/route-vacancy-scan.md","markdown":"# Route vacancy scan\n\nRank every route train by chart vacancy and hopping coverage.\n\n`GET /v1/charts/vacant-berths/route-scan`\n\n- **Scope:** `charts:read`\n- **Cost:** 8 requests\n- **Plans:** Scale and Enterprise\n\nResolves station names or codes, scans route trains with bounded concurrency, scores each option, and returns plain-language recommendations.\n\n```\nRUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/charts/vacant-berths/route-scan?from=Bhusaval&to=Ahmedabad&date=$RUN_DATE&quota=GN&max_trains=8&min_score=50&only_running=true&only_chart_prepared=false&sort_by=score&include_detail=true&train_types=SF%2CRAJDHANI%2CVANDE_BHARAT&avoid_train_types=PASSENGER%2CMEMU%2CDEMU&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=3A%2C2A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\"\n```\n\nScale and Enterprise keys must sign every request. Add the three signature headers to this sample: [HMAC signing](https://railcore.tech/docs/hmac) shows how.\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"from\": {\n      \"station_code\": \"BSL\",\n      \"station_name\": \"Bhusaval Jn\",\n      \"resolved_from\": \"name\",\n      \"input\": \"Bhusaval\",\n      \"confidence\": 0.98,\n      \"alternates\": []\n    },\n    \"to\": {\n      \"station_code\": \"ADI\",\n      \"station_name\": \"Ahmedabad Jn\",\n      \"resolved_from\": \"name\",\n      \"input\": \"Ahmedabad\",\n      \"confidence\": 0.99,\n      \"alternates\": []\n    },\n    \"journey_date\": \"2026-11-20\",\n    \"quota\": \"GN\",\n    \"route_summary\": {\n      \"total_trains_on_route\": 12,\n      \"trains_running_on_date\": 10,\n      \"trains_scanned\": 8,\n      \"trains_with_direct_vacancy\": 2,\n      \"trains_with_hopping_coverage\": 4,\n      \"best_train_number\": \"12656\",\n      \"best_recommendation\": \"Direct berth available in 3A\",\n      \"best_score\": 92\n    },\n    \"matches\": [\n      {\n        \"train_number\": \"12656\",\n        \"train_name\": \"Navjeevan SF Express\",\n        \"departure_time\": \"10:25\",\n        \"arrival_time\": \"18:00\",\n        \"duration_minutes\": 455,\n        \"runs_on_date\": true,\n        \"chart_prepared\": true,\n        \"recommendation\": \"Direct berth available in 3A\",\n        \"urgency_hint\": \"Chart 2 prepared. Vacancy is authoritative.\",\n        \"score\": 92,\n        \"classes_summary\": [\n          {\n            \"class_code\": \"3A\",\n            \"direct_available\": true,\n            \"direct_berth_count\": 4\n          }\n        ],\n        \"hopping_detail\": null,\n        \"scan_status\": \"OK\",\n        \"scan_status_reason\": null\n      }\n    ],\n    \"_meta\": {\n      \"trains_dispatched\": 8,\n      \"partial_failures\": [],\n      \"sort_by\": \"score\"\n    }\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `charts:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nThis endpoint is on the Scale and Enterprise plans, and keys on those plans must sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `from` string required Boarding station code or name. Fuzzy station-name matching is supported. Example Bhusaval\n- `to` string required Destination station code or name. Example Ahmedabad\n- `date` string(date) required Journey date in YYYY-MM-DD format. Example 2026-11-20\n- `quota` string optional Reservation quota. Example GN Default GN GN TQ PT LD SS HP DP HO YU FT\n- `max_trains` integer optional Maximum trains fanned out for a full scan. Other trains remain visible as skipped. Example 8 Default 100 Range 1 to 100\n- `min_score` number optional Drop returned matches below this score. Example 50 Default 0 Range 0 to 100\n- `only_running` boolean optional Include only trains scheduled to run on the requested date. Example true Default true true false\n- `only_chart_prepared` boolean optional Include only trains with at least one prepared chart. Example false Default false true false\n- `sort_by` string optional Order matches by departure, latest departure, duration, score, or chart readiness. Example score Default departure departure departure_desc duration score chart_ready\n- `include_detail` boolean optional Include full hopping_detail for every scanned train. Example true Default true true false\n- `train_types` string optional Comma-separated train-type allow list. Example SF,RAJDHANI,VANDE_BHARAT\n- `avoid_train_types` string optional Comma-separated train-type deny list. Deny wins over allow. Example PASSENGER,MEMU,DEMU\n- `max_hops` integer optional Maximum hopping chain length per train. Example 6 Default 6 Range 1 to 12\n- `prefer_berth` string optional Preferred berth codes or aliases, comma-separated. Example LB,SLB\n- `avoid_berth` string optional Berth codes or aliases to avoid. Avoid wins on conflicts. Example UB,SUB\n- `prefer_class` string optional Preferred travel classes, comma-separated. Example 3A,2A\n- `avoid_class` string optional Classes to skip entirely, comma-separated. Example 1A\n- `include_fare` boolean optional Add fare lookups to direct and hopping options. Example false Default false true false\n- `include_alternate_boarding` boolean optional Evaluate nearby boarding points on the same train. Example false Default false true false\n- `strategies` string optional Comma-separated strategy list: min_hops, min_seat_changes, cheapest, or all. Example min_hops,cheapest Default min_hops\n- `alternate_boarding_mode` string optional lightweight reuses fetched data; extended performs fresh candidate lookups. Example lightweight Default lightweight lightweight extended\n- `alternate_boarding_max_candidates` integer optional Maximum extended-mode candidates. Example 3 Default 3 Range 1 to 5\n- `include_cross_class` boolean optional Build one plan that can switch travel classes between hops. Example false Default false true false\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `from / to` ResolvedStation Canonical station match, input, confidence, and alternates.\n- `journey_date / quota` string Applied search context.\n- `route_summary` object Route totals, scanned counts, coverage counts, and the best result.\n- `matches[].train_number / train_name / train_type` string Train identity.\n- `matches[].departure_time / arrival_time / duration_minutes` string / integer Segment schedule.\n- `matches[].runs_on_date / chart_prepared` boolean Eligibility and chart state.\n- `matches[].recommendation / urgency_hint` string | null Display-ready booking guidance.\n- `matches[].score / score_breakdown` integer / object 0 to 100 ranking and auditable components.\n- `matches[].classes_summary` ClassSummary[] Compact direct and hopping coverage per class.\n- `matches[].hopping_detail` VacantBerthsHoppingResponse | null Full analysis when include_detail is true.\n- `matches[].scan_status / scan_status_reason` string | null OK, chart state, upstream failure, or skip reason.\n- `_meta` object Partial failures, filters, cap decisions, sort, preferences, and upstream summary.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [STATION_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-STATION_NOT_FOUND) Do not retry unchanged A station input could not be resolved above the confidence threshold.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- This is the widest synchronous operation and does the most upstream work. Use the async job for long scans or user-facing workflows.\n- It counts as 8 requests whatever these options are; they change the upstream lookups made, not what is counted.\n\nSource: https://railcore.tech/docs/api/route-vacancy-scan\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/charts/vacant-berths/route-scan?from=Bhusaval&to=Ahmedabad&date=$RUN_DATE&quota=GN&max_trains=8&min_score=50&only_running=true&only_chart_prepared=false&sort_by=score&include_detail=true&train_types=SF%2CRAJDHANI%2CVANDE_BHARAT&avoid_train_types=PASSENGER%2CMEMU%2CDEMU&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=3A%2C2A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\"","node":"const runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst response = await fetch(`https://ir.railcore.tech/v1/charts/vacant-berths/route-scan?from=Bhusaval&to=Ahmedabad&date=${runDate}&quota=GN&max_trains=8&min_score=50&only_running=true&only_chart_prepared=false&sort_by=score&include_detail=true&train_types=SF%2CRAJDHANI%2CVANDE_BHARAT&avoid_train_types=PASSENGER%2CMEMU%2CDEMU&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=3A%2C2A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false`, {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nresponse = requests.request(\n    \"GET\",\n    f\"https://ir.railcore.tech/v1/charts/vacant-berths/route-scan?from=Bhusaval&to=Ahmedabad&date={run_date}&quota=GN&max_trains=8&min_score=50&only_running=true&only_chart_prepared=false&sort_by=score&include_detail=true&train_types=SF%2CRAJDHANI%2CVANDE_BHARAT&avoid_train_types=PASSENGER%2CMEMU%2CDEMU&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=3A%2C2A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/charts/vacant-berths/route-scan?from=Bhusaval&to=Ahmedabad&date={$runDate}&quota=GN&max_trains=8&min_score=50&only_running=true&only_chart_prepared=false&sort_by=score&include_detail=true&train_types=SF%2CRAJDHANI%2CVANDE_BHARAT&avoid_train_types=PASSENGER%2CMEMU%2CDEMU&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=3A%2C2A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/charts/vacant-berths/route-scan?from=Bhusaval&to=Ahmedabad&date=\" + runDate + \"&quota=GN&max_trains=8&min_score=50&only_running=true&only_chart_prepared=false&sort_by=score&include_detail=true&train_types=SF%2CRAJDHANI%2CVANDE_BHARAT&avoid_train_types=PASSENGER%2CMEMU%2CDEMU&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=3A%2C2A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/charts/vacant-berths/route-scan?from=Bhusaval&to=Ahmedabad&date=\" + runDate + \"&quota=GN&max_trains=8&min_score=50&only_running=true&only_chart_prepared=false&sort_by=score&include_detail=true&train_types=SF%2CRAJDHANI%2CVANDE_BHARAT&avoid_train_types=PASSENGER%2CMEMU%2CDEMU&max_hops=6&prefer_berth=LB%2CSLB&avoid_berth=UB%2CSUB&prefer_class=3A%2C2A&avoid_class=1A&include_fare=false&include_alternate_boarding=false&strategies=min_hops%2Ccheapest&alternate_boarding_mode=lightweight&alternate_boarding_max_candidates=3&include_cross_class=false\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\nMETHOD=GET\nAPI_PATH=\"/v1/charts/vacant-berths/route-scan\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"alternate_boarding_max_candidates=3&alternate_boarding_mode=lightweight&avoid_berth=UB%2CSUB&avoid_class=1A&avoid_train_types=PASSENGER%2CMEMU%2CDEMU&date=${RUN_DATE}&from=Bhusaval&include_alternate_boarding=false&include_cross_class=false&include_detail=true&include_fare=false&max_hops=6&max_trains=8&min_score=50&only_chart_prepared=false&only_running=true&prefer_berth=LB%2CSLB&prefer_class=3A%2C2A&quota=GN&sort_by=score&strategies=min_hops%2Ccheapest&to=Ahmedabad&train_types=SF%2CRAJDHANI%2CVANDE_BHARAT\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst method = \"GET\";\nconst path = \"/v1/charts/vacant-berths/route-scan\";\nconst params = [\n  [\"from\", \"Bhusaval\"],\n  [\"to\", \"Ahmedabad\"],\n  [\"date\", runDate],\n  [\"quota\", \"GN\"],\n  [\"max_trains\", \"8\"],\n  [\"min_score\", \"50\"],\n  [\"only_running\", \"true\"],\n  [\"only_chart_prepared\", \"false\"],\n  [\"sort_by\", \"score\"],\n  [\"include_detail\", \"true\"],\n  [\"train_types\", \"SF,RAJDHANI,VANDE_BHARAT\"],\n  [\"avoid_train_types\", \"PASSENGER,MEMU,DEMU\"],\n  [\"max_hops\", \"6\"],\n  [\"prefer_berth\", \"LB,SLB\"],\n  [\"avoid_berth\", \"UB,SUB\"],\n  [\"prefer_class\", \"3A,2A\"],\n  [\"avoid_class\", \"1A\"],\n  [\"include_fare\", \"false\"],\n  [\"include_alternate_boarding\", \"false\"],\n  [\"strategies\", \"min_hops,cheapest\"],\n  [\"alternate_boarding_mode\", \"lightweight\"],\n  [\"alternate_boarding_max_candidates\", \"3\"],\n  [\"include_cross_class\", \"false\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nmethod = \"GET\"\npath = \"/v1/charts/vacant-berths/route-scan\"\nparams = [\n    (\"from\", \"Bhusaval\"),\n    (\"to\", \"Ahmedabad\"),\n    (\"date\", run_date),\n    (\"quota\", \"GN\"),\n    (\"max_trains\", \"8\"),\n    (\"min_score\", \"50\"),\n    (\"only_running\", \"true\"),\n    (\"only_chart_prepared\", \"false\"),\n    (\"sort_by\", \"score\"),\n    (\"include_detail\", \"true\"),\n    (\"train_types\", \"SF,RAJDHANI,VANDE_BHARAT\"),\n    (\"avoid_train_types\", \"PASSENGER,MEMU,DEMU\"),\n    (\"max_hops\", \"6\"),\n    (\"prefer_berth\", \"LB,SLB\"),\n    (\"avoid_berth\", \"UB,SUB\"),\n    (\"prefer_class\", \"3A,2A\"),\n    (\"avoid_class\", \"1A\"),\n    (\"include_fare\", \"false\"),\n    (\"include_alternate_boarding\", \"false\"),\n    (\"strategies\", \"min_hops,cheapest\"),\n    (\"alternate_boarding_mode\", \"lightweight\"),\n    (\"alternate_boarding_max_candidates\", \"3\"),\n    (\"include_cross_class\", \"false\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$method = \"GET\";\n$path = \"/v1/charts/vacant-berths/route-scan\";\n$params = [\n    [\"from\", \"Bhusaval\"],\n    [\"to\", \"Ahmedabad\"],\n    [\"date\", $runDate],\n    [\"quota\", \"GN\"],\n    [\"max_trains\", \"8\"],\n    [\"min_score\", \"50\"],\n    [\"only_running\", \"true\"],\n    [\"only_chart_prepared\", \"false\"],\n    [\"sort_by\", \"score\"],\n    [\"include_detail\", \"true\"],\n    [\"train_types\", \"SF,RAJDHANI,VANDE_BHARAT\"],\n    [\"avoid_train_types\", \"PASSENGER,MEMU,DEMU\"],\n    [\"max_hops\", \"6\"],\n    [\"prefer_berth\", \"LB,SLB\"],\n    [\"avoid_berth\", \"UB,SUB\"],\n    [\"prefer_class\", \"3A,2A\"],\n    [\"avoid_class\", \"1A\"],\n    [\"include_fare\", \"false\"],\n    [\"include_alternate_boarding\", \"false\"],\n    [\"strategies\", \"min_hops,cheapest\"],\n    [\"alternate_boarding_mode\", \"lightweight\"],\n    [\"alternate_boarding_max_candidates\", \"3\"],\n    [\"include_cross_class\", \"false\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\tmethod := \"GET\"\n\tpath := \"/v1/charts/vacant-berths/route-scan\"\n\tparams := [][2]string{\n\t\t{\"from\", \"Bhusaval\"},\n\t\t{\"to\", \"Ahmedabad\"},\n\t\t{\"date\", runDate},\n\t\t{\"quota\", \"GN\"},\n\t\t{\"max_trains\", \"8\"},\n\t\t{\"min_score\", \"50\"},\n\t\t{\"only_running\", \"true\"},\n\t\t{\"only_chart_prepared\", \"false\"},\n\t\t{\"sort_by\", \"score\"},\n\t\t{\"include_detail\", \"true\"},\n\t\t{\"train_types\", \"SF,RAJDHANI,VANDE_BHARAT\"},\n\t\t{\"avoid_train_types\", \"PASSENGER,MEMU,DEMU\"},\n\t\t{\"max_hops\", \"6\"},\n\t\t{\"prefer_berth\", \"LB,SLB\"},\n\t\t{\"avoid_berth\", \"UB,SUB\"},\n\t\t{\"prefer_class\", \"3A,2A\"},\n\t\t{\"avoid_class\", \"1A\"},\n\t\t{\"include_fare\", \"false\"},\n\t\t{\"include_alternate_boarding\", \"false\"},\n\t\t{\"strategies\", \"min_hops,cheapest\"},\n\t\t{\"alternate_boarding_mode\", \"lightweight\"},\n\t\t{\"alternate_boarding_max_candidates\", \"3\"},\n\t\t{\"include_cross_class\", \"false\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        String method = \"GET\";\n        String path = \"/v1/charts/vacant-berths/route-scan\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"from\", \"Bhusaval\"},\n            new String[] {\"to\", \"Ahmedabad\"},\n            new String[] {\"date\", runDate},\n            new String[] {\"quota\", \"GN\"},\n            new String[] {\"max_trains\", \"8\"},\n            new String[] {\"min_score\", \"50\"},\n            new String[] {\"only_running\", \"true\"},\n            new String[] {\"only_chart_prepared\", \"false\"},\n            new String[] {\"sort_by\", \"score\"},\n            new String[] {\"include_detail\", \"true\"},\n            new String[] {\"train_types\", \"SF,RAJDHANI,VANDE_BHARAT\"},\n            new String[] {\"avoid_train_types\", \"PASSENGER,MEMU,DEMU\"},\n            new String[] {\"max_hops\", \"6\"},\n            new String[] {\"prefer_berth\", \"LB,SLB\"},\n            new String[] {\"avoid_berth\", \"UB,SUB\"},\n            new String[] {\"prefer_class\", \"3A,2A\"},\n            new String[] {\"avoid_class\", \"1A\"},\n            new String[] {\"include_fare\", \"false\"},\n            new String[] {\"include_alternate_boarding\", \"false\"},\n            new String[] {\"strategies\", \"min_hops,cheapest\"},\n            new String[] {\"alternate_boarding_mode\", \"lightweight\"},\n            new String[] {\"alternate_boarding_max_candidates\", \"3\"},\n            new String[] {\"include_cross_class\", \"false\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"submit-route-scan-job","category":"Jobs","method":"POST","path":"/jobs/route-scan","url_template":"https://ir.railcore.tech/v1/jobs/route-scan","title":"Submit route-scan job","summary":"Run route scanning asynchronously.","description":"Creates a durable route-scan job, retries once on processing failure, and optionally calls your callback URL at completion.","scope":"charts:write","availability":"Scale and Enterprise","signing_plans_only":true,"cost":{"kind":"flat","requests":8,"text":"8 requests"},"response_format":"json","parameters":[],"body_fields":[{"name":"from","type":"string","required":true,"description":"Boarding station code or station name."},{"name":"to","type":"string","required":true,"description":"Destination station code or station name."},{"name":"date","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD."},{"name":"quota","type":"Quota","description":"Reservation quota, default GN."},{"name":"max_trains","type":"integer","description":"Maximum trains to scan, 1 to 100."},{"name":"min_score","type":"number","description":"Drop matches scoring below 0 to 100."},{"name":"only_running","type":"boolean","description":"Keep only trains that run on the requested day."},{"name":"only_chart_prepared","type":"boolean","description":"Keep only trains with a prepared chart."},{"name":"sort_by","type":"string","description":"departure, departure_desc, duration, score, or chart_ready."},{"name":"include_detail","type":"boolean","description":"Include the full hopping result per train."},{"name":"train_types","type":"string","description":"Comma-separated train-type allow list."},{"name":"avoid_train_types","type":"string","description":"Comma-separated train-type deny list."},{"name":"max_hops","type":"integer","description":"Maximum hopping chain length, 1 to 12."},{"name":"prefer_berth / avoid_berth","type":"string","description":"Comma-separated berth preference codes."},{"name":"prefer_class / avoid_class","type":"string","description":"Comma-separated class preference codes."},{"name":"include_fare","type":"boolean","description":"Decorate direct and hopping options with fare data."},{"name":"include_alternate_boarding","type":"boolean","description":"Evaluate nearby boarding points."},{"name":"strategies","type":"string","description":"min_hops, min_seat_changes, cheapest, or all."},{"name":"alternate_boarding_mode","type":"string","description":"lightweight or extended."},{"name":"alternate_boarding_max_candidates","type":"integer","description":"Extended candidate cap, 1 to 5."},{"name":"include_cross_class","type":"boolean","description":"Allow a plan that changes class between hops."},{"name":"callback_url","type":"string(uri)","description":"Optional. Where RailCore POSTs the job's outcome when it finishes, signed with the webhook_secret this request returns. An https URL on a public host, port 443 or 1024 and up, with no user name or password. localhost, private, link-local, CGNAT and cloud metadata addresses are refused with 400 VALIDATION_ERROR (details[].field callback_url). See the webhooks guide."}],"body_example":{"from":"BSL","to":"ADI","date":"{{date:today_ist}}","quota":"GN","max_trains":"8","only_running":"true","include_fare":"false","prefer_class":"3A,2A"},"response_fields":[{"name":"job_id","type":"string","description":"Use this identifier for polling, streaming, or cancellation."},{"name":"status","type":"processing","description":"Initial job state."},{"name":"poll_url","type":"string","description":"Relative polling endpoint."},{"name":"stream_url","type":"string","description":"Relative SSE endpoint."},{"name":"message","type":"string","description":"Submission summary."},{"name":"webhook_secret","type":"string","description":"Present when you gave a callback_url: the secret (whsec_…) that signs this job's callbacks. It is shown once and RailCore does not store it, so save it with the job_id."}],"response_example":{"success":true,"data":{"job_id":"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","status":"processing","poll_url":"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","stream_url":"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream","message":"Route scan submitted. Poll the poll_url for results."},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":["A submission is counted when accepted. Cancelling it, or a later failure, does not currently give the requests back.","With a callback_url, RailCore sends one POST when the job finishes: { job_id, status: \"complete\", result } or { job_id, status: \"failed\", error }. It is signed in X-RailCore-Webhook-Signature with the webhook_secret from this answer. After a 5xx, 408, 429, timeout or dropped connection it is sent 3 more times, after 2, 8 and 30 seconds. The webhooks guide shows how to check the signature."],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid, or callback_url is not an https URL on a public host. error.details[].field names the field. Not counted.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":429,"code":"JOB_LIMIT_EXCEEDED","description":"Five jobs are already active on this account, across all of its keys.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for an active job to finish, or cancel one with DELETE /jobs/{job_id}, then submit again. An account can run five jobs at once."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/submit-route-scan-job","markdown_url":"https://railcore.tech/docs/api/submit-route-scan-job.md","markdown":"# Submit route-scan job\n\nRun route scanning asynchronously.\n\n`POST /v1/jobs/route-scan`\n\n- **Scope:** `charts:write`\n- **Cost:** 8 requests\n- **Plans:** Scale and Enterprise\n\nCreates a durable route-scan job, retries once on processing failure, and optionally calls your callback URL at completion.\n\n```\nRUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X POST \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  --data '{\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$RUN_DATE\"'\",\"quota\":\"GN\",\"max_trains\":\"8\",\"only_running\":\"true\",\"include_fare\":\"false\",\"prefer_class\":\"3A,2A\"}' \\\n  \"https://ir.railcore.tech/v1/jobs/route-scan\"\n```\n\nScale and Enterprise keys must sign every request. Add the three signature headers to this sample: [HMAC signing](https://railcore.tech/docs/hmac) shows how.\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"job_id\": \"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"status\": \"processing\",\n    \"poll_url\": \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"stream_url\": \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\",\n    \"message\": \"Route scan submitted. Poll the poll_url for results.\"\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `charts:write` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nThis endpoint is on the Scale and Enterprise plans, and keys on those plans must sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Request body\n\nSend Content-Type: application/json.\n\n- `from` string required Boarding station code or station name.\n- `to` string required Destination station code or station name.\n- `date` string(date) required Journey date in YYYY-MM-DD.\n- `quota` Quota optional Reservation quota, default GN.\n- `max_trains` integer optional Maximum trains to scan, 1 to 100.\n- `min_score` number optional Drop matches scoring below 0 to 100.\n- `only_running` boolean optional Keep only trains that run on the requested day.\n- `only_chart_prepared` boolean optional Keep only trains with a prepared chart.\n- `sort_by` string optional departure, departure_desc, duration, score, or chart_ready.\n- `include_detail` boolean optional Include the full hopping result per train.\n- `train_types` string optional Comma-separated train-type allow list.\n- `avoid_train_types` string optional Comma-separated train-type deny list.\n- `max_hops` integer optional Maximum hopping chain length, 1 to 12.\n- `prefer_berth / avoid_berth` string optional Comma-separated berth preference codes.\n- `prefer_class / avoid_class` string optional Comma-separated class preference codes.\n- `include_fare` boolean optional Decorate direct and hopping options with fare data.\n- `include_alternate_boarding` boolean optional Evaluate nearby boarding points.\n- `strategies` string optional min_hops, min_seat_changes, cheapest, or all.\n- `alternate_boarding_mode` string optional lightweight or extended.\n- `alternate_boarding_max_candidates` integer optional Extended candidate cap, 1 to 5.\n- `include_cross_class` boolean optional Allow a plan that changes class between hops.\n- `callback_url` string(uri) optional Optional. Where RailCore POSTs the job's outcome when it finishes, signed with the webhook_secret this request returns. An https URL on a public host, port 443 or 1024 and up, with no user name or password. localhost, private, link-local, CGNAT and cloud metadata addresses are refused with 400 VALIDATION_ERROR (details[].field callback_url). See the webhooks guide.\n\napplication/json\n\n```\n{\n  \"from\": \"BSL\",\n  \"to\": \"ADI\",\n  \"date\": \"2026-11-20\",\n  \"quota\": \"GN\",\n  \"max_trains\": \"8\",\n  \"only_running\": \"true\",\n  \"include_fare\": \"false\",\n  \"prefer_class\": \"3A,2A\"\n}\n```\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `job_id` string Use this identifier for polling, streaming, or cancellation.\n- `status` processing Initial job state.\n- `poll_url` string Relative polling endpoint.\n- `stream_url` string Relative SSE endpoint.\n- `message` string Submission summary.\n- `webhook_secret` string Present when you gave a callback_url: the secret (whsec_…) that signs this job's callbacks. It is shown once and RailCore does not store it, so save it with the job_id.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid, or callback_url is not an https URL on a public host. error.details[].field names the field. Not counted.\n- 429 [JOB_LIMIT_EXCEEDED](https://railcore.tech/docs/errors-reference#error-JOB_LIMIT_EXCEEDED) Safe to retry Five jobs are already active on this account, across all of its keys.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- A submission is counted when accepted. Cancelling it, or a later failure, does not currently give the requests back.\n- With a callback_url, RailCore sends one POST when the job finishes: { job_id, status: \"complete\", result } or { job_id, status: \"failed\", error }. It is signed in X-RailCore-Webhook-Signature with the webhook_secret from this answer. After a 5xx, 408, 429, timeout or dropped connection it is sent 3 more times, after 2, 8 and 30 seconds. The webhooks guide shows how to check the signature.\n\nSource: https://railcore.tech/docs/api/submit-route-scan-job\nLast updated: 19 Nov 2026\n","samples":{"unsigned":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X POST \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  --data '{\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$RUN_DATE\"'\",\"quota\":\"GN\",\"max_trains\":\"8\",\"only_running\":\"true\",\"include_fare\":\"false\",\"prefer_class\":\"3A,2A\"}' \\\n  \"https://ir.railcore.tech/v1/jobs/route-scan\"","node":"const runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst response = await fetch(\"https://ir.railcore.tech/v1/jobs/route-scan\", {\n  method: \"POST\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"Content-Type\": \"application/json\",\n  },\n  body: JSON.stringify({\n  \"from\": \"BSL\",\n  \"to\": \"ADI\",\n  \"date\": runDate,\n  \"quota\": \"GN\",\n  \"max_trains\": \"8\",\n  \"only_running\": \"true\",\n  \"include_fare\": \"false\",\n  \"prefer_class\": \"3A,2A\"\n}),\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nresponse = requests.request(\n    \"POST\",\n    \"https://ir.railcore.tech/v1/jobs/route-scan\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    json={\"from\": \"BSL\", \"to\": \"ADI\", \"date\": run_date, \"quota\": \"GN\", \"max_trains\": \"8\", \"only_running\": \"true\", \"include_fare\": \"false\", \"prefer_class\": \"3A,2A\"},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/jobs/route-scan\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"POST\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n        \"Content-Type: application/json\",\n    ],\n    CURLOPT_POSTFIELDS => json_encode([\n        \"from\" => \"BSL\",\n        \"to\" => \"ADI\",\n        \"date\" => $runDate,\n        \"quota\" => \"GN\",\n        \"max_trains\" => \"8\",\n        \"only_running\" => \"true\",\n        \"include_fare\" => \"false\",\n        \"prefer_class\" => \"3A,2A\",\n    ]),\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"POST\", \"https://ir.railcore.tech/v1/jobs/route-scan\", strings.NewReader(`{\n  \"from\": \"BSL\",\n  \"to\": \"ADI\",\n  \"date\": \"` + runDate + `\",\n  \"quota\": \"GN\",\n  \"max_trains\": \"8\",\n  \"only_running\": \"true\",\n  \"include_fare\": \"false\",\n  \"prefer_class\": \"3A,2A\"\n}`))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        String body = \"\"\"\n            {\n              \"from\": \"BSL\",\n              \"to\": \"ADI\",\n              \"date\": \"%s\",\n              \"quota\": \"GN\",\n              \"max_trains\": \"8\",\n              \"only_running\": \"true\",\n              \"include_fare\": \"false\",\n              \"prefer_class\": \"3A,2A\"\n            }\n            \"\"\".formatted(runDate);\n\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/jobs/route-scan\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"Content-Type\", \"application/json\")\n            .POST(HttpRequest.BodyPublishers.ofString(body))\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\nMETHOD=POST\nAPI_PATH=\"/v1/jobs/route-scan\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY='{\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$RUN_DATE\"'\",\"quota\":\"GN\",\"max_trains\":\"8\",\"only_running\":\"true\",\"include_fare\":\"false\",\"prefer_class\":\"3A,2A\"}'\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  -H \"Content-Type: application/json\" \\\n  --data-binary \"$BODY\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst method = \"POST\";\nconst path = \"/v1/jobs/route-scan\";\nconst params = [];\nconst body = JSON.stringify({\n  \"from\": \"BSL\",\n  \"to\": \"ADI\",\n  \"date\": runDate,\n  \"quota\": \"GN\",\n  \"max_trains\": \"8\",\n  \"only_running\": \"true\",\n  \"include_fare\": \"false\",\n  \"prefer_class\": \"3A,2A\"\n});\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n    \"Content-Type\": \"application/json\",\n  },\n  body,\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport json\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nmethod = \"POST\"\npath = \"/v1/jobs/route-scan\"\nparams = []\nbody = json.dumps({\"from\": \"BSL\", \"to\": \"ADI\", \"date\": run_date, \"quota\": \"GN\", \"max_trains\": \"8\", \"only_running\": \"true\", \"include_fare\": \"false\", \"prefer_class\": \"3A,2A\"}, separators=(\",\", \":\"))\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n    \"Content-Type\": \"application/json\",\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    data=body.encode(\"utf-8\"),\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$method = \"POST\";\n$path = \"/v1/jobs/route-scan\";\n$params = [];\n$body = json_encode([\n    \"from\" => \"BSL\",\n    \"to\" => \"ADI\",\n    \"date\" => $runDate,\n    \"quota\" => \"GN\",\n    \"max_trains\" => \"8\",\n    \"only_running\" => \"true\",\n    \"include_fare\" => \"false\",\n    \"prefer_class\" => \"3A,2A\",\n]);\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n    \"Content-Type: application/json\",\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\tmethod := \"POST\"\n\tpath := \"/v1/jobs/route-scan\"\n\tparams := [][2]string{}\n\tbody := `{\n  \"from\": \"BSL\",\n  \"to\": \"ADI\",\n  \"date\": \"` + runDate + `\",\n  \"quota\": \"GN\",\n  \"max_trains\": \"8\",\n  \"only_running\": \"true\",\n  \"include_fare\": \"false\",\n  \"prefer_class\": \"3A,2A\"\n}`\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        String method = \"POST\";\n        String path = \"/v1/jobs/route-scan\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"{\\\"from\\\":\\\"BSL\\\",\\\"to\\\":\\\"ADI\\\",\\\"date\\\":\\\"\" + runDate + \"\\\",\\\"quota\\\":\\\"GN\\\",\\\"max_trains\\\":\\\"8\\\",\\\"only_running\\\":\\\"true\\\",\\\"include_fare\\\":\\\"false\\\",\\\"prefer_class\\\":\\\"3A,2A\\\"}\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"submit-hopping-job","category":"Jobs","method":"POST","path":"/jobs/hopping","url_template":"https://ir.railcore.tech/v1/jobs/hopping","title":"Submit hopping job","summary":"Run berth-hopping analysis asynchronously.","description":"Creates a durable train-specific hopping job with optional completion callback and one automatic retry.","scope":"charts:write","availability":"Scale and Enterprise","signing_plans_only":true,"cost":{"kind":"flat","requests":4,"text":"4 requests"},"response_format":"json","parameters":[],"body_fields":[{"name":"train_number","type":"string","required":true,"description":"Train to analyze."},{"name":"from","type":"string","required":true,"description":"Boarding station code."},{"name":"to","type":"string","required":true,"description":"Destination station code."},{"name":"date","type":"string(date)","required":true,"description":"Journey date in YYYY-MM-DD."},{"name":"quota","type":"Quota","description":"Reservation quota, default GN."},{"name":"via","type":"string","description":"Comma-separated stations the plan must cross."},{"name":"max_hops","type":"integer","description":"Maximum chain length, 1 to 12."},{"name":"prefer_berth / avoid_berth","type":"string","description":"Comma-separated berth preference codes."},{"name":"prefer_class / avoid_class","type":"string","description":"Comma-separated class preference codes."},{"name":"include_fare","type":"boolean","description":"Add fare details."},{"name":"include_alternate_boarding","type":"boolean","description":"Evaluate nearby boarding stations."},{"name":"include_cross_class","type":"boolean","description":"Allow class changes between hops."},{"name":"strategies","type":"string","description":"min_hops, min_seat_changes, cheapest, or all."},{"name":"callback_url","type":"string(uri)","description":"Optional. Where RailCore POSTs the job's outcome when it finishes, signed with the webhook_secret this request returns. An https URL on a public host, port 443 or 1024 and up, with no user name or password. localhost, private, link-local, CGNAT and cloud metadata addresses are refused with 400 VALIDATION_ERROR (details[].field callback_url). See the webhooks guide."}],"body_example":{"train_number":"12656","from":"BSL","to":"ADI","date":"{{date:today_ist}}","quota":"GN","max_hops":"6","include_fare":"true","prefer_class":"3A"},"response_fields":[{"name":"job_id","type":"string","description":"Use this identifier for polling, streaming, or cancellation."},{"name":"status","type":"processing","description":"Initial job state."},{"name":"poll_url","type":"string","description":"Relative polling endpoint."},{"name":"stream_url","type":"string","description":"Relative SSE endpoint."},{"name":"message","type":"string","description":"Submission summary."},{"name":"webhook_secret","type":"string","description":"Present when you gave a callback_url: the secret (whsec_…) that signs this job's callbacks. It is shown once and RailCore does not store it, so save it with the job_id."}],"response_example":{"success":true,"data":{"job_id":"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","status":"processing","poll_url":"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","stream_url":"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream","message":"Hopping analysis submitted. Poll the poll_url for results."},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":["A submission is counted when accepted. Cancelling it, or a later failure, does not currently give the requests back.","With a callback_url, RailCore sends one POST when the job finishes: { job_id, status: \"complete\", result } or { job_id, status: \"failed\", error }. It is signed in X-RailCore-Webhook-Signature with the webhook_secret from this answer. After a 5xx, 408, 429, timeout or dropped connection it is sent 3 more times, after 2, 8 and 30 seconds. The webhooks guide shows how to check the signature."],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid, or callback_url is not an https URL on a public host. error.details[].field names the field. Not counted.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":429,"code":"JOB_LIMIT_EXCEEDED","description":"Five jobs are already active on this account, across all of its keys.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for an active job to finish, or cancel one with DELETE /jobs/{job_id}, then submit again. An account can run five jobs at once."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/submit-hopping-job","markdown_url":"https://railcore.tech/docs/api/submit-hopping-job.md","markdown":"# Submit hopping job\n\nRun berth-hopping analysis asynchronously.\n\n`POST /v1/jobs/hopping`\n\n- **Scope:** `charts:write`\n- **Cost:** 4 requests\n- **Plans:** Scale and Enterprise\n\nCreates a durable train-specific hopping job with optional completion callback and one automatic retry.\n\n```\nRUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X POST \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  --data '{\"train_number\":\"12656\",\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$RUN_DATE\"'\",\"quota\":\"GN\",\"max_hops\":\"6\",\"include_fare\":\"true\",\"prefer_class\":\"3A\"}' \\\n  \"https://ir.railcore.tech/v1/jobs/hopping\"\n```\n\nScale and Enterprise keys must sign every request. Add the three signature headers to this sample: [HMAC signing](https://railcore.tech/docs/hmac) shows how.\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"job_id\": \"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"status\": \"processing\",\n    \"poll_url\": \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"stream_url\": \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\",\n    \"message\": \"Hopping analysis submitted. Poll the poll_url for results.\"\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `charts:write` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nThis endpoint is on the Scale and Enterprise plans, and keys on those plans must sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Request body\n\nSend Content-Type: application/json.\n\n- `train_number` string required Train to analyze.\n- `from` string required Boarding station code.\n- `to` string required Destination station code.\n- `date` string(date) required Journey date in YYYY-MM-DD.\n- `quota` Quota optional Reservation quota, default GN.\n- `via` string optional Comma-separated stations the plan must cross.\n- `max_hops` integer optional Maximum chain length, 1 to 12.\n- `prefer_berth / avoid_berth` string optional Comma-separated berth preference codes.\n- `prefer_class / avoid_class` string optional Comma-separated class preference codes.\n- `include_fare` boolean optional Add fare details.\n- `include_alternate_boarding` boolean optional Evaluate nearby boarding stations.\n- `include_cross_class` boolean optional Allow class changes between hops.\n- `strategies` string optional min_hops, min_seat_changes, cheapest, or all.\n- `callback_url` string(uri) optional Optional. Where RailCore POSTs the job's outcome when it finishes, signed with the webhook_secret this request returns. An https URL on a public host, port 443 or 1024 and up, with no user name or password. localhost, private, link-local, CGNAT and cloud metadata addresses are refused with 400 VALIDATION_ERROR (details[].field callback_url). See the webhooks guide.\n\napplication/json\n\n```\n{\n  \"train_number\": \"12656\",\n  \"from\": \"BSL\",\n  \"to\": \"ADI\",\n  \"date\": \"2026-11-20\",\n  \"quota\": \"GN\",\n  \"max_hops\": \"6\",\n  \"include_fare\": \"true\",\n  \"prefer_class\": \"3A\"\n}\n```\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `job_id` string Use this identifier for polling, streaming, or cancellation.\n- `status` processing Initial job state.\n- `poll_url` string Relative polling endpoint.\n- `stream_url` string Relative SSE endpoint.\n- `message` string Submission summary.\n- `webhook_secret` string Present when you gave a callback_url: the secret (whsec_…) that signs this job's callbacks. It is shown once and RailCore does not store it, so save it with the job_id.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid, or callback_url is not an https URL on a public host. error.details[].field names the field. Not counted.\n- 429 [JOB_LIMIT_EXCEEDED](https://railcore.tech/docs/errors-reference#error-JOB_LIMIT_EXCEEDED) Safe to retry Five jobs are already active on this account, across all of its keys.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- A submission is counted when accepted. Cancelling it, or a later failure, does not currently give the requests back.\n- With a callback_url, RailCore sends one POST when the job finishes: { job_id, status: \"complete\", result } or { job_id, status: \"failed\", error }. It is signed in X-RailCore-Webhook-Signature with the webhook_secret from this answer. After a 5xx, 408, 429, timeout or dropped connection it is sent 3 more times, after 2, 8 and 30 seconds. The webhooks guide shows how to check the signature.\n\nSource: https://railcore.tech/docs/api/submit-hopping-job\nLast updated: 19 Nov 2026\n","samples":{"unsigned":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X POST \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  --data '{\"train_number\":\"12656\",\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$RUN_DATE\"'\",\"quota\":\"GN\",\"max_hops\":\"6\",\"include_fare\":\"true\",\"prefer_class\":\"3A\"}' \\\n  \"https://ir.railcore.tech/v1/jobs/hopping\"","node":"const runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst response = await fetch(\"https://ir.railcore.tech/v1/jobs/hopping\", {\n  method: \"POST\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"Content-Type\": \"application/json\",\n  },\n  body: JSON.stringify({\n  \"train_number\": \"12656\",\n  \"from\": \"BSL\",\n  \"to\": \"ADI\",\n  \"date\": runDate,\n  \"quota\": \"GN\",\n  \"max_hops\": \"6\",\n  \"include_fare\": \"true\",\n  \"prefer_class\": \"3A\"\n}),\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import datetime\nimport os\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nresponse = requests.request(\n    \"POST\",\n    \"https://ir.railcore.tech/v1/jobs/hopping\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    json={\"train_number\": \"12656\", \"from\": \"BSL\", \"to\": \"ADI\", \"date\": run_date, \"quota\": \"GN\", \"max_hops\": \"6\", \"include_fare\": \"true\", \"prefer_class\": \"3A\"},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$ch = curl_init(\"https://ir.railcore.tech/v1/jobs/hopping\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"POST\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n        \"Content-Type: application/json\",\n    ],\n    CURLOPT_POSTFIELDS => json_encode([\n        \"train_number\" => \"12656\",\n        \"from\" => \"BSL\",\n        \"to\" => \"ADI\",\n        \"date\" => $runDate,\n        \"quota\" => \"GN\",\n        \"max_hops\" => \"6\",\n        \"include_fare\" => \"true\",\n        \"prefer_class\" => \"3A\",\n    ]),\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\treq, err := http.NewRequest(\"POST\", \"https://ir.railcore.tech/v1/jobs/hopping\", strings.NewReader(`{\n  \"train_number\": \"12656\",\n  \"from\": \"BSL\",\n  \"to\": \"ADI\",\n  \"date\": \"` + runDate + `\",\n  \"quota\": \"GN\",\n  \"max_hops\": \"6\",\n  \"include_fare\": \"true\",\n  \"prefer_class\": \"3A\"\n}`))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        String body = \"\"\"\n            {\n              \"train_number\": \"12656\",\n              \"from\": \"BSL\",\n              \"to\": \"ADI\",\n              \"date\": \"%s\",\n              \"quota\": \"GN\",\n              \"max_hops\": \"6\",\n              \"include_fare\": \"true\",\n              \"prefer_class\": \"3A\"\n            }\n            \"\"\".formatted(runDate);\n\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/jobs/hopping\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"Content-Type\", \"application/json\")\n            .POST(HttpRequest.BodyPublishers.ofString(body))\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"RUN_DATE=$(TZ=Asia/Kolkata date +%F)\nMETHOD=POST\nAPI_PATH=\"/v1/jobs/hopping\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY='{\"train_number\":\"12656\",\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$RUN_DATE\"'\",\"quota\":\"GN\",\"max_hops\":\"6\",\"include_fare\":\"true\",\"prefer_class\":\"3A\"}'\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  -H \"Content-Type: application/json\" \\\n  --data-binary \"$BODY\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\n\nconst method = \"POST\";\nconst path = \"/v1/jobs/hopping\";\nconst params = [];\nconst body = JSON.stringify({\n  \"train_number\": \"12656\",\n  \"from\": \"BSL\",\n  \"to\": \"ADI\",\n  \"date\": runDate,\n  \"quota\": \"GN\",\n  \"max_hops\": \"6\",\n  \"include_fare\": \"true\",\n  \"prefer_class\": \"3A\"\n});\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n    \"Content-Type\": \"application/json\",\n  },\n  body,\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport json\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nrun_date = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=5, minutes=30))).date().isoformat()\n\nmethod = \"POST\"\npath = \"/v1/jobs/hopping\"\nparams = []\nbody = json.dumps({\"train_number\": \"12656\", \"from\": \"BSL\", \"to\": \"ADI\", \"date\": run_date, \"quota\": \"GN\", \"max_hops\": \"6\", \"include_fare\": \"true\", \"prefer_class\": \"3A\"}, separators=(\",\", \":\"))\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n    \"Content-Type\": \"application/json\",\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    data=body.encode(\"utf-8\"),\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$runDate = (new DateTime(\"now\", new DateTimeZone(\"Asia/Kolkata\")))->format(\"Y-m-d\");\n\n$method = \"POST\";\n$path = \"/v1/jobs/hopping\";\n$params = [];\n$body = json_encode([\n    \"train_number\" => \"12656\",\n    \"from\" => \"BSL\",\n    \"to\" => \"ADI\",\n    \"date\" => $runDate,\n    \"quota\" => \"GN\",\n    \"max_hops\" => \"6\",\n    \"include_fare\" => \"true\",\n    \"prefer_class\" => \"3A\",\n]);\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n    \"Content-Type: application/json\",\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\trunDate := time.Now().In(time.FixedZone(\"IST\", 5*3600+30*60)).Format(\"2006-01-02\")\n\n\tmethod := \"POST\"\n\tpath := \"/v1/jobs/hopping\"\n\tparams := [][2]string{}\n\tbody := `{\n  \"train_number\": \"12656\",\n  \"from\": \"BSL\",\n  \"to\": \"ADI\",\n  \"date\": \"` + runDate + `\",\n  \"quota\": \"GN\",\n  \"max_hops\": \"6\",\n  \"include_fare\": \"true\",\n  \"prefer_class\": \"3A\"\n}`\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String runDate = java.time.LocalDate.now(java.time.ZoneId.of(\"Asia/Kolkata\")).toString();\n        String method = \"POST\";\n        String path = \"/v1/jobs/hopping\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"{\\\"train_number\\\":\\\"12656\\\",\\\"from\\\":\\\"BSL\\\",\\\"to\\\":\\\"ADI\\\",\\\"date\\\":\\\"\" + runDate + \"\\\",\\\"quota\\\":\\\"GN\\\",\\\"max_hops\\\":\\\"6\\\",\\\"include_fare\\\":\\\"true\\\",\\\"prefer_class\\\":\\\"3A\\\"}\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"get-job","category":"Jobs","method":"GET","path":"/jobs/{job_id}","url_template":"https://ir.railcore.tech/v1/jobs/{job_id}","title":"Get job","summary":"Poll status and retrieve a completed result.","description":"Returns progress while active, result data when complete, or a terminal error for failed and cancelled jobs.","scope":"charts:read","availability":"Scale and Enterprise","signing_plans_only":true,"cost":{"kind":"flat","requests":0,"text":"0 requests"},"response_format":"json","parameters":[{"name":"job_id","in":"path","type":"string","required":true,"description":"Job identifier returned by a submission endpoint.","example":"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","pattern":"^job_"}],"body_fields":[],"response_fields":[{"name":"job_id","type":"string","description":"Persistent job identifier."},{"name":"status","type":"JobStatus","description":"pending, processing, complete, failed, or cancelled."},{"name":"type","type":"string","description":"route-scan or hopping."},{"name":"created_at / completed_at","type":"string(date-time)","description":"Lifecycle timestamps in IST."},{"name":"progress","type":"string","description":"Current human-readable processing stage."},{"name":"callback_status","type":"string","description":"not_configured when no callback_url was given. pending until the callback is settled: the job's status is saved before the callback is sent, so a poll can see the result first. sent when your endpoint answered 2xx; failed when it never did, or the address was refused.","allowed":["not_configured","pending","sent","failed"]},{"name":"callback_attempts","type":"integer","description":"How many times the callback was sent, 0 to 4: 0 when the address was refused before the first send. Present once the callback is settled."},{"name":"data","type":"object","description":"Completed route-scan or hopping result."},{"name":"error","type":"object","description":"Terminal code and message when the job failed."}],"response_example":{"success":true,"data":{"success":true,"job_id":"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","status":"processing","type":"route-scan","created_at":"{{date:today_ist}}T10:55:51.794+05:30","progress":"Scanning trains (from: BSL, to: ADI)..."},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":404,"code":"JOB_NOT_FOUND","description":"The job does not exist or has expired.","retryable":false,"category":"NOT_FOUND","fix":"Check the job ID. Jobs and their results expire, so submit the job again if it is gone."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/get-job","markdown_url":"https://railcore.tech/docs/api/get-job.md","markdown":"# Get job\n\nPoll status and retrieve a completed result.\n\n`GET /v1/jobs/{job_id}`\n\n- **Scope:** `charts:read`\n- **Cost:** 0 requests\n- **Plans:** Scale and Enterprise\n\nReturns progress while active, result data when complete, or a terminal error for failed and cancelled jobs.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"\n```\n\nScale and Enterprise keys must sign every request. Add the three signature headers to this sample: [HMAC signing](https://railcore.tech/docs/hmac) shows how.\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"success\": true,\n    \"job_id\": \"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"status\": \"processing\",\n    \"type\": \"route-scan\",\n    \"created_at\": \"2026-11-20T10:55:51.794+05:30\",\n    \"progress\": \"Scanning trains (from: BSL, to: ADI)...\"\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `charts:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nThis endpoint is on the Scale and Enterprise plans, and keys on those plans must sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `job_id` string required Job identifier returned by a submission endpoint. Example job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `job_id` string Persistent job identifier.\n- `status` JobStatus pending, processing, complete, failed, or cancelled.\n- `type` string route-scan or hopping.\n- `created_at / completed_at` string(date-time) Lifecycle timestamps in IST.\n- `progress` string Current human-readable processing stage.\n- `callback_status` string not_configured when no callback_url was given. pending until the callback is settled: the job's status is saved before the callback is sent, so a poll can see the result first. sent when your endpoint answered 2xx; failed when it never did, or the address was refused. not_configured pending sent failed\n- `callback_attempts` integer How many times the callback was sent, 0 to 4: 0 when the address was refused before the first send. Present once the callback is settled.\n- `data` object Completed route-scan or hopping result.\n- `error` object Terminal code and message when the job failed.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [JOB_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-JOB_NOT_FOUND) Do not retry unchanged The job does not exist or has expired.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/get-job\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\";\nconst params = [];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"\nparams = []\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\";\n$params = [];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"\n\tparams := [][2]string{}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"cancel-job","category":"Jobs","method":"DELETE","path":"/jobs/{job_id}","url_template":"https://ir.railcore.tech/v1/jobs/{job_id}","title":"Cancel job","summary":"Cancel a pending or processing job.","description":"Marks the job cancelled. Work already in progress is stopped where it can be.","scope":"charts:write","availability":"Scale and Enterprise","signing_plans_only":true,"cost":{"kind":"flat","requests":0,"text":"0 requests"},"response_format":"json","parameters":[{"name":"job_id","in":"path","type":"string","required":true,"description":"Job identifier returned by a submission endpoint.","example":"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","pattern":"^job_"}],"body_fields":[],"response_fields":[{"name":"success","type":"boolean","description":"Cancellation result."},{"name":"job_id","type":"string","description":"Cancelled job."},{"name":"status","type":"cancelled","description":"Terminal state."},{"name":"message","type":"string","description":"Cancellation summary."}],"response_example":{"success":true,"data":{"success":true,"job_id":"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","status":"cancelled","message":"Job cancelled"},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":404,"code":"JOB_NOT_FOUND","description":"The job does not exist.","retryable":false,"category":"NOT_FOUND","fix":"Check the job ID. Jobs and their results expire, so submit the job again if it is gone."},{"status":409,"code":"JOB_ALREADY_FINISHED","description":"A complete, failed, or cancelled job cannot be cancelled again.","retryable":false,"category":"NOT_FOUND","fix":"There is nothing to cancel. Read the job's result with GET /jobs/{job_id} instead."},{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/cancel-job","markdown_url":"https://railcore.tech/docs/api/cancel-job.md","markdown":"# Cancel job\n\nCancel a pending or processing job.\n\n`DELETE /v1/jobs/{job_id}`\n\n- **Scope:** `charts:write`\n- **Cost:** 0 requests\n- **Plans:** Scale and Enterprise\n\nMarks the job cancelled. Work already in progress is stopped where it can be.\n\n```\ncurl -sS -X DELETE \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"\n```\n\nScale and Enterprise keys must sign every request. Add the three signature headers to this sample: [HMAC signing](https://railcore.tech/docs/hmac) shows how.\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"success\": true,\n    \"job_id\": \"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"status\": \"cancelled\",\n    \"message\": \"Job cancelled\"\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `charts:write` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nThis endpoint is on the Scale and Enterprise plans, and keys on those plans must sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `job_id` string required Job identifier returned by a submission endpoint. Example job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `success` boolean Cancellation result.\n- `job_id` string Cancelled job.\n- `status` cancelled Terminal state.\n- `message` string Cancellation summary.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 404 [JOB_NOT_FOUND](https://railcore.tech/docs/errors-reference#error-JOB_NOT_FOUND) Do not retry unchanged The job does not exist.\n- 409 [JOB_ALREADY_FINISHED](https://railcore.tech/docs/errors-reference#error-JOB_ALREADY_FINISHED) Do not retry unchanged A complete, failed, or cancelled job cannot be cancelled again.\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/cancel-job\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X DELETE \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\", {\n  method: \"DELETE\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"DELETE\",\n    \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"DELETE\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"DELETE\", \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .DELETE()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=DELETE\nAPI_PATH=\"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"DELETE\";\nconst path = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\";\nconst params = [];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"DELETE\"\npath = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"\nparams = []\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"DELETE\";\n$path = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\";\n$params = [];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"DELETE\"\n\tpath := \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\"\n\tparams := [][2]string{}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"DELETE\";\n        String path = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}},{"id":"stream-job","category":"Jobs","method":"GET","path":"/jobs/{job_id}/stream","url_template":"https://ir.railcore.tech/v1/jobs/{job_id}/stream","title":"Stream job progress","summary":"Receive progress and terminal state over SSE.","description":"Emits a progress event every two seconds, then one complete or failed event before closing the connection.","scope":"charts:read","availability":"Scale and Enterprise","signing_plans_only":true,"cost":{"kind":"flat","requests":0,"text":"0 requests"},"response_format":"sse","parameters":[{"name":"job_id","in":"path","type":"string","required":true,"description":"Job identifier returned by a submission endpoint.","example":"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","pattern":"^job_"}],"body_fields":[],"response_fields":[{"name":"event: progress","type":"SSE","description":"data contains status and progress."},{"name":"event: complete","type":"SSE","description":"data contains the final route-scan or hopping result."},{"name":"event: failed","type":"SSE","description":"data.error contains JOB_NOT_FOUND, CANCELLED, POLL_ERROR, or processing failure details."}],"response_example":"event: progress\ndata: {\"status\":\"processing\",\"progress\":\"Scanning trains...\"}\n\nevent: complete\ndata: {\"route_summary\":{\"trains_scanned\":8}}\n\n","notes":["The playground captures streamed text for up to 20 seconds. Use EventSource or a streaming fetch client in production."],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/stream-job","markdown_url":"https://railcore.tech/docs/api/stream-job.md","markdown":"# Stream job progress\n\nReceive progress and terminal state over SSE.\n\n`GET /v1/jobs/{job_id}/stream`\n\n- **Scope:** `charts:read`\n- **Cost:** 0 requests\n- **Plans:** Scale and Enterprise\n- **Format:** `text/event-stream`\n\nEmits a progress event every two seconds, then one complete or failed event before closing the connection.\n\n```\ncurl -N -sS \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Accept: text/event-stream\" \\\n  \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\"\n```\n\nScale and Enterprise keys must sign every request. Add the three signature headers to this sample: [HMAC signing](https://railcore.tech/docs/hmac) shows how.\n\n```\nevent: progress\ndata: {\"status\":\"processing\",\"progress\":\"Scanning trains...\"}\n\nevent: complete\ndata: {\"route_summary\":{\"trains_scanned\":8}}\n```\n\n## Authentication\n\nSend a key that has the `charts:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nThis endpoint is on the Scale and Enterprise plans, and keys on those plans must sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Path parameters\n\n- `job_id` string required Job identifier returned by a submission endpoint. Example job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\n\n## Response\n\nThis operation emits named server-sent events.\n\n- `event: progress` SSE data contains status and progress.\n- `event: complete` SSE data contains the final route-scan or hopping result.\n- `event: failed` SSE data.error contains JOB_NOT_FOUND, CANCELLED, POLL_ERROR, or processing failure details.\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\n## Notes\n\n- The playground captures streamed text for up to 20 seconds. Use EventSource or a streaming fetch client in production.\n\nSource: https://railcore.tech/docs/api/stream-job\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -N -sS \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Accept: text/event-stream\" \\\n  \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\"","node":"const streamUrl = \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\";\nconst terminalEvents = new Set([\"complete\", \"failed\"]);\nconst sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));\nlet terminalReceived = false;\n\nfor (let attempt = 0; attempt < 5 && !terminalReceived; attempt += 1) {\n  try {\n    const response = await fetch(streamUrl, {\n      headers: {\n        \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n        Accept: \"text/event-stream\",\n      },\n    });\n    if (!response.ok || !response.body) {\n      throw new Error(`SSE request failed: ${response.status}`);\n    }\n\n    const reader = response.body.getReader();\n    const decoder = new TextDecoder();\n    let buffer = \"\";\n\n    while (!terminalReceived) {\n      const { value, done } = await reader.read();\n      if (done) break;\n      buffer += decoder.decode(value, { stream: true }).replace(/\\r\\n/g, \"\\n\");\n      const frames = buffer.split(\"\\n\\n\");\n      buffer = frames.pop() ?? \"\";\n\n      for (const frame of frames) {\n        const lines = frame.split(\"\\n\");\n        const event = lines.find((line) => line.startsWith(\"event:\"))?.slice(6).trim() ?? \"message\";\n        const dataText = lines\n          .filter((line) => line.startsWith(\"data:\"))\n          .map((line) => line.slice(5).trimStart())\n          .join(\"\\n\");\n        if (!dataText) continue;\n\n        let data = dataText;\n        try { data = JSON.parse(dataText); } catch { /* Keep non-JSON event data as text. */ }\n        console.log(event, data);\n        if (terminalEvents.has(event)) {\n          terminalReceived = true;\n          break;\n        }\n      }\n    }\n  } catch (error) {\n    console.error(error instanceof Error ? error.message : error);\n  }\n\n  if (!terminalReceived && attempt < 4) {\n    const delay = Math.min(1_000 * 2 ** attempt, 8_000);\n    console.warn(`Stream closed before a terminal event; reconnecting in ${delay} ms...`);\n    await sleep(delay);\n  }\n}\n\nif (!terminalReceived) throw new Error(\"Stream ended without a complete or failed event\");","python":"import json\nimport os\nimport time\nimport requests\n\nstream_url = \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\"\nterminal_events = {\"complete\", \"failed\"}\nterminal_received = False\n\nfor attempt in range(5):\n    try:\n        with requests.get(\n            stream_url,\n            headers={\n                \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n                \"Accept\": \"text/event-stream\",\n            },\n            stream=True,\n            timeout=(10, 60),\n        ) as response:\n            response.raise_for_status()\n            event_name = \"message\"\n            data_lines = []\n\n            for line in response.iter_lines(decode_unicode=True):\n                if line == \"\":\n                    if data_lines:\n                        data_text = \"\\n\".join(data_lines)\n                        try:\n                            data = json.loads(data_text)\n                        except json.JSONDecodeError:\n                            data = data_text\n                        print(event_name, data, flush=True)\n                        if event_name in terminal_events:\n                            terminal_received = True\n                            break\n                    event_name = \"message\"\n                    data_lines = []\n                elif line.startswith(\"event:\"):\n                    event_name = line[6:].strip()\n                elif line.startswith(\"data:\"):\n                    data_lines.append(line[5:].lstrip())\n    except requests.RequestException as error:\n        print(f\"Stream error: {error}\", flush=True)\n\n    if terminal_received:\n        break\n    if attempt < 4:\n        delay = min(2 ** attempt, 8)\n        print(f\"Stream closed before a terminal event; reconnecting in {delay}s...\", flush=True)\n        time.sleep(delay)\n\nif not terminal_received:\n    raise RuntimeError(\"Stream ended without a complete or failed event\")","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\");\ncurl_setopt_array($ch, [\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n        \"Accept: text/event-stream\",\n    ],\n    // Print each chunk as it arrives instead of waiting for the stream to close.\n    CURLOPT_WRITEFUNCTION => function ($ch, $chunk) {\n        echo $chunk;\n        return strlen($chunk);\n    },\n    CURLOPT_TIMEOUT => 60,\n]);\ncurl_exec($ch);\ncurl_close($ch);","go":"package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"Accept\", \"text/event-stream\")\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\t// One line per \"event:\" or \"data:\" field; a blank line ends an event.\n\tscanner := bufio.NewScanner(res.Body)\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\n\npublic class RailCoreStream {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\"))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"Accept\", \"text/event-stream\")\n            .GET()\n            .build();\n\n        // One line per \"event:\" or \"data:\" field; a blank line ends an event.\n        HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofLines())\n            .body()\n            .forEach(System.out::println);\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -N -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  -H \"Accept: text/event-stream\" \\\n  \"https://ir.railcore.tech${API_PATH}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\";\nconst params = [];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n    Accept: \"text/event-stream\",\n  },\n});\n// Print the event stream as it arrives.\nconst reader = response.body.getReader();\nconst decoder = new TextDecoder();\nfor (;;) {\n  const { value, done } = await reader.read();\n  if (done) break;\n  process.stdout.write(decoder.decode(value, { stream: true }));\n}","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\"\nparams = []\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n    \"Accept\": \"text/event-stream\",\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    stream=True,\n    timeout=(10, 60),\n)\nfor line in response.iter_lines(decode_unicode=True):\n    print(line, flush=True)","php":"<?php\n$method = \"GET\";\n$path = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\";\n$params = [];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n    \"Accept: text/event-stream\",\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    // Print each chunk of the event stream as it arrives.\n    CURLOPT_WRITEFUNCTION => function ($ch, $chunk) {\n        echo $chunk;\n        return strlen($chunk);\n    },\n    CURLOPT_TIMEOUT => 60,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\ncurl_exec($ch);\ncurl_close($ch);","go":"package main\n\nimport (\n\t\"bufio\"\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\"\n\tparams := [][2]string{}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\treq.Header.Set(\"Accept\", \"text/event-stream\")\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\t// One line per \"event:\" or \"data:\" field; a blank line ends an event.\n\tscanner := bufio.NewScanner(res.Body)\n\tfor scanner.Scan() {\n\t\tfmt.Println(scanner.Text())\n\t}\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\";\n        List<String[]> params = new ArrayList<>();\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(60))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature)\n            .header(\"Accept\", \"text/event-stream\");\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        // One line per \"event:\" or \"data:\" field; a blank line ends an event.\n        HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofLines())\n            .body()\n            .forEach(System.out::println);\n    }\n}"}}},{"id":"list-jobs","category":"Jobs","method":"GET","path":"/jobs","url_template":"https://ir.railcore.tech/v1/jobs","title":"List jobs","summary":"List recent jobs with optional filters.","description":"Returns compact lifecycle records without loading full result payloads.","scope":"charts:read","availability":"Scale and Enterprise","signing_plans_only":true,"cost":{"kind":"flat","requests":0,"text":"0 requests"},"response_format":"json","parameters":[{"name":"status","in":"query","type":"string","required":false,"description":"Filter by lifecycle status.","example":"processing","allowed":["pending","processing","complete","failed","cancelled"]},{"name":"type","in":"query","type":"string","required":false,"description":"Filter by job type.","example":"route-scan","allowed":["route-scan","hopping"]},{"name":"limit","in":"query","type":"integer","required":false,"description":"Maximum records.","example":"20","default":"20","minimum":1,"maximum":100}],"body_fields":[],"response_fields":[{"name":"jobs[]","type":"JobSummary[]","description":"Compact lifecycle rows."},{"name":"jobs[].job_id / status / type","type":"string","description":"Job identity and state."},{"name":"jobs[].created_at / completed_at","type":"string | undefined","description":"Lifecycle timestamps."},{"name":"jobs[].progress","type":"string | undefined","description":"Current stage."},{"name":"jobs[].callback_status / callback_attempts","type":"string / integer","description":"Callback delivery state (not_configured, pending, sent or failed) and how many sends were made, as on get job."},{"name":"count","type":"integer","description":"Rows returned."}],"response_example":{"success":true,"data":{"jobs":[{"job_id":"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","status":"processing","type":"route-scan","created_at":"{{date:today_ist}}T10:55:51.794+05:30","progress":"Scanning trains...","callback_status":"not_configured"}],"count":1},"meta":{"api_version":"v1","request_id":"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8","trace_id":"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9","timestamp":"{{date:today_ist}}T10:57:05.609Z","freshness":{"mode":"live","retrieved_at":"{{date:today_ist}}T10:57:05.609Z","sources":[{"confidence":"high"}]}}},"notes":[],"errors":[{"status":400,"code":"VALIDATION_ERROR","description":"A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.","retryable":false,"category":"VALIDATION","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted."},{"status":401,"code":"MISSING_API_KEY","description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","retryable":false,"category":"AUTH","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard."},{"status":401,"code":"INVALID_API_KEY","description":"The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.","retryable":false,"category":"AUTH","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard."},{"status":401,"code":"AMBIGUOUS_API_KEY","description":"More than one key header was sent, with different keys. Send the key in one header.","retryable":false,"category":"AUTH","fix":"Send the key in one header only, or make every key header carry the same key."},{"status":401,"code":"SIGNATURE_INVALID","description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","retryable":false,"category":"AUTH","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one."},{"status":403,"code":"SCOPE_MISSING","description":"The key lacks this operation's scope.","retryable":false,"category":"AUTH","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope."},{"status":403,"code":"PLAN_ENDPOINT_DISABLED","description":"The account's plan does not include this endpoint.","retryable":false,"category":"FORBIDDEN","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes."},{"status":402,"code":"CREDITS_EXHAUSTED","description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","retryable":false,"category":"QUOTA","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches."},{"status":429,"code":"RATE_LIMITED","description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","retryable":true,"category":"RATE_LIMIT","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit."},{"status":410,"code":"API_VERSION_SUNSET","description":"This API version has reached its announced sunset date. Migrate to a supported major version.","retryable":false,"category":"NOT_FOUND","fix":"Move to a supported API version. The changelog names the current one."},{"status":503,"code":"UPSTREAM_UNAVAILABLE","description":"Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"UPSTREAM_TIMEOUT","description":"The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.","retryable":true,"category":"UPSTREAM","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted."},{"status":503,"code":"METERING_UNAVAILABLE","description":"The request could not be counted, so no data was returned. Retry with backoff.","retryable":true,"category":"INTERNAL","fix":"Retry with backoff. The request was not counted and no data was sent."}],"docs_url":"https://railcore.tech/docs/api/list-jobs","markdown_url":"https://railcore.tech/docs/api/list-jobs.md","markdown":"# List jobs\n\nList recent jobs with optional filters.\n\n`GET /v1/jobs`\n\n- **Scope:** `charts:read`\n- **Cost:** 0 requests\n- **Plans:** Scale and Enterprise\n\nReturns compact lifecycle records without loading full result payloads.\n\n```\ncurl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/jobs?status=processing&type=route-scan&limit=20\"\n```\n\nScale and Enterprise keys must sign every request. Add the three signature headers to this sample: [HMAC signing](https://railcore.tech/docs/hmac) shows how.\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"jobs\": [\n      {\n        \"job_id\": \"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n        \"status\": \"processing\",\n        \"type\": \"route-scan\",\n        \"created_at\": \"2026-11-20T10:55:51.794+05:30\",\n        \"progress\": \"Scanning trains...\",\n        \"callback_status\": \"not_configured\"\n      }\n    ],\n    \"count\": 1\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"trace_id\": \"trc_01J5Z7Y8N2K4M6P8R0T2V4X6Z9\",\n    \"timestamp\": \"2026-11-20T10:57:05.609Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:05.609Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Authentication\n\nSend a key that has the `charts:read` scope, in any one of these headers. The examples use the one you pick under **Key header**.\n\n- `X-RailCore-Key: rk_live_...` RailCore's own header. The samples start with it.\n- `Authorization: Bearer rk_live_...` The standard bearer token, for clients that set it for you.\n- `X-Api-Key: rk_live_...` For gateways and tools that send a key in this header.\n\nSend one header only: two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n\nThis endpoint is on the Scale and Enterprise plans, and keys on those plans must sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature.\n\n[How to sign](https://railcore.tech/docs/hmac) [Auth guide](https://railcore.tech/docs/authentication)\n\n## Query parameters\n\n- `status` string optional Filter by lifecycle status. Example processing pending processing complete failed cancelled\n- `type` string optional Filter by job type. Example route-scan route-scan hopping\n- `limit` integer optional Maximum records. Example 20 Default 20 Range 1 to 100\n\n## Response\n\nThe fields of data. Every response wraps them in the shared RailCore envelope.\n\n- `jobs[]` JobSummary[] Compact lifecycle rows.\n  - `job_id / status / type` string Job identity and state.\n  - `created_at / completed_at` string | undefined Lifecycle timestamps.\n  - `progress` string | undefined Current stage.\n  - `callback_status / callback_attempts` string / integer Callback delivery state (not_configured, pending, sent or failed) and how many sends were made, as on get job.\n- `count` integer Rows returned.\n\nThe envelope's own fields (success, error, meta) are in [Response envelope](https://railcore.tech/docs/responses).\n\n## Errors\n\nWhat this endpoint can answer besides success. Branch on error.code; a failed request is not counted.\n\n- 400 [VALIDATION_ERROR](https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR) Do not retry unchanged A required field is missing or invalid. error.details[].field names the parameter, such as date or items[2].date.\n- 401 [MISSING_API_KEY](https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY) Do not retry unchanged No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.\n- 401 [INVALID_API_KEY](https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY) Do not retry unchanged The key is unknown or revoked. A disabled or expired key answers API_KEY_DISABLED or API_KEY_EXPIRED.\n- 401 [AMBIGUOUS_API_KEY](https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY) Do not retry unchanged More than one key header was sent, with different keys. Send the key in one header.\n- 401 [SIGNATURE_INVALID](https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID) Do not retry unchanged HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.\n- 403 [SCOPE_MISSING](https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING) Do not retry unchanged The key lacks this operation's scope.\n- 403 [PLAN_ENDPOINT_DISABLED](https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED) Do not retry unchanged The account's plan does not include this endpoint.\n- 402 [CREDITS_EXHAUSTED](https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED) Do not retry unchanged The month's requests are used up, or too few are left for this request. Nothing is fetched.\n- 429 [RATE_LIMITED](https://railcore.tech/docs/errors-reference#error-RATE_LIMITED) Safe to retry The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.\n- 410 [API_VERSION_SUNSET](https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET) Do not retry unchanged This API version has reached its announced sunset date. Migrate to a supported major version.\n- 503 [UPSTREAM_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE) Safe to retry Live data could not be retrieved. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [UPSTREAM_TIMEOUT](https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT) Safe to retry The live-data request ran past its deadline. Wait for Retry-After, then retry with backoff. Not counted.\n- 503 [METERING_UNAVAILABLE](https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE) Safe to retry The request could not be counted, so no data was returned. Retry with backoff.\n\n[Open the full error catalog](https://railcore.tech/docs/errors-reference)\n\nSource: https://railcore.tech/docs/api/list-jobs\nLast updated: 12 Nov 2026\n","samples":{"unsigned":{"curl":"curl -sS -X GET \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/jobs?status=processing&type=route-scan&limit=20\"","node":"const response = await fetch(\"https://ir.railcore.tech/v1/jobs?status=processing&type=route-scan&limit=20\", {\n  method: \"GET\",\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n  },\n});\n\nconst body = await response.json();\nconsole.log(response.status, body);","python":"import os\nimport requests\n\nresponse = requests.request(\n    \"GET\",\n    \"https://ir.railcore.tech/v1/jobs?status=processing&type=route-scan&limit=20\",\n    headers={\"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"]},\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$ch = curl_init(\"https://ir.railcore.tech/v1/jobs?status=processing&type=route-scan&limit=20\");\ncurl_setopt_array($ch, [\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_CUSTOMREQUEST => \"GET\",\n    CURLOPT_HTTPHEADER => [\n        \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    ],\n    CURLOPT_TIMEOUT => 20,\n]);\n$body = json_decode(curl_exec($ch), true);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r($body);","go":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n)\n\nfunc main() {\n\treq, err := http.NewRequest(\"GET\", \"https://ir.railcore.tech/v1/jobs?status=processing&type=route-scan&limit=20\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tbody, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(body))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.time.Duration;\n\npublic class RailCoreExample {\n    public static void main(String[] args) throws Exception {\n        HttpRequest request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech/v1/jobs?status=processing&type=route-scan&limit=20\"))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .GET()\n            .build();\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request, HttpResponse.BodyHandlers.ofString());\n\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"},"signed":{"curl":"METHOD=GET\nAPI_PATH=\"/v1/jobs\"\n# Each name and value encoded with strict RFC 3986, then sorted by name, then value.\nQUERY=\"limit=20&status=processing&type=route-scan\"\nBODY=''\n\nTIMESTAMP=$(date +%s)\nNONCE=$(openssl rand -hex 16)\nBODY_HASH=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hex | sed 's/^.* //')\nSIGNATURE=$(printf '%s\\n%s\\n%s\\n%s\\n%s\\n%s' \"$METHOD\" \"$API_PATH\" \"$QUERY\" \"$BODY_HASH\" \"$TIMESTAMP\" \"$NONCE\" \\\n  | openssl dgst -sha256 -hmac \"$RAILCORE_HMAC_SECRET\" -binary | openssl base64 -A)\n\ncurl -sS -X \"$METHOD\" \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"X-RailCore-Timestamp: $TIMESTAMP\" \\\n  -H \"X-RailCore-Nonce: $NONCE\" \\\n  -H \"X-RailCore-Signature: $SIGNATURE\" \\\n  \"https://ir.railcore.tech${API_PATH}?${QUERY}\"","node":"import { createHash, createHmac, randomBytes } from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/jobs\";\nconst params = [\n  [\"status\", \"processing\"],\n  [\"type\", \"route-scan\"],\n  [\"limit\", \"20\"],\n];\nconst body = \"\";\n\n// Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\nconst encode = (value) =>\n  encodeURIComponent(value).replace(/[!'()*]/g, (c) => \"%\" + c.charCodeAt(0).toString(16).toUpperCase());\n// Encode each name and value, then sort the encoded pairs by name, then value.\nconst query = params\n  .map(([key, value]) => [encode(key), encode(value)])\n  .sort(([ka, va], [kb, vb]) => (ka === kb ? (va < vb ? -1 : va > vb ? 1 : 0) : ka < kb ? -1 : 1))\n  .map(([key, value]) => `${key}=${value}`)\n  .join(\"&\");\n\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = randomBytes(16).toString(\"hex\");\nconst bodyHash = createHash(\"sha256\").update(body, \"utf8\").digest(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET).update(payload, \"utf8\").digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}${query ? `?${query}` : \"\"}`, {\n  method,\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\nconsole.log(response.status, await response.json());","python":"import base64\nimport hashlib\nimport hmac\nimport os\nimport secrets\nimport time\nfrom urllib.parse import quote\n\nimport requests\n\nmethod = \"GET\"\npath = \"/v1/jobs\"\nparams = [\n    (\"status\", \"processing\"),\n    (\"type\", \"route-scan\"),\n    (\"limit\", \"20\"),\n]\nbody = \"\"\n\n\ndef encode(value):\n    # Strict RFC 3986: escape everything except A-Z a-z 0-9 - . _ ~\n    return quote(value, safe=\"\")\n\n\n# Encode each name and value, then sort the encoded pairs by name, then value.\nquery = \"&\".join(f\"{key}={value}\" for key, value in sorted((encode(k), encode(v)) for k, v in params))\ntimestamp = str(int(time.time()))\nnonce = secrets.token_hex(16)\nbody_hash = hashlib.sha256(body.encode(\"utf-8\")).hexdigest()\npayload = \"\\n\".join([method, path, query, body_hash, timestamp, nonce])\nsecret = os.environ[\"RAILCORE_HMAC_SECRET\"].encode(\"utf-8\")\nsignature = base64.b64encode(hmac.new(secret, payload.encode(\"utf-8\"), hashlib.sha256).digest()).decode(\"ascii\")\n\nheaders = {\n    \"X-RailCore-Key\": os.environ[\"RAILCORE_KEY\"],\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n}\nresponse = requests.request(\n    method,\n    \"https://ir.railcore.tech\" + path + (f\"?{query}\" if query else \"\"),\n    headers=headers,\n    timeout=20,\n)\nprint(response.status_code, response.json())","php":"<?php\n$method = \"GET\";\n$path = \"/v1/jobs\";\n$params = [\n    [\"status\", \"processing\"],\n    [\"type\", \"route-scan\"],\n    [\"limit\", \"20\"],\n];\n$body = \"\";\n\n// rawurlencode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\n// Encode each name and value, then sort the encoded pairs by name, then value.\n$pairs = array_map(fn($p) => [rawurlencode($p[0]), rawurlencode($p[1])], $params);\nusort($pairs, fn($a, $b) => strcmp($a[0], $b[0]) ?: strcmp($a[1], $b[1]));\n$query = implode(\"&\", array_map(fn($p) => $p[0] . \"=\" . $p[1], $pairs));\n\n$timestamp = (string) time();\n$nonce = bin2hex(random_bytes(16));\n$payload = implode(\"\\n\", [$method, $path, $query, hash(\"sha256\", $body), $timestamp, $nonce]);\n$signature = base64_encode(hash_hmac(\"sha256\", $payload, getenv(\"RAILCORE_HMAC_SECRET\"), true));\n\n$headers = [\n    \"X-RailCore-Key: \" . getenv(\"RAILCORE_KEY\"),\n    \"X-RailCore-Timestamp: \" . $timestamp,\n    \"X-RailCore-Nonce: \" . $nonce,\n    \"X-RailCore-Signature: \" . $signature,\n];\n\n$ch = curl_init(\"https://ir.railcore.tech\" . $path . ($query !== \"\" ? \"?\" . $query : \"\"));\ncurl_setopt_array($ch, [\n    CURLOPT_CUSTOMREQUEST => $method,\n    CURLOPT_HTTPHEADER => $headers,\n    CURLOPT_RETURNTRANSFER => true,\n    CURLOPT_TIMEOUT => 20,\n]);\nif ($body !== \"\") {\n    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);\n}\n$response = curl_exec($ch);\n$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);\ncurl_close($ch);\n\necho $status, PHP_EOL;\nprint_r(json_decode($response, true));","go":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/rand\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n// encode is strict RFC 3986: it keeps only A-Z a-z 0-9 - . _ ~\nfunc encode(s string) string {\n\tvar b strings.Builder\n\tfor _, c := range []byte(s) {\n\t\tif c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~' {\n\t\t\tb.WriteByte(c)\n\t\t} else {\n\t\t\tfmt.Fprintf(&b, \"%%%02X\", c)\n\t\t}\n\t}\n\treturn b.String()\n}\n\nfunc main() {\n\tmethod := \"GET\"\n\tpath := \"/v1/jobs\"\n\tparams := [][2]string{\n\t\t{\"status\", \"processing\"},\n\t\t{\"type\", \"route-scan\"},\n\t\t{\"limit\", \"20\"},\n\t}\n\tbody := \"\"\n\n\t// Encode each name and value, then sort the encoded pairs by name, then value.\n\tencoded := make([][2]string, len(params))\n\tfor i, p := range params {\n\t\tencoded[i] = [2]string{encode(p[0]), encode(p[1])}\n\t}\n\tsort.Slice(encoded, func(i, j int) bool {\n\t\tif encoded[i][0] != encoded[j][0] {\n\t\t\treturn encoded[i][0] < encoded[j][0]\n\t\t}\n\t\treturn encoded[i][1] < encoded[j][1]\n\t})\n\tpairs := make([]string, len(encoded))\n\tfor i, p := range encoded {\n\t\tpairs[i] = p[0] + \"=\" + p[1]\n\t}\n\tquery := strings.Join(pairs, \"&\")\n\n\ttimestamp := strconv.FormatInt(time.Now().Unix(), 10)\n\tnonceBytes := make([]byte, 16)\n\tif _, err := rand.Read(nonceBytes); err != nil {\n\t\tpanic(err)\n\t}\n\tnonce := hex.EncodeToString(nonceBytes)\n\tbodyHash := sha256.Sum256([]byte(body))\n\tpayload := strings.Join([]string{method, path, query, hex.EncodeToString(bodyHash[:]), timestamp, nonce}, \"\\n\")\n\tmac := hmac.New(sha256.New, []byte(os.Getenv(\"RAILCORE_HMAC_SECRET\")))\n\tmac.Write([]byte(payload))\n\tsignature := base64.StdEncoding.EncodeToString(mac.Sum(nil))\n\n\ttarget := \"https://ir.railcore.tech\" + path\n\tif query != \"\" {\n\t\ttarget += \"?\" + query\n\t}\n\tvar reqBody io.Reader\n\tif body != \"\" {\n\t\treqBody = strings.NewReader(body)\n\t}\n\treq, err := http.NewRequest(method, target, reqBody)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"X-RailCore-Key\", os.Getenv(\"RAILCORE_KEY\"))\n\treq.Header.Set(\"X-RailCore-Timestamp\", timestamp)\n\treq.Header.Set(\"X-RailCore-Nonce\", nonce)\n\treq.Header.Set(\"X-RailCore-Signature\", signature)\n\tif body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\n\tout, _ := io.ReadAll(res.Body)\n\tfmt.Println(res.Status)\n\tfmt.Println(string(out))\n}","java":"import java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.SecureRandom;\nimport java.time.Duration;\nimport java.util.ArrayList;\nimport java.util.Base64;\nimport java.util.HexFormat;\nimport java.util.List;\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\n\n// Java 17 or later (HexFormat).\npublic class RailCoreSignedExample {\n    // Strict RFC 3986: keep only A-Z a-z 0-9 - . _ ~\n    static String encode(String value) {\n        StringBuilder out = new StringBuilder();\n        for (byte b : value.getBytes(StandardCharsets.UTF_8)) {\n            int c = b & 0xFF;\n            if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '.' || c == '_' || c == '~') {\n                out.append((char) c);\n            } else {\n                out.append(String.format(\"%%%02X\", c));\n            }\n        }\n        return out.toString();\n    }\n\n    public static void main(String[] args) throws Exception {\n        String method = \"GET\";\n        String path = \"/v1/jobs\";\n        List<String[]> params = new ArrayList<>(List.<String[]>of(\n            new String[] {\"status\", \"processing\"},\n            new String[] {\"type\", \"route-scan\"},\n            new String[] {\"limit\", \"20\"}\n        ));\n        String body = \"\";\n\n        // Encode each name and value, then sort the encoded pairs by name, then value.\n        List<String[]> encoded = new ArrayList<>();\n        for (String[] p : params) encoded.add(new String[] {encode(p[0]), encode(p[1])});\n        encoded.sort((a, b) -> a[0].equals(b[0]) ? a[1].compareTo(b[1]) : a[0].compareTo(b[0]));\n        List<String> pairs = new ArrayList<>();\n        for (String[] p : encoded) pairs.add(p[0] + \"=\" + p[1]);\n        String query = String.join(\"&\", pairs);\n\n        String timestamp = Long.toString(System.currentTimeMillis() / 1000);\n        byte[] nonceBytes = new byte[16];\n        new SecureRandom().nextBytes(nonceBytes);\n        String nonce = HexFormat.of().formatHex(nonceBytes);\n        String bodyHash = HexFormat.of().formatHex(MessageDigest.getInstance(\"SHA-256\").digest(body.getBytes(StandardCharsets.UTF_8)));\n        String payload = String.join(\"\\n\", method, path, query, bodyHash, timestamp, nonce);\n        Mac mac = Mac.getInstance(\"HmacSHA256\");\n        mac.init(new SecretKeySpec(System.getenv(\"RAILCORE_HMAC_SECRET\").getBytes(StandardCharsets.UTF_8), \"HmacSHA256\"));\n        String signature = Base64.getEncoder().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));\n\n        HttpRequest.Builder request = HttpRequest.newBuilder()\n            .uri(URI.create(\"https://ir.railcore.tech\" + path + (query.isEmpty() ? \"\" : \"?\" + query)))\n            .timeout(Duration.ofSeconds(20))\n            .header(\"X-RailCore-Key\", System.getenv(\"RAILCORE_KEY\"))\n            .header(\"X-RailCore-Timestamp\", timestamp)\n            .header(\"X-RailCore-Nonce\", nonce)\n            .header(\"X-RailCore-Signature\", signature);\n        if (body.isEmpty()) {\n            request.method(method, HttpRequest.BodyPublishers.noBody());\n        } else {\n            request.header(\"Content-Type\", \"application/json\").method(method, HttpRequest.BodyPublishers.ofString(body));\n        }\n\n        HttpResponse<String> response = HttpClient.newHttpClient()\n            .send(request.build(), HttpResponse.BodyHandlers.ofString());\n        System.out.println(response.statusCode());\n        System.out.println(response.body());\n    }\n}"}}}],"guides":[{"id":"overview","title":"Documentation home","description":"Indian Railways API docs: live train running status, schedules, stations, seat availability and fares, with a playground. Free tier: 500 requests a month.","group":"Get started","url":"https://railcore.tech/docs","markdown_url":"https://railcore.tech/docs.md","markdown":"# Indian Railways API documentation\n\nLive train status, schedules, stations, seat availability, fares, chart intelligence, and async analysis through one authenticated v1 API.\n\n## Start here\n\n1. [Create a key Sign up, verify your email and create a free key in the console.](https://railcore.tech/docs/quickstart)\n2. [Send it in a header X-RailCore-Key or Authorization: Bearer, on every request. Some plans also sign each one.](https://railcore.tech/docs/authentication)\n3. [Read the envelope success, then data or error, with a request ID on every answer.](https://railcore.tech/docs/responses)\n\n## Base URL\n\nv1 has one production environment. There is no sandbox in the current major.\n\n`https://ir.railcore.tech/v1`\n\n## First request\n\nEvery operation needs your API key, in X-RailCore-Key, Authorization: Bearer or X-Api-Key: pick the header on the sample. Store the key in an environment variable, not source code.\n\nTerminal\n\n```\ncurl -sS \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/stations/search?q=bhusaval&limit=5\"\n```\n\nGrowth, Scale and Enterprise keys must sign\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone. Without a signature their requests answer `401 SIGNATURE_INVALID`. [How to sign a request](https://railcore.tech/docs/hmac).\n\n## API map\n\n30 operations in 7 groups. The reference lists every operation an API key can call, including the async job operations.\n\n### Stations\n\n- [GET Search stations `/v1/stations/search`](https://railcore.tech/docs/api/search-stations)\n- [GET Get station `/v1/stations/{station_code}`](https://railcore.tech/docs/api/get-station)\n- [GET Live station board `/v1/stations/{station_code}/live`](https://railcore.tech/docs/api/live-station-board)\n\n### Trains\n\n- [GET Search trains `/v1/trains/search`](https://railcore.tech/docs/api/search-trains)\n- [GET Get train `/v1/trains/{train_number}`](https://railcore.tech/docs/api/get-train)\n- [GET Train schedule `/v1/trains/{train_number}/schedule`](https://railcore.tech/docs/api/train-schedule)\n- [GET Booking stops `/v1/trains/{train_number}/stops`](https://railcore.tech/docs/api/train-stops)\n- [GET Full train route `/v1/trains/{train_number}/route`](https://railcore.tech/docs/api/train-route)\n- [GET Coach position `/v1/trains/{train_number}/coach-position`](https://railcore.tech/docs/api/coach-position)\n- [GET Live train status `/v1/trains/{train_number}/live`](https://railcore.tech/docs/api/live-train)\n\n### Journeys\n\n- [GET Trains between stations `/v1/routes/trains`](https://railcore.tech/docs/api/route-trains)\n- [GET Journey search `/v1/journeys/search`](https://railcore.tech/docs/api/journey-search)\n- [POST Compare journeys `/v1/journeys/compare`](https://railcore.tech/docs/api/compare-journeys)\n\n### Availability\n\n- [GET Seat availability `/v1/availability/seats`](https://railcore.tech/docs/api/seat-availability)\n- [POST Batch seat availability `/v1/availability/seats/batch`](https://railcore.tech/docs/api/batch-seat-availability)\n- [GET Availability calendar `/v1/availability/calendar`](https://railcore.tech/docs/api/availability-calendar)\n- [GET Available classes `/v1/availability/classes`](https://railcore.tech/docs/api/available-classes)\n\n### Fares\n\n- [GET Fare estimate `/v1/fares/estimate`](https://railcore.tech/docs/api/fare-estimate)\n- [GET Search fares `/v1/fares/search`](https://railcore.tech/docs/api/search-fares)\n- [GET Unreserved fare `/v1/fares/unreserved`](https://railcore.tech/docs/api/unreserved-fare)\n\n### Charts Scale and Enterprise only\n\n- [GET Chart status `/v1/charts/status`](https://railcore.tech/docs/api/chart-status)\n- [GET Vacant berths `/v1/charts/vacant-berths`](https://railcore.tech/docs/api/vacant-berths)\n- [GET Vacant berth hopping `/v1/charts/vacant-berths/hopping`](https://railcore.tech/docs/api/vacant-berths-hopping)\n- [GET Route vacancy scan `/v1/charts/vacant-berths/route-scan`](https://railcore.tech/docs/api/route-vacancy-scan)\n\n### Jobs Scale and Enterprise only\n\n- [POST Submit route-scan job `/v1/jobs/route-scan`](https://railcore.tech/docs/api/submit-route-scan-job)\n- [POST Submit hopping job `/v1/jobs/hopping`](https://railcore.tech/docs/api/submit-hopping-job)\n- [GET Get job `/v1/jobs/{job_id}`](https://railcore.tech/docs/api/get-job)\n- [DELETE Cancel job `/v1/jobs/{job_id}`](https://railcore.tech/docs/api/cancel-job)\n- [GET Stream job progress `/v1/jobs/{job_id}/stream`](https://railcore.tech/docs/api/stream-job)\n- [GET List jobs `/v1/jobs`](https://railcore.tech/docs/api/list-jobs)\n\n## How the API behaves\n\n- **Live by default:** Responses use no-store headers and include freshness metadata. Do not treat live train or availability data as static.\n- **Failed requests are free:** Only successful 2xx responses are counted, and most requests count as one. [See plans and costs](https://railcore.tech/docs/credits).\n- **Null means unknown:** A field the API cannot establish for a run is null. It is never filled in from the timetable.\n- **Codes are the contract:** Messages can be reworded; `error.code` stays. [Every code](https://railcore.tech/docs/errors-reference) is in one catalog.\n\n## Plans and terms\n\nWhat each plan includes and costs, and the terms every API key is used under.\n\n[Plans and pricing](https://railcore.tech/pricing)\n\n[Developer API Terms](https://railcore.tech/legal/api-terms)\n\nSource: https://railcore.tech/docs\nLast updated: 12 Nov 2026\n"},{"id":"quickstart","title":"Quickstart","description":"Make your first request to the RailCore Indian Railways API: create a free key, then get live train status from cURL, Node.js, Python, PHP, Go or Java.","group":"Get started","url":"https://railcore.tech/docs/quickstart","markdown_url":"https://railcore.tech/docs/quickstart.md","markdown":"# Quickstart\n\nMake the first authenticated request.\n\n## 1. Sign up and verify your email\n\n[Create a RailCore account](https://railcore.tech/login?mode=signup&next=%2Fdashboard%3Fview%3Ddeveloper%26section%3Dkeys) and open the link in the email we send you. Keys and the rest of the developer console unlock once your email is verified.\n\n## 2. Create a key\n\nOpen **Dashboard > Developer > API keys** and create a key with the `live:read` scope. The Free plan costs nothing: 500 requests a month, 10 a minute and 100 a day, on 20 of the 30 endpoints, live train status included. Build and evaluate. No card, no phone number.\n\nThe plaintext appears once\n\nCopy the key into your secret manager immediately. RailCore stores only its hash.\n\nTerminal\n\n```\nexport RAILCORE_KEY=\"rk_live_your_key_here\"\n```\n\n## 3. Ask where a train is\n\nLive train status for 12951, for the run that leaves its first station today in India. Each sample works out today's date when it runs.\n\n```\nRUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -i \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  \"https://ir.railcore.tech/v1/trains/12951/live?date=$RUN_DATE\"\n```\n\nThe key travels in `X-RailCore-Key`, `Authorization: Bearer` or `X-Api-Key`: pick one under **Key header** and every sample in these docs is written that way. Send the key in one header only.\n\n## 4. Read the response\n\n| Path | Use |\n| --- | --- |\n| `success` | Branch before reading data or error. |\n| `data` | Endpoint payload on success: here the run's status, delay and every station. |\n| `error.code` | Stable machine-readable failure code. |\n| `meta.request_id` | Log this value and include it in support requests. |\n| `meta.freshness` | Live retrieval and confidence context. |\n\n### Headers to expect\n\nHTTP\n\n```\nHTTP/2 200\nContent-Type: application/json; charset=utf-8\nCache-Control: no-store, no-cache, must-revalidate, private\nX-RailCore-Request-ID: req_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\nX-RailCore-Plan: developer_free\nX-RailCore-RateLimit-Limit: 10\nX-RailCore-RateLimit-Remaining: 9\nX-RailCore-RateLimit-Reset: 1785472200\nX-RailCore-RateLimit-Day-Limit: 100\nX-RailCore-RateLimit-Day-Remaining: 99\nX-RailCore-RateLimit-Day-Reset: 1785522600\nX-RailCore-Credits-Cost: 1\nX-RailCore-Credits-Remaining: 499\nX-RailCore-Confidence: high\nServer-Timing: key;dur=3, limits;dur=2, credits;dur=4, upstream;dur=21, total;dur=31\n```\n\nThis request counts as 1 request: `X-RailCore-Credits-Cost` says what it counted as and `X-RailCore-Credits-Remaining` how many requests are left this month. A request that fails is not counted. The rate-limit headers are your account's, shared by all its keys. [Every header](https://railcore.tech/docs/headers).\n\n## 5. On a signed plan, sign it\n\nGrowth, Scale and Enterprise keys must sign\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone. Without a signature their requests answer `401 SIGNATURE_INVALID`. [How to sign a request](https://railcore.tech/docs/hmac).\n\nNode.js, signed\n\n```\nimport crypto from \"node:crypto\";\n\nconst runDate = new Intl.DateTimeFormat(\"en-CA\", { timeZone: \"Asia/Kolkata\" }).format(new Date());\nconst path = \"/v1/trains/12951/live\";\nconst query = `date=${runDate}`;\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = crypto.randomBytes(16).toString(\"hex\");\n// A GET has no body, so its hash is the hash of zero bytes.\nconst bodyHash = crypto.createHash(\"sha256\").update(\"\").digest(\"hex\");\nconst payload = [\"GET\", path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = crypto\n  .createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET)\n  .update(payload)\n  .digest(\"base64\");\n\nconst response = await fetch(`https://ir.railcore.tech${path}?${query}`, {\n  headers: {\n    \"X-RailCore-Key\": process.env.RAILCORE_KEY,\n    \"X-RailCore-Timestamp\": timestamp,\n    \"X-RailCore-Nonce\": nonce,\n    \"X-RailCore-Signature\": signature,\n  },\n});\n```\n\nThe signing secret is shown once, with the key, when you create or rotate a Growth, Scale or Enterprise key. Keep it on your server, here as `RAILCORE_HMAC_SECRET`.\n\nThe signature covers the method, path, query, a hash of the exact body bytes, the timestamp and a nonce. [HMAC signing](https://railcore.tech/docs/hmac) has the full rules.\n\n## Next\n\n- Try any endpoint from its page with the playground. Signed in, choose Use my account: it works on every plan, with no signing, within your plan's per-minute limit. Or paste a Free or Starter key. [Using the playground](https://railcore.tech/docs/playground).\n- See what every endpoint counts as in [requests and billing](https://railcore.tech/docs/credits), and the limits in [rate limits](https://railcore.tech/docs/rate-limits).\n- Compare plans on [pricing](https://railcore.tech/pricing).\n\nSource: https://railcore.tech/docs/quickstart\nLast updated: 13 Nov 2026\n"},{"id":"authentication","title":"Authentication","description":"How authentication works on the RailCore Indian Railways API: the three key headers, scopes, expiry and rotation, IP allowlists and request signing.","group":"Get started","url":"https://railcore.tech/docs/authentication","markdown_url":"https://railcore.tech/docs/authentication.md","markdown":"# Authentication\n\nAPI keys, scopes, expiry, and IP allowlists.\n\n## API-key header\n\nHTTP\n\n```\nGET /v1/trains/12656 HTTP/1.1\nHost: ir.railcore.tech\nX-RailCore-Key: rk_live_your_key_here\n```\n\nKeys are opaque values with at least 24 characters. Do not place them in browser bundles, URLs, logs, public repositories, mobile apps, or support messages.\n\nSend the key in X-RailCore-Key, or as Authorization: Bearer \\<key>, or in X-Api-Key. Use one header: two headers with different keys answer 401 AMBIGUOUS_API_KEY. The other two headers carry the same key:\n\nAlternatives\n\n```\nAuthorization: Bearer rk_live_your_key_here\nX-Api-Key: rk_live_your_key_here\n```\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone. The signature does not cover the key, so it verifies the same whichever header carries it. [How to sign a request](https://railcore.tech/docs/hmac).\n\n## Scopes\n\nIssue a separate least-privilege key for each integration and environment. All keys on an account share its rate limits and monthly requests.\n\n| Scope | Access |\n| --- | --- |\n| `stations:read` | Station search and static station details |\n| `trains:read` | Train search and static train details |\n| `schedule:read` | Schedules, stops, routes, and coach positions |\n| `live:read` | Live station boards and live train status |\n| `journeys:read` | Route discovery, journey search, and comparison |\n| `availability:read` | Seat availability, calendars, and classes |\n| `fares:read` | Reserved and unreserved fares |\n| `charts:read` | Chart, vacancy, and job-result reads |\n| `charts:write` | Submit and cancel premium analysis jobs |\n\n## Plan security controls\n\n| Control | Free | Starter | Growth | Scale | Enterprise |\n| --- | --- | --- | --- | --- | --- |\n| API-key header | Yes | Yes | Yes | Yes | Yes |\n| IPv4 and IPv6 allowlist | No | No | Optional | Optional | Optional |\n| HMAC signing | No | No | Required | Required | Required |\n| Premium chart scopes | No | No | No | Yes | Yes |\n\n## IP allowlists\n\nGrowth, Scale and Enterprise keys can restrict requests to fixed egress CIDR blocks.\n\nCIDR examples\n\n```\n203.0.113.42/32\n203.0.113.0/24\n2001:db8:abcd::/48\n```\n\nIPv4 prefixes may be /8 to /32. IPv6 prefixes may be /48 to /128. Allowlist the public NAT or proxy address that reaches RailCore.\n\n## Lifecycle\n\nExpiration\n\nKeys do not expire by default. Add expires_at for temporary integrations.\n\nRotation\n\nRotation creates a replacement secret and revokes the previous credential.\n\nRevocation\n\nDashboard revocation is immediate and propagates in under a second.\n\nHMAC mode\n\nGrowth, Scale and Enterprise keys must sign every request and come with a one-time signing secret. A key issued before November 3, 2026 has no secret: rotate it to get one.\n\nSource: https://railcore.tech/docs/authentication\nLast updated: 10 Nov 2026\n"},{"id":"playground","title":"Using the playground","description":"Try every RailCore Indian Railways API endpoint in the browser, signed in or with a key: build a request, send it and read the live response.","group":"Get started","url":"https://railcore.tech/docs/playground","markdown_url":"https://railcore.tech/docs/playground.md","markdown":"# Using the playground\n\nTest with your account or a key.\n\n## What the tester sends\n\nUse my account\n\nSigned in, the playground gets a token for your own account that lasts 15 minutes, and sends it as Authorization: Bearer. It works on every plan with no signing. Its requests count against your account's monthly requests and limits, including your plan's per-minute limit. It can only read, so submitting or cancelling a job cannot be tried here: send those from your server, with a signed request.\n\nMemory-only key\n\nOr paste a Free or Starter key. It stays in this page's memory and is cleared when the page closes.\n\nDirect request\n\nThe browser calls https://ir.railcore.tech. RailCore docs do not proxy or record the key or the token.\n\n20 second guard\n\nLong requests can be cancelled and are stopped automatically after the playground timeout.\n\nEndpoint examples\n\nEvery endpoint page has cURL, Node.js, Python, PHP, Go and Java samples that read the key from an environment variable.\n\n## Workflow\n\n1. Choose an endpoint from the API reference.\n2. Signed in, choose Use my account: it works on every plan. Or paste a Free or Starter key with the required scope. A pasted Growth, Scale or Enterprise key is refused, because those keys must sign every request.\n3. Review the populated path, query, or JSON body fields. Clear optional fields you do not want to send.\n4. Send the request. Inspect the HTTP status, measured browser latency, body, and exposed response headers.\n5. Use the endpoint page's code examples when moving the tested request into your server-side application.\n\nNever enter a signing secret here\n\nThe playground never asks for one. Keep it on your server and sign there with the [HMAC examples](https://railcore.tech/docs/hmac). To try a Growth, Scale and Enterprise plan from this page, sign in and choose Use my account.\n\nCORS and exposed headers\n\nIf a browser blocks the request, use the generated server-side sample. Browsers show only headers that the API exposes through CORS.\n\nSource: https://railcore.tech/docs/playground\nLast updated: 10 Nov 2026\n"},{"id":"responses","title":"Response envelope","description":"The response envelope every RailCore Indian Railways API endpoint returns: success and error shapes, request ids, freshness metadata and response headers.","group":"Core concepts","url":"https://railcore.tech/docs/responses","markdown_url":"https://railcore.tech/docs/responses.md","markdown":"# Response envelope\n\nShared success, error, metadata, and headers.\n\n## Success envelope\n\nJSON\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"query\": \"bhusaval\",\n    \"results\": []\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J...\",\n    \"trace_id\": \"trc_01J...\",\n    \"timestamp\": \"2026-11-20T10:57:12.764Z\",\n    \"freshness\": {\n      \"mode\": \"live\",\n      \"retrieved_at\": \"2026-11-20T10:57:12.764Z\",\n      \"sources\": [\n        {\n          \"confidence\": \"high\"\n        }\n      ]\n    }\n  }\n}\n```\n\n## Shared fields\n\n- `success` boolean Whether the operation succeeded.\n- `data` object Endpoint-specific payload. Replaced by error on failures.\n- `meta.api_version` string API major used for the response.\n- `meta.request_id` string Stable request identifier to include with support requests.\n- `meta.trace_id` string Distributed trace identifier.\n- `meta.timestamp` string(date-time) Response creation time as an ISO instant.\n- `meta.freshness` object Live retrieval time and source confidence metadata.\n\n## Freshness\n\nLive requests emit `Cache-Control: no-store, no-cache, must-revalidate, private`. The confidence header and freshness block report whether live sources agreed and when they last reported.\n\n## Forward-compatible parsing\n\n- Ignore unknown response fields.\n- Branch on `success` before reading data.\n- Use `error.code`, never parse the human message.\n- Allow unknown enum and error values to fall through to a safe default.\n- Log the request ID with operation, status, and latency.\n\nSource: https://railcore.tech/docs/responses\nLast updated: 10 Nov 2026\n"},{"id":"errors","title":"Errors and retries","description":"Handle RailCore Indian Railways API errors correctly: stable error codes, which failures are retryable, Retry-After on 429 and 503, and how to back off safely.","group":"Core concepts","url":"https://railcore.tech/docs/errors","markdown_url":"https://railcore.tech/docs/errors.md","markdown":"# Errors and retries\n\nStable codes and retry decisions.\n\n## Error envelope\n\nJSON\n\n```\n{\n  \"success\": false,\n  \"error\": {\n    \"code\": \"STATION_NOT_FOUND\",\n    \"message\": \"Station ZZZZ not found. Check the station code.\",\n    \"category\": \"NOT_FOUND\",\n    \"retryable\": false,\n    \"details\": []\n  },\n  \"meta\": {\n    \"api_version\": \"v1\",\n    \"request_id\": \"req_01J...\",\n    \"trace_id\": \"trc_01J...\",\n    \"timestamp\": \"2026-11-20T10:57:12.786Z\"\n  }\n}\n```\n\nA 404 names what was not found: `Station ZZZZ not found. Check the station code.` or `Train 99999 not found. Check the train number.`\n\n## Validation details\n\nA 400 VALIDATION_ERROR lists each problem in error.details. field names the parameter or body field, with its place in a list where it has one.\n\nJSON\n\n```\n{\n  \"success\": false,\n  \"error\": {\n    \"code\": \"VALIDATION_ERROR\",\n    \"message\": \"'match' must be city or station\",\n    \"category\": \"VALIDATION\",\n    \"retryable\": false,\n    \"details\": [\n      {\n        \"field\": \"match\",\n        \"issue\": \"'match' must be city or station\"\n      }\n    ]\n  }\n}\n```\n\nOther values of `field` include `date`, `items[2].date` and `callback_url`.\n\n## Categories\n\n| Category | Typical HTTP | Action |\n| --- | --- | --- |\n| VALIDATION | 400 or 422 | Fix the request. Never retry unchanged. A 422 means the journey itself can't be enquired (quota, class, run day, booking window). |\n| AUTH | 401 or 403 | Fix or rotate the credential, or check the key's IP allowlist, scopes and plan status. |\n| FORBIDDEN | 403 | Move to a plan that includes the endpoint. |\n| QUOTA | 402 | Wait for renewal or change plan. |\n| RATE_LIMIT | 429 | Honor Retry-After and add jitter. |\n| NOT_FOUND | 404, 409 or 410 | Verify identifiers. Chart pending can be retried later. |\n| UPSTREAM | 503 | Wait for Retry-After, then retry with bounded exponential backoff. |\n| INTERNAL | 500 or 503 | Retry with backoff and alert if persistent. |\n\nUpstream failures answer 503\n\nWhen a live-data source fails or times out, the API answers `503` with `UPSTREAM_UNAVAILABLE` or `UPSTREAM_TIMEOUT`, a `Retry-After` header and the usual request ID. The request is not counted. Because `METERING_UNAVAILABLE` is a 503 too, branch on `error.code`, not the status.\n\n## Retry policy\n\nNode.js\n\n```\nfunction shouldRetry(status, error, attempt) {\n  if (attempt >= 5) return false;\n  if (status === 429) return true;\n  return [\n    \"UPSTREAM_UNAVAILABLE\",\n    \"UPSTREAM_TIMEOUT\",\n    \"METERING_UNAVAILABLE\",\n    \"INTERNAL\",\n  ].includes(error.code);\n}\n```\n\nRecommended backoff\n\nUse approximately 500 ms, 1 s, 2 s, and 4 s with jitter. Honor Retry-After on 429 and 503 responses and stop after five attempts.\n\n## Debugging checklist\n\n1. Log the response status, `error.code`, and `X-RailCore-Request-ID`.\n2. Verify the key scope and plan entitlement for this route.\n3. For signature failures, print the exact canonical payload without the secret.\n4. For repeated live-data failures, check status.railcore.tech.\n5. Include the request ID in a support message within the seven-day request-log window.\n\nSource: https://railcore.tech/docs/errors\nLast updated: 19 Nov 2026\n"},{"id":"rate-limits","title":"Rate limits","description":"RailCore Indian Railways API rate limits: per-minute budgets on every plan, the Free plan's daily cap, the headers that say what is left, and 429 responses.","group":"Core concepts","url":"https://railcore.tech/docs/rate-limits","markdown_url":"https://railcore.tech/docs/rate-limits.md","markdown":"# Rate limits\n\nPer-minute budgets, headers, and 429s.\n\n## Plan budgets\n\nEvery account has a per-minute budget. Free accounts also have a daily budget, counted per IST day. Starter, Growth and Scale have no daily cap. Rate limits are per account. Every key on the account shares them, and creating another key does not reset them.\n\n| Plan | Per minute | Per IST day |\n| --- | --- | --- |\n| Free | 10 | 100 |\n| Starter | 60 | No daily cap |\n| Growth | 200 | No daily cap |\n| Scale | 500 | No daily cap |\n| Enterprise | Agreed | Agreed |\n\n## Response headers\n\nA response on a Free account, two requests into the minute and the day. The counts are the account's, whichever key sent the request:\n\nHTTP\n\n```\nX-RailCore-RateLimit-Limit: 10\nX-RailCore-RateLimit-Remaining: 8\nX-RailCore-RateLimit-Reset: 1785472200\nX-RailCore-RateLimit-Day-Limit: 100\nX-RailCore-RateLimit-Day-Remaining: 98\nX-RailCore-RateLimit-Day-Reset: 1785522600\n```\n\nX-RailCore-RateLimit-Limit, -Remaining and -Reset are sent only when the account's plan has a per-minute limit. A plan without one (Enterprise), and a request refused before the key was read (a malformed request, a missing or wrong key), get none of the three, never 0. Only Free accounts have a daily cap, and only their keys receive the X-RailCore-RateLimit-Day-* headers. A key without a daily cap gets no Day-* headers and never a daily 429. Read each header only when it is present.\n\n429 means stop\n\nRespect Retry-After. Extra keys or workers do not help: every key on the account draws on the same limits. Daily budgets reset at 00:00 IST.\n\n## High-cost edge caps\n\nOn top of the plan's per-minute budget, and shared by every key on the account like it.\n\n| Route family | Additional cap |\n| --- | --- |\n| `/v1/charts/*` | 30 requests per minute per account |\n| `/v1/availability/seats/batch` | 30 requests per minute per account |\n\n## Monthly requests are separate\n\nRate limits and monthly requests both belong to the account, and its keys share them. A request must pass both. Hitting a rate limit returns 429 and is retryable; running out of requests returns 402 `CREDITS_EXHAUSTED` and is not retryable until the plan renews or changes. See [requests and billing](https://railcore.tech/docs/credits).\n\nSource: https://railcore.tech/docs/rate-limits\nLast updated: 13 Nov 2026\n"},{"id":"credits","title":"Requests and billing","description":"RailCore Indian Railways API pricing: monthly requests on each plan, what each endpoint counts as (most count as one), batches, and free failed requests.","group":"Core concepts","url":"https://railcore.tech/docs/credits","markdown_url":"https://railcore.tech/docs/credits.md","markdown":"# Requests and billing\n\nPlans, per-request costs, and batches.\n\n## How requests are counted\n\n- Each plan includes a number of requests a month. Most requests count as 1; the table below lists every cost.\n- Only successful 2xx responses are counted. A request that fails, for any reason, is free. A batch or comparison that succeeds is counted at the size it asked for, even when some of its items fail inside the response.\n- The response headers keep their older name: `X-RailCore-Credits-Cost` is what this request counted as and `X-RailCore-Credits-Remaining` the requests left. One credit is one request.\n- When the month's requests run out, requests answer 402 `CREDITS_EXHAUSTED` until the plan renews or you change plan.\n\n## Plans\n\nMonthly list prices in Indian rupees. Rate limits are on the rate limits page.\n\n| Plan | List price | Requests a month | Per 1,000 requests | Use |\n| --- | --- | --- | --- | --- |\n| Free | ₹0 | 500 | Free | Evaluation and personal projects |\n| Starter | ₹699/month | 40,000 | ₹17.48 | Commercial use |\n| Growth | ₹2,499/month | 1,50,000 | ₹16.66 | Commercial use |\n| Scale | ₹6,499/month | 5,00,000 | ₹13.00 | Commercial use |\n| Enterprise | Contract | Agreed volume | Contract | Commercial use |\n\n## Cost per request\n\nMost endpoints count each request as one. The chart suite counts more because each of its requests does far more work.\n\n| Operation | Requests | Plans |\n| --- | --- | --- |\n| GET `/v1/stations/search` | 1 request | All plans |\n| GET `/v1/stations/{station_code}` | 1 request | All plans |\n| GET `/v1/stations/{station_code}/live` | 1 request | All plans |\n| GET `/v1/trains/search` | 1 request | All plans |\n| GET `/v1/trains/{train_number}` | 1 request | All plans |\n| GET `/v1/trains/{train_number}/schedule` | 1 request | All plans |\n| GET `/v1/trains/{train_number}/stops` | 1 request | All plans |\n| GET `/v1/trains/{train_number}/route` | 1 request | All plans |\n| GET `/v1/trains/{train_number}/coach-position` | 1 request | All plans |\n| GET `/v1/trains/{train_number}/live` | 1 request | All plans |\n| GET `/v1/routes/trains` | 1 request | All plans |\n| GET `/v1/journeys/search` | 1 request | All plans |\n| POST `/v1/journeys/compare` | 1 request per route compared, minimum 1 request | All plans |\n| GET `/v1/availability/seats` | 1 request | All plans |\n| POST `/v1/availability/seats/batch` | 1 request per distinct class per item, minimum 1 request | All plans |\n| GET `/v1/availability/calendar` | 1 request | All plans |\n| GET `/v1/availability/classes` | 1 request | All plans |\n| GET `/v1/fares/estimate` | 1 request | All plans |\n| GET `/v1/fares/search` | 1 request | All plans |\n| GET `/v1/fares/unreserved` | 1 request | All plans |\n| GET `/v1/charts/status` | 1 request | Scale and Enterprise |\n| GET `/v1/charts/vacant-berths` | 3 requests | Scale and Enterprise |\n| GET `/v1/charts/vacant-berths/hopping` | 4 requests | Scale and Enterprise |\n| GET `/v1/charts/vacant-berths/route-scan` | 8 requests | Scale and Enterprise |\n| POST `/v1/jobs/route-scan` | 8 requests | Scale and Enterprise |\n| POST `/v1/jobs/hopping` | 4 requests | Scale and Enterprise |\n| GET `/v1/jobs/{job_id}` | 0 requests | Scale and Enterprise |\n| DELETE `/v1/jobs/{job_id}` | 0 requests | Scale and Enterprise |\n| GET `/v1/jobs/{job_id}/stream` | 0 requests | Scale and Enterprise |\n| GET `/v1/jobs` | 0 requests | Scale and Enterprise |\n\n## Batches and comparisons\n\nJavaScript\n\n```\n// POST /v1/availability/seats/batch\n// 1 request per distinct class per item, minimum 1 request. Classes compare case-insensitively,\n// so a class repeated in one item counts once. An item without classes,\n// or with an empty list, is checked in 4 default classes.\nconst distinctClasses = (classes) => new Set(classes.map((code) => String(code).trim().toUpperCase())).size;\nconst classRequests = items.reduce((total, item) => total + (item.classes?.length ? distinctClasses(item.classes) : 4), 0);\nconst batchCalls = Math.max(1, classRequests);\n\n// POST /v1/journeys/compare\n// 1 request per route compared, minimum 1 request.\nconst compareCalls = Math.max(1, journeys.length);\n```\n\nThe largest batch, 25 items with 8 classes each, counts as 200 requests. Comparing 5 routes counts as 5 requests.\n\nThe cost is worked out from the request body before any lookup runs. A batch or comparison that answers 200 is counted at that size: an item or route that fails inside the response still counts, and nothing is given back for it. A request refused as a whole (4xx or 5xx) is free. Ask only for the classes you need.\n\n## Settlement rules\n\n`2xx`\n\nCounted. X-RailCore-Credits-Cost and X-RailCore-Credits-Remaining report the requests counted and left.\n\n`4xx or 5xx`\n\nNot counted.\n\n`402`\n\nToo few requests are left to cover this one. Nothing is fetched.\n\n`503 METERING_UNAVAILABLE`\n\nA successful live result is withheld because the request could not be counted.\n\n`Async jobs`\n\nSubmission is counted when accepted, and stays counted if the job later fails or is cancelled. Polling, listing, streaming and cancelling count as 0 requests.\n\nSource: https://railcore.tech/docs/credits\nLast updated: 13 Nov 2026\n"},{"id":"hmac","title":"HMAC signing","description":"Sign RailCore Indian Railways API requests with HMAC: payload canonicalization, the signature header, timestamp windows and replay protection.","group":"Core concepts","url":"https://railcore.tech/docs/hmac","markdown_url":"https://railcore.tech/docs/hmac.md","markdown":"# HMAC signing\n\nPayload canonicalization and replay protection.\n\nWho must sign\n\nGrowth, Scale and Enterprise keys must also sign every request with HMAC-SHA256, sending X-RailCore-Timestamp, X-RailCore-Nonce and X-RailCore-Signature. Free and Starter keys send the key alone.\n\n## Required headers\n\nHTTP\n\n```\nX-RailCore-Key: rk_live_...\nX-RailCore-Timestamp: 1785472200\nX-RailCore-Nonce: 01J5Z7Y8N2K4M6P8R0T2V4X6Z8\nX-RailCore-Signature: base64_hmac_value\n```\n\nThe signing secret is shown once, with the key, when you create or rotate a Growth, Scale or Enterprise key. It never leaves your server: it is not sent in any header.\n\nThe key header is your choice: the signature does not cover it, so it verifies the same in `X-RailCore-Key`, `Authorization: Bearer` or `X-Api-Key`.\n\n## Signature payload\n\nCanonical bytes\n\n```\nMETHOD\nPATH\nCANONICAL_QUERY\nSHA256_HEX(BODY)\nTIMESTAMP\nNONCE\n```\n\n## Signing rules\n\n- Encode with RFC 3986. Leave only A-Z, a-z, 0-9, hyphen, underscore, period, and tilde unescaped.\n- Use uppercase percent-encoding hex.\n- Sort keys in ASCII order. Sort repeated values and emit each pair.\n- Hash the exact bytes of the request body, as sent. Any JSON formatting works, compact or indented, as long as the bytes you hash are the bytes you send. A request with no body hashes zero bytes.\n- Acceptable timestamp skew is plus or minus 5 min. Generate a fresh 16 to 128 character nonce for every attempt.\n\n## Check a signature\n\nBuild the same request here and compare each line with what your code produces. A mismatch in the canonical query or the body hash is the usual cause of SIGNATURE_INVALID.\n\n## Node.js signing core\n\nNode.js\n\n```\nimport crypto from \"node:crypto\";\n\nconst method = \"GET\";\nconst path = \"/v1/routes/trains\";\n// A week from today, so the sample never asks about a date that has passed.\nconst date = new Date(Date.now() + 7 * 86_400_000).toISOString().slice(0, 10);\nconst query = `date=${date}&from=BSL&to=ADI`;\nconst bodyHash = crypto.createHash(\"sha256\").update(\"\").digest(\"hex\");\nconst timestamp = Math.floor(Date.now() / 1000).toString();\nconst nonce = crypto.randomBytes(16).toString(\"hex\");\nconst payload = [method, path, query, bodyHash, timestamp, nonce].join(\"\\n\");\nconst signature = crypto\n  .createHmac(\"sha256\", process.env.RAILCORE_HMAC_SECRET)\n  .update(payload)\n  .digest(\"base64\");\n```\n\n## Signing a body\n\nSerialize the body once, hash that string, and send the same string. The API hashes the bytes it receives, so whitespace and key order are yours to choose.\n\nNode.js\n\n```\n// The exact string you send. Indented or compact, either signs correctly.\nconst body = JSON.stringify({ journeys: [{ from: \"BSL\", to: \"ADI\", date }] }, null, 2);\nconst bodyHash = crypto.createHash(\"sha256\").update(body).digest(\"hex\");\nconst payload = [\"POST\", \"/v1/journeys/compare\", \"\", bodyHash, timestamp, nonce].join(\"\\n\");\n// ...sign payload as above, then send the same string:\nawait fetch(\"https://ir.railcore.tech/v1/journeys/compare\", {\n  method: \"POST\",\n  headers: { \"Content-Type\": \"application/json\", /* key and signature headers */ },\n  body,\n});\n```\n\nDo not sign in a frontend\n\nThe signing secret is a server credential. A leaked API key alone should not be enough to forge signed requests.\n\n## Common failures\n\n| Code | Check |\n| --- | --- |\n| SIGNATURE_INVALID | Secret, path including /v1, canonical query ordering, and that the body hash is of the exact bytes sent |\n| TIMESTAMP_EXPIRED | NTP and Unix seconds |\n| NONCE_REUSED | Generate a new nonce for every retry |\n\nSource: https://railcore.tech/docs/hmac\nLast updated: 12 Nov 2026\n"},{"id":"webhooks","title":"Webhooks","description":"Receive RailCore Indian Railways API job results by webhook: the callback URL rules, the signed POST, how to verify its signature in Node.js, and retries.","group":"Core concepts","url":"https://railcore.tech/docs/webhooks","markdown_url":"https://railcore.tech/docs/webhooks.md","markdown":"# Webhooks\n\nSigned callbacks when an async job ends.\n\nWhat a webhook is for\n\nRoute-scan and hopping jobs run in the background. Instead of polling `GET /v1/jobs/{job_id}`, give a `callback_url` when you submit the job, and RailCore POSTs the outcome to it once the job ends.\n\n## Ask for a callback\n\nAdd callback_url to the body of POST /v1/jobs/route-scan or POST /v1/jobs/hopping.\n\ncURL\n\n```\nRUN_DATE=$(TZ=Asia/Kolkata date +%F)\n\ncurl -sS -X POST \\\n  -H \"X-RailCore-Key: $RAILCORE_KEY\" \\\n  -H \"Content-Type: application/json\" \\\n  --data '{\"from\":\"BSL\",\"to\":\"ADI\",\"date\":\"'\"$RUN_DATE\"'\",\"callback_url\":\"https://hooks.example.com/railcore\"}' \\\n  \"https://ir.railcore.tech/v1/jobs/route-scan\"\n```\n\nThe 202 answer carries `webhook_secret`. It is shown once and RailCore does not store it: save it with the `job_id`. It is the key that signs this job's callbacks.\n\nJSON\n\n```\n{\n  \"success\": true,\n  \"data\": {\n    \"job_id\": \"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"status\": \"processing\",\n    \"poll_url\": \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\n    \"stream_url\": \"/v1/jobs/job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8/stream\",\n    \"message\": \"Route scan submitted. Poll the poll_url for results.\",\n    \"webhook_secret\": \"whsec_...\"\n  }\n}\n```\n\n## The callback URL\n\n- An `https` URL on a public host, on port 443 or a port from 1024 up.\n- No user name or password in the URL.\n- Not localhost, and not a private, link-local, CGNAT (100.64.0.0/10) or cloud metadata address.\n- Checked when the job is submitted: a URL that breaks a rule answers `400 VALIDATION_ERROR` with `details[].field` `callback_url`, and is not counted. Checked again just before each send, after the host name is resolved, so a name that later points at a private address is not called.\n- Redirects are not followed. A 3xx answer is final.\n\n## What RailCore sends\n\nOne POST with a JSON body when the job ends.\n\nHTTP\n\n```\nPOST /railcore HTTP/1.1\nContent-Type: application/json\nX-RailCore-Webhook-Id: job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\nX-RailCore-Webhook-Timestamp: 1785472200\nX-RailCore-Webhook-Attempt: 1\nX-RailCore-Webhook-Signature: v1=5f2b...e91c\n\n{\"job_id\":\"job_01J5Z7Y8N2K4M6P8R0T2V4X6Z8\",\"status\":\"complete\",\"result\":{ ... }}\n```\n\n- The body is `{ \"job_id\", \"status\": \"complete\", \"result\" }`, where `result` is what polling the job returns, or `{ \"job_id\", \"status\": \"failed\", \"error\" }`.\n- `X-RailCore-Webhook-Id` is the job id. `X-RailCore-Webhook-Timestamp` is when this send was signed, in Unix seconds. `X-RailCore-Webhook-Attempt` is which send it is, 1 to 4.\n- `X-RailCore-Webhook-Signature` is `v1=` and the lower-case hex HMAC-SHA256 of the timestamp, a period and the raw body (`<timestamp>.<raw body>`), keyed with the job's `webhook_secret`.\n\n## Check the signature\n\nCheck every callback before you trust it. Sign the raw bytes you received: parsing the JSON and serializing it again changes them.\n\nNode.js\n\n```\nimport crypto from \"node:crypto\";\n\nconst TOLERANCE_SECONDS = 5 * 60;\n\n/**\n * rawBody: the body exactly as received, as a Buffer, before JSON.parse.\n * headers: Node's lower-cased request headers.\n * secret: the webhook_secret from the job's 202 answer.\n */\nexport function verifyRailCoreWebhook(rawBody, headers, secret) {\n  const timestamp = headers[\"x-railcore-webhook-timestamp\"] ?? \"\";\n  const signature = headers[\"x-railcore-webhook-signature\"] ?? \"\";\n  if (!/^\\d+$/.test(timestamp)) return false;\n  // Refuse a send signed more than 5 minutes ago: a replay of an old callback.\n  const age = Math.floor(Date.now() / 1000) - Number(timestamp);\n  if (Math.abs(age) > TOLERANCE_SECONDS) return false;\n\n  const expected = \"v1=\" + crypto\n    .createHmac(\"sha256\", secret)\n    .update(`${timestamp}.`)\n    .update(rawBody)\n    .digest(\"hex\");\n  const given = Buffer.from(signature);\n  const wanted = Buffer.from(expected);\n  // Constant-time: never compare signatures with === or ==.\n  return given.length === wanted.length && crypto.timingSafeEqual(given, wanted);\n}\n```\n\nA receiving server built on `node:http`:\n\nNode.js\n\n```\nimport http from \"node:http\";\n\nhttp.createServer((req, res) => {\n  const chunks = [];\n  req.on(\"data\", (chunk) => chunks.push(chunk));\n  req.on(\"end\", () => {\n    const rawBody = Buffer.concat(chunks);\n    const jobId = req.headers[\"x-railcore-webhook-id\"];\n    const secret = webhookSecrets.get(jobId); // saved from the 202 answer\n    if (!secret || !verifyRailCoreWebhook(rawBody, req.headers, secret)) {\n      res.writeHead(401).end();\n      return;\n    }\n    const event = JSON.parse(rawBody.toString(\"utf8\"));\n    // event.status is \"complete\" with event.result, or \"failed\" with event.error.\n    // A send can arrive twice (your 2xx was lost): act on each job_id once.\n    res.writeHead(204).end();\n  });\n}).listen(8443);\n```\n\n## Answers and retries\n\n- Answer with any 2xx within 5 seconds. The callback is then settled as sent.\n- After a 5xx, 408 or 429, a timeout or a dropped connection, RailCore sends it again, 3 more times, after 2, 8 and 30 seconds. Each send is signed afresh, with its own timestamp.\n- Any other answer, a 4xx or a 3xx, is final: the callback is settled as failed and not sent again.\n- A send can reach you twice when your answer is lost on the way back. Use the job id to act on each job once.\n\n## Delivery status on the job\n\nGET /v1/jobs/{job_id} and GET /v1/jobs show how the callback went.\n\n| callback_status | Meaning |\n| --- | --- |\n| `not_configured` | The job was submitted without a callback_url. |\n| `pending` | The callback is not settled yet. RailCore saves the job's result before it sends the callback, so a poll can show the result while this is still pending. |\n| `sent` | Your endpoint answered 2xx. |\n| `failed` | Every send failed, an answer was final, or the address was refused when it was resolved. |\n\n`callback_attempts`, present once the callback is settled, says how many sends were made: 0 to 4.\n\nKeep the secret on your server\n\nA webhook secret is a server credential, like the HMAC signing secret. Anyone who has it can forge callbacks for that job.\n\nSource: https://railcore.tech/docs/webhooks\nLast updated: 12 Nov 2026\n"},{"id":"errors-reference","title":"Error code catalog","description":"Every public RailCore Indian Railways API error code in one table, with its HTTP status, meaning and whether the request is safe to retry.","group":"Resources","url":"https://railcore.tech/docs/errors-reference","markdown_url":"https://railcore.tech/docs/errors-reference.md","markdown":"# Error code catalog\n\nEvery public error code in one table.\n\nBranch on code\n\nMessages can improve without a version change. The code is the stable contract.\n\n43 codes\n\n| HTTP | Code | Retry | Meaning and fix |\n| --- | --- | --- | --- |\n| 400 | `INVALID_INPUT` | No | Generic schema or input validation failure. Fix: Read error.message, correct the value it names and send the request again. On a seat enquiry it can also mean the train does not serve that journey: check that it stops at both stations. |\n| 400 | `VALIDATION_ERROR` | No | A request field is missing or invalid. The message names it, and error.details[].field names the parameter (date, items[2].date, match, callback_url). Fix: Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted. |\n| 400 | `INVALID_STATION_CODE` | No | Station code format or reference validation failed. Fix: Send a station code of 1 to 6 letters or digits, such as NDLS, or J for Jalna. Look a code up with GET /stations/search. |\n| 400 | `INVALID_TRAIN_NUMBER` | No | Train number format validation failed. Fix: Send the train number as 4 to 6 digits or capital letters, such as 12951. Find a number with GET /trains/search. |\n| 400 | `INVALID_DATE` | No | Date format or allowed window validation failed. Fix: Send the date as YYYY-MM-DD in India time (IST), inside the window the endpoint's page gives. |\n| 400 | `INVALID_QUOTA` | No | Unknown quota code. Fix: Use a quota code the endpoint's page lists, such as GN or TQ. |\n| 400 | `INVALID_CLASS_CODE` | No | Unknown class code. Fix: Use a class code the endpoint's page lists, such as SL, 3A or 2A. |\n| 401 | `MISSING_API_KEY` | No | No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short. Fix: Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard. |\n| 401 | `AMBIGUOUS_API_KEY` | No | More than one key header was sent, with different keys. Send the key in one header. Fix: Send the key in one header only, or make every key header carry the same key. |\n| 401 | `INVALID_API_KEY` | No | The credential is unknown or revoked. Fix: Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard. |\n| 401 | `API_KEY_DISABLED` | No | The credential was disabled by policy or an operator. Fix: Use another active key from the developer dashboard, or contact support to find out why this one was disabled. |\n| 401 | `API_KEY_EXPIRED` | No | Credential expiry has passed. Fix: Create or rotate a key in the developer dashboard and update your configuration with the new one. |\n| 401 | `SIGNATURE_INVALID` | No | HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated. Fix: Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one. |\n| 401 | `TIMESTAMP_EXPIRED` | No | Signed timestamp is outside the five-minute window. Fix: Send the current Unix time in seconds in X-RailCore-Timestamp and keep your server clock in sync (NTP). It must be within five minutes of RailCore's clock. |\n| 401 | `NONCE_REUSED` | No | The signed nonce already appeared in the replay window. Fix: Generate a new random nonce of 16 to 128 characters for every request, retries included. |\n| 401 | `PLAYGROUND_TOKEN_EXPIRED` | No | A docs playground token has expired or is not valid. They last 15 minutes; the playground gets a new one by itself. Fix: Get a new playground token: the docs console does this by itself, or sign in again. Tokens last 15 minutes. |\n| 403 | `IP_NOT_ALLOWED` | No | Caller IP is not in the key allowlist. Fix: Send requests from an address on the key's IP allowlist, or add this address to the allowlist in the developer dashboard. |\n| 403 | `SCOPE_MISSING` | No | The key lacks the operation scope. Fix: Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope. |\n| 403 | `PLAN_INACTIVE` | No | The subscription is paused, past due, or cancelled. Fix: Renew, resume or reactivate the subscription in the developer dashboard's billing section. Requests work again as soon as it is active. |\n| 403 | `PLAN_ENDPOINT_DISABLED` | No | The current plan does not include the endpoint. Fix: Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes. |\n| 402 | `CREDITS_EXHAUSTED` | No | The month's requests are used up, or too few are left for this request. Nothing is fetched. Fix: Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches. |\n| 429 | `RATE_LIMITED` | Yes | The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After. Fix: Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit. |\n| 429 | `JOB_LIMIT_EXCEEDED` | Yes | Five async jobs are already active on the account, across all of its keys. Fix: Wait for an active job to finish, or cancel one with DELETE /jobs/{job_id}, then submit again. An account can run five jobs at once. |\n| 404 | `TRAIN_NOT_FOUND` | No | No train has that number, on any /trains/{train_number}/ path but /live. The message names it: Train 99999 not found. Check the train number. Fix: Check the train number. Find the right one by name or number with GET /trains/search. |\n| 404 | `STATION_NOT_FOUND` | No | A station code or name could not be resolved. The message names it: Station ZZZZ not found. Check the station code. Fix: Check the station code. Find it by name with GET /stations/search. |\n| 404 | `COACH_POSITION_NOT_FOUND` | No | On /trains/{train_number}/coach-position: the train exists, but no source RailCore reads publishes its coach composition. The message names it: No coach composition is published for train 12345. Not counted. Fix: No source publishes this train's coach composition. Retrying soon will not help; try again on another day. |\n| 404 | `NO_TRAINS_FOUND` | No | No train matches the route and date. Fix: Try another date, nearby stations, or match=city to include every station in both cities. |\n| 404 | `NOT_FOUND` | No | Nothing matches the request: a train with no run on the date asked for on live train status, no fare for a fare estimate, or a path the API does not have. Fix: Nothing matches the request. Check the identifiers and the date (a train may not run that day), then ask again. |\n| 404 | `JOB_NOT_FOUND` | No | The async job does not exist or expired. Fix: Check the job ID. Jobs and their results expire, so submit the job again if it is gone. |\n| 409 | `CHART_NOT_PREPARED` | Yes | The chart is not ready yet. Fix: Ask again later: the chart is prepared a few hours before the train leaves. |\n| 422 | `TATKAL_NOT_OPEN` | No | Tatkal booking has not opened for the journey yet. error.opens_at (IST) says when, if known. Not counted. Fix: Ask again after the time in error.opens_at (IST). Tatkal opens the day before the train leaves its origin, at 10:00 for AC classes and 11:00 for the rest. |\n| 422 | `QUOTA_NOT_AVAILABLE` | No | The train does not offer that quota in that class for the journey. Not counted. Fix: Choose another quota or class: the train does not offer this quota in this class. |\n| 422 | `QUOTA_NOT_SUPPORTED` | No | Seat availability is not offered for that quota on any train: it answers GN, TQ, SS and LD only. Premium Tatkal (PT), HP, DP, HO, YU and FT can be checked on IRCTC. RailCore refuses it before the seat provider is asked. Not counted. Fix: Use GN, TQ, SS or LD. Other quotas, Premium Tatkal included, cannot be checked through RailCore; check them on IRCTC. |\n| 422 | `CLASS_NOT_AVAILABLE` | No | The train does not carry that class. error.message lists the classes it does. Not counted. Fix: Choose one of the classes the message lists for this train. |\n| 422 | `TRAIN_NOT_RUNNING` | No | The train does not leave the boarding station on that date. error.message lists the days it does. Not counted. Fix: Choose one of the days the message lists, or check the boarding station. |\n| 422 | `BOOKING_NOT_OPEN` | No | The date has not opened for booking: reservations open 60 days before the journey, at 8:00 AM in India. RailCore refuses it before the seat provider is asked. error.message names the day it opens. Not counted. Fix: Choose a date inside the booking window: reservations open 60 days before the journey, at 08:00 IST. |\n| 409 | `JOB_ALREADY_FINISHED` | No | The job is already terminal and cannot be cancelled. Fix: There is nothing to cancel. Read the job's result with GET /jobs/{job_id} instead. |\n| 410 | `API_VERSION_SUNSET` | No | The requested API major has reached its announced sunset date. Migrate to a supported version. Fix: Move to a supported API version. The changelog names the current one. |\n| 410 | `ENDPOINT_RETIRED` | No | The endpoint no longer answers API keys. The Link header and error.details name the endpoint to use instead. Fix: Use the endpoint the Link header and error.details name. For live train status that is GET /trains/{train_number}/live. |\n| 503 | `UPSTREAM_UNAVAILABLE` | Yes | Every live-data route for the request failed. Sent with Retry-After; not counted. Fix: Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted. |\n| 503 | `UPSTREAM_TIMEOUT` | Yes | The live-data source ran past its deadline. Sent with Retry-After; not counted. Fix: Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted. |\n| 500 | `INTERNAL` | Yes | Unexpected server error. Fix: Retry with backoff. If it keeps happening, contact support with the X-RailCore-Request-ID. |\n| 503 | `METERING_UNAVAILABLE` | Yes | The request could not be counted, so the data was withheld. Fix: Retry with backoff. The request was not counted and no data was sent. |\n\nSource: https://railcore.tech/docs/errors-reference\nLast updated: 19 Nov 2026\n"},{"id":"headers","title":"Header reference","description":"Reference for every RailCore Indian Railways API header: authentication and request headers, rate-limit and request counters, and the trace id for support.","group":"Resources","url":"https://railcore.tech/docs/headers","markdown_url":"https://railcore.tech/docs/headers.md","markdown":"# Header reference\n\nRequest, rate, credit, and trace headers.\n\n| Header | Direction | Meaning |\n| --- | --- | --- |\n| `X-RailCore-Key` | Request | The API key. Required, unless it is sent in Authorization or X-Api-Key instead |\n| `Authorization` | Request | Bearer \\<key>: the API key, as an alternative to X-RailCore-Key |\n| `X-Api-Key` | Request | The API key, as an alternative to X-RailCore-Key. Two key headers with different keys answer 401 AMBIGUOUS_API_KEY |\n| `X-RailCore-Timestamp` | Request | Unix seconds; required on Growth, Scale and Enterprise keys |\n| `X-RailCore-Nonce` | Request | Unique replay-protection token; required on Growth, Scale and Enterprise keys |\n| `X-RailCore-Signature` | Request | Base64 HMAC-SHA256 signature; required on Growth, Scale and Enterprise keys |\n| `X-RailCore-Request-ID` | Response | Support and request-log identifier |\n| `X-RailCore-Trace-ID` | Response | Distributed trace identifier |\n| `X-RailCore-Plan` | Response | Plan applied to the request |\n| `X-RailCore-RateLimit-Limit` | Response | The account's per-minute budget, shared by all its keys. Sent only when the plan has a per-minute limit. |\n| `X-RailCore-RateLimit-Remaining` | Response | Requests left in the account's current minute. Sent only when the plan has a per-minute limit. |\n| `X-RailCore-RateLimit-Reset` | Response | Minute reset Unix time. Sent only when the plan has a per-minute limit. |\n| `X-RailCore-RateLimit-Day-Limit` | Response | The account's daily request budget, per IST day. Sent only on keys with a daily cap (Free). |\n| `X-RailCore-RateLimit-Day-Remaining` | Response | Daily requests left. Sent only on keys with a daily cap (Free). |\n| `X-RailCore-RateLimit-Day-Reset` | Response | Daily reset Unix time. Sent only on keys with a daily cap (Free). |\n| `X-RailCore-Credits-Cost` | Response | What this request counted as (one credit is one request) |\n| `X-RailCore-Credits-Remaining` | Response | Requests left on the account |\n| `X-RailCore-Confidence` | Response | high, medium, or low live-data confidence. A finished run whose arrival at its last station was reported is high |\n| `Server-Timing` | Response | Where the request spent its time, in milliseconds: stages such as key, limits, credits and upstream in the order they ran, then total. Sent on every response |\n| `Retry-After` | Response | Seconds to wait before retrying a 429 or a 503 |\n| `Deprecation` | Response | When the path stopped answering API keys, as @ and Unix seconds (RFC 9745). Sent only with 410 ENDPOINT_RETIRED, from a retired path. |\n| `Sunset` | Response | The same moment as an HTTP date (RFC 8594). Sent only with 410 ENDPOINT_RETIRED, from a retired path. |\n| `Link` | Response | The path to use instead (rel=\"successor-version\") and the changelog entry (rel=\"deprecation\"). Sent only with 410 ENDPOINT_RETIRED, from a retired path. |\n| `X-RailCore-Webhook-Id` | Webhook | The job_id, on a job's callback to your callback_url |\n| `X-RailCore-Webhook-Timestamp` | Webhook | Unix seconds when this send was signed |\n| `X-RailCore-Webhook-Attempt` | Webhook | Which send this is, 1 to 4 |\n| `X-RailCore-Webhook-Signature` | Webhook | v1= and the hex HMAC-SHA256 of the timestamp, a period and the raw body, with the job's webhook_secret |\n\nRetired paths\n\nGET /v1/trains/{train_number}/live-status and /running were retired on November 3, 2026. They answer 410 ENDPOINT_RETIRED with Deprecation, Sunset and Link, and are not counted. Live train status at /v1/trains/{train_number}/live replaces both.\n\nWebhook headers\n\nThe four X-RailCore-Webhook-* headers come on the POST RailCore sends to a job's callback_url, not on API responses. [Webhooks](https://railcore.tech/docs/webhooks) shows how to check them.\n\nBrowser visibility\n\nServer clients receive every header. Browser JavaScript can read only CORS-exposed response headers.\n\nSource: https://railcore.tech/docs/headers\nLast updated: 20 Nov 2026\n"},{"id":"mcp","title":"Use RailCore in AI coding tools","description":"Connect Claude, Cursor, VS Code or any MCP client to the RailCore Indian Railways API docs: endpoints, code samples, error fixes and plans. No key needed.","group":"Resources","url":"https://railcore.tech/docs/mcp","markdown_url":"https://railcore.tech/docs/mcp.md","markdown":"# Use RailCore in AI coding tools\n\nConnect AI coding tools to these docs over MCP.\n\n## What it is\n\n**RailCore Developers** is an MCP server: it gives an AI assistant these docs, so it can answer from them while you code. Ask it how to make a request, why one failed or which plan fits, and it answers from the same endpoint pages, guides, error codes and plans you read here, with code samples in six languages.\n\nIt needs no sign-in and no API key. It answers from the docs and never sends a request to the API, so it spends none of your requests.\n\n## Server address\n\n`https://mcp.railcore.tech/developers/mcp`\n\nTransport: Streamable HTTP. No sign-in.\n\n## Claude Code\n\nRun this in a terminal:\n\nTerminal\n\n```\nclaude mcp add --transport http railcore-developers https://mcp.railcore.tech/developers/mcp\n```\n\nThat adds it for you, in the current project. Add `--scope user` before the name to have it in every project, or `--scope project` to save it in the project's `.mcp.json` for everyone who works on it.\n\n## Claude\n\nOn claude.ai and in Claude Desktop, add it as a custom connector:\n\n1. Open **Customize > Connectors**.\n2. Choose **+ Add**, then **Add custom connector**.\n3. Name it RailCore Developers and paste the server address.\n4. When asked how people connect, choose **No sign in**, then **Add**.\n\nA Free Claude plan can add one custom connector. On Team and Enterprise plans, an owner adds it for everyone under **Organization settings > Connectors**.\n\n## Cursor\n\n.cursor/mcp.json\n\n```\n{\n  \"mcpServers\": {\n    \"railcore-developers\": {\n      \"url\": \"https://mcp.railcore.tech/developers/mcp\"\n    }\n  }\n}\n```\n\nSave it as `.cursor/mcp.json` in your project, or as `~/.cursor/mcp.json` to have it in every project. If the file already lists servers, add `railcore-developers` beside them.\n\n## VS Code\n\n.mcp.json\n\n```\n{\n  \"mcpServers\": {\n    \"railcore-developers\": {\n      \"type\": \"http\",\n      \"url\": \"https://mcp.railcore.tech/developers/mcp\",\n      \"tools\": [\n        \"*\"\n      ]\n    }\n  }\n}\n```\n\nSave it as `.mcp.json` at the root of your workspace. Or run **MCP: Add Server** from the Command Palette, choose HTTP and paste the server address.\n\nA setup that keeps its servers in `.vscode/mcp.json` lists them under `servers`:\n\n.vscode/mcp.json\n\n```\n{\n  \"servers\": {\n    \"railcore-developers\": {\n      \"type\": \"http\",\n      \"url\": \"https://mcp.railcore.tech/developers/mcp\"\n    }\n  }\n}\n```\n\n## Any other MCP client\n\n| Setting | Value |\n| --- | --- |\n| Address | `https://mcp.railcore.tech/developers/mcp` |\n| Transport | Streamable HTTP |\n| Sign-in | None: no API key and no OAuth |\n| MCP version | 2026-07-28. Clients on the 2025 versions are served too. |\n\n## What it can answer\n\nYour assistant picks the tool. You can also name one in your question.\n\n| Tool | What it gives your assistant |\n| --- | --- |\n| `search_docs` | Searches the guides, the endpoint pages and the error codes, and returns the pages that match. |\n| `get_endpoint` | One endpoint in full: its parameters, what a request to it counts as, the scope its key needs, the plans that include it, whether it must be signed, and the errors it can answer. |\n| `get_code_sample` | A request to any endpoint in cURL, Node.js, Python, PHP, Go or Java. For a Growth, Scale or Enterprise key, the sample signs the request. |\n| `explain_error` | What an error code or an error response means, and how to fix it. It removes anything shaped like an API key from the text before reading it. |\n| `get_plans` | Every plan: its price, its monthly requests, its rate limits and what it includes. |\n\nAs resources, it offers the [OpenAPI document](https://railcore.tech/railcore-developer-api-v1.openapi.yaml), every guide and every endpoint page, for clients that let you attach one to a conversation. Clients that show prompts list three:\n\n| Prompt | Use it to |\n| --- | --- |\n| `integrate_endpoint` | Add one endpoint to your code. |\n| `debug_api_error` | Find out why a request failed and what to change. |\n| `choose_plan` | Pick a plan for what you are building. |\n\n## Things to ask\n\n- Write a Python function that gets the live running status of train 12951 from RailCore.\n- My RailCore request answers 401 SIGNATURE_INVALID. What is wrong with my signing code?\n- Which RailCore plan fits about 20,000 requests a month, and does it need signed requests?\n\nIt reads the docs, not the API\n\nThe server cannot see your account or your keys. Code it writes runs with your own key, and its requests are counted like any other.\n\n## Privacy and limits\n\n- Keep your API key and signing secret out of the chat: the server never needs them. If a key ends up in an error you ask about, `explain_error` removes it before reading the error.\n- Each time your assistant uses a tool, the server records the tool's name, your client's name and version, how long the answer took, and your IP address, for rate limiting.\n- Each IP address has a rate limit. If your assistant reaches it, wait a little and ask again.\n- It reads the docs from the [docs catalog](https://railcore.tech/docs/mcp-catalog.json) every 10 minutes, so for a few minutes after the docs change it can still give the earlier answer.\n\nSource: https://railcore.tech/docs/mcp\nLast updated: 20 Nov 2026\n"},{"id":"changelog","title":"Changelog","description":"Release history for the RailCore Indian Railways API and its documentation: new endpoints, response changes and deprecations, newest first.","group":"Resources","url":"https://railcore.tech/docs/changelog","markdown_url":"https://railcore.tech/docs/changelog.md","markdown":"# Changelog\n\nAPI and documentation release history.\n\nLatest release\n\nNovember 20, 2026: the RailCore Developers MCP server brings these docs into Claude, Cursor, VS Code and other AI coding tools. [Add it to yours](https://railcore.tech/docs/mcp). The latest change to the API itself, November 19, 2026: seat availability answers the General, Tatkal, Lower berth / senior citizen and Ladies quotas. Any other quota, Premium Tatkal included, is refused with `422 QUOTA_NOT_SUPPORTED` before the seat provider is asked, and is not counted.\n\n## November 20, 2026: An MCP server for AI coding tools\n\n- The RailCore Developers MCP server, at `https://mcp.railcore.tech/developers/mcp`, gives an AI assistant these docs. It searches the guides, endpoint pages and error codes; gives an endpoint's parameters, what a request to it counts as, its scope, plans and errors; writes requests in cURL, Node.js, Python, PHP, Go and Java, signed for Growth, Scale and Enterprise keys; explains an error and how to fix it; and lists the plans.\n- It needs no sign-in and no API key. It answers from the docs and sends no request to the API, so it spends none of your requests.\n- [Use RailCore in AI coding tools](https://railcore.tech/docs/mcp) shows how to add it to Claude Code, Claude, Cursor, VS Code or any other MCP client.\n- The API itself did not change.\n\n## November 19, 2026: Seat availability names the quotas it answers\n\n- `GET /v1/availability/seats`, `POST /v1/availability/seats/batch` and `GET /v1/availability/calendar` answer `GN` (General), `TQ` (Tatkal), `SS` (Lower berth / senior citizen) and `LD` (Ladies). Any other quota (`PT`, `HP`, `DP`, `HO`, `YU`, `FT`) is refused with `422 QUOTA_NOT_SUPPORTED`, not retryable, before the seat provider is asked, and is not counted. The message names the quota and says to check it on IRCTC.\n- Those quotas answered `422 QUOTA_NOT_AVAILABLE`, \"This train does not offer this quota in this class\", for every train. That was not about the train: RailCore's seat source cannot check these quotas on any train, including trains that do sell Premium Tatkal.\n- Batch: an item with such a quota is not asked and not counted, and comes back in its place as a failed item with `error: \"QUOTA_NOT_SUPPORTED\"`. When no item names a quota the API answers, the whole request answers 422.\n- Calendar: a Premium Tatkal calendar answered 200 with an empty `days` list, and was counted. It now answers `422 QUOTA_NOT_SUPPORTED`, not counted.\n- `QUOTA_NOT_AVAILABLE` keeps its meaning for the four quotas above: the train does not offer that quota in that class for the journey.\n- Trains between stations and fares: `availability_summary` on `GET /v1/routes/trains`, and fares on `GET /v1/fares/estimate` and `GET /v1/fares/search`, are given for `GN` and `TQ`. With any other quota the routes answer lists the trains without availability, the estimate answers `404 NOT_FOUND`, and the fare search lists trains without fares. Their answers did not change; the reference now says so, and the request console offers `GN` and `TQ` there.\n\nCheck your integration\n\nIf you send `quota=PT` (or `HP`, `DP`, `HO`, `YU`, `FT`) to seat availability, handle `422 QUOTA_NOT_SUPPORTED`: a retry, another date or another train will not change it. Show your users that the quota is checked on IRCTC instead of reading it as the train having no seats in that quota.\n\n## November 13, 2026: Free plan: 500 requests a month, 10 a minute, 100 a day\n\n- The Free plan includes 500 requests a month (it was 2,000), 10 a minute (was 20) and 100 a day (was 300). It still covers every core endpoint except PNR.\n- The daily limit keeps a loop that goes wrong from spending the whole month in one afternoon. Once the day's 100 are used, requests answer `429 RATE_LIMITED` until the next IST day, and the rest of the month's requests stay for the days after.\n- A Free account keeps what is left of its current month. Its next monthly refill, on the day of the month its plan started, is 500. A Free account opened from today starts with 500. The new per-minute and daily limits apply to every Free key from this release.\n- Failed requests are still not counted, and Starter, Growth, Scale and Enterprise are unchanged. Nothing about the endpoints or their answers changed in this release.\n\nCheck your integration\n\nOn Free, a key that has used the month's requests is refused with `402 CREDITS_EXHAUSTED` until its next refill, and one that has used the day's with `429 RATE_LIMITED` until the next IST day. `X-RailCore-Credits-Remaining` and `X-RailCore-RateLimit-Day-Remaining` show what is left. Keep to 10 requests a minute, and honor `Retry-After`. If you need more, [Starter](https://railcore.tech/pricing) includes 40,000 requests a month with no daily cap.\n\n## November 13, 2026: Live speed is an estimate that moves\n\n- `GET /v1/trains/{train_number}/live`: `speed_kmph` is RailCore's estimate of the speed where the train was last reported, from its coaches and type, the timetable and how it has run. It is never above what the train may run at (130 km/h on LHB coaches, 110 on ICF), and lower as the train leaves a halt or nears the next. The average from the last timed station it replaces could read over 150 km/h.\n- The estimate is rounded to 5 km/h, and `speed_kmph` moves within 5 km/h of it every 2 seconds, the same for every caller at the same moment, as a moving train's speed does. It is still an estimate: label it as one.\n- `speed_basis` is `estimated` while the train runs (it was `average_since_last_report`), `stationary` for 0 and `unavailable` when the report is too old to place the train. A train running through a station it does not stop at is no longer read as standing there.\n\n## November 12, 2026: Station board window, match by station, signed webhooks\n\n- `GET /v1/stations/{station_code}/live` lists a train only when its expected or booked time at the station, arriving or leaving, falls between 2 hours ago and `window_hours` ahead (4 or 8; any other value reads as 8). The new `window` object gives `from` and `to` as India-time instants (`+05:30`), with `hours_back` and `hours_ahead`. A departure that crosses midnight is dated the next day. A field with no value is left out, never `null`: `source_station_code`, `source_station_name`, `current_station_code`, `cancellation.to_station_code` and the rest.\n- Station board: in place of a field with no value, each train carries `notes`, which says why. Time fields still hold only real times. The keys are `arrival` (`Starts at New Delhi: departs only, no arrival`), `departure` (`Ends at New Delhi: arrives only, no departure`), `halt` (`Starts at New Delhi: no halt`, `Has not stopped here yet`), `platform` (`Platform not announced yet`), `last_reported` (`Not reported yet`), `position` (`Not started yet: at its first station, New Delhi`), `expected` and `rescheduled`. `notes` is present only when it has at least one entry.\n- Station board: a platform the board does not name yet is filled from the railway's running status of the run, when RailCore already holds it (`platform_basis: \"expected\"`), or else the train's usual platform from the timetable (`\"usual\"`, not confirmed for today); a platform on the board is `\"announced\"`. On 12 November all 12 NDLS trains without a platform had one this way. A train that has started gets its `last_reported_at` from the same running status; one that has not started has none anywhere.\n- Station board: a train with no live forecast yet shows its booked times as the expected ones, with a delay of 0 and the new `timing_basis: \"scheduled\"`; a forecast from the live feed is `timing_basis: \"live\"`. A train that has not started and has no position stands at its first station: `current_station_code` is that station and `departed_current_station` is `false`.\n- Station board: a train the railway moved before it starts carries `rescheduled_minutes` (15 or more) and `notes.rescheduled`, and its delay counts from the new time. 22362 at New Delhi was booked to leave at 19:10 and expected at 01:30 the next day, with a delay of 0: `rescheduled_minutes: 380`, `Rescheduled by 6 h 20 min: now departs at 01:30 on 13 Nov`. It read as on time.\n- Station board: RailCore's train catalog wins over the live feed for a train it lists. The first and last stations come from the catalog, and so do `train_name` and `extended_train_name` when the feed named other ends: the feeds reuse numbers for other local trains, and 64034 was shown as `SHAKURBASTI - GHAZIABAD Local` where the catalog's 64034 is the `Shamli - Delhi MEMU`, SMQL to DLI. A train the catalog does not list is left as the feed gives it.\n- `GET /v1/routes/trains` and `GET /v1/journeys/search` take `match`. `city`, the default and the behaviour until now, lists trains between every station of the two cities, so a search from MMCT to NDLS also lists trains from BDTS to NZM. `station` lists only trains between the two stations asked for, and answers `404 NO_TRAINS_FOUND`, not counted, when there are none. Every answer, and every result of `POST /v1/journeys/compare`, carries `matched_by`: `station` or `city`. Each train's `from_station_code`, `from_station_name`, `to_station_code` and `to_station_name` say where it is boarded and left; they were sent but not documented.\n- Also documented for the first time: `from_station_code`, `to_station_code`, `journey_date` and `quota` on `GET /v1/fares/search`, and `enriched` on `GET /v1/stations/search`.\n- A 404 names what it could not find: `STATION_NOT_FOUND` says `Station ZZZZ not found. Check the station code.` An unknown train on any `/v1/trains/{train_number}/…` path but `/live` answers `TRAIN_NOT_FOUND`, `Train 99999 not found. Check the train number.`, where some answered a bare `NOT_FOUND`. On a `400 VALIDATION_ERROR`, `details[].field` names the parameter (`date`, `items[2].date`, `match`, `callback_url`); it said `custom`.\n- `GET /v1/trains/{train_number}/live`: `date` is optional. Without it the answer is for the run on its way now (one that has left its first station and is not more than 3 hours past its booked arrival; with two on the way, the one that left most recently), or else the next run to leave. `journey_date` says which. A finished run whose arrival at its last station was reported has `confidence: \"high\"`, in the body and in `X-RailCore-Confidence`.\n- Live train status: the first station has no `scheduled_arrival`, `eta`, `delay_arrival_minutes` or `actual_arrival`, and the last station no `scheduled_departure`, `etd`, `delay_departure_minutes` or `actual_departure`; `stop_type` (`ORIGIN`, `DESTINATION`) says why, and so does the station's `notes`: `notes.arrival` at the first station, `notes.departure` at the last. Each was a copy of the station's other time. `stations[].station_name`, `current_station_name`, `approaching_station_name` and `previous_station_name` are written as the RailCore site writes them (`New Delhi`, `Mumbai Central`), not as upper-case booking names.\n- `/schedule`, `/stops` and `/route`: the same rule. The `ORIGIN` stop has no `arrival_time` and the `DESTINATION` stop no `departure_time`, and each carries `notes` saying why; from November 12, 2026 they copied the other time. Station names are in the site's casing. A halt's `distance_km` is the railway timetable's whole kilometres; a passing station's is worked out to 0.1 km.\n- Seat availability, batch and calendar: a `REGRET` class's `confirmation_probability.text` reads `Waitlist full (regret)`, where it read `Booking closed` or `No more booking`: regret means the waitlist is full, not that booking has closed. `wl_pool` and `wl_pool_position` are now filled on batch and calendar answers too, whenever the availability text names a pool (`GNWL276/WL185` gives `GNWL` and 276).\n- A seat enquiry for a date past the booking window (reservations open 60 days before the journey, at 8:00 AM in India; the foreign tourist quota `FT` is exempt) is refused with `422 BOOKING_NOT_OPEN` before the seat provider is asked, and is not counted. A single-seat enquiry for a day the train does not leave the boarding station is refused with `422 TRAIN_NOT_RUNNING` the same way. On the calendar, a start date past the window is `422 BOOKING_NOT_OPEN`, and a window that runs past the last open date stops at it. In a batch, items past the window are not asked and not counted: each comes back in its place as a failed item with `error: \"BOOKING_NOT_OPEN\"`, and when every item is past the window the whole request answers 422.\n- `GET /v1/trains/{train_number}/coach-position`: power cars (`LPR`, `EOG`) are listed in their places, with `coach_type: \"POWER_CAR\"` and `class_name` `Power car` or `Generator car`. They were left out, which left a gap in `position_from_engine`. New `power_cars` counts them and `total_vehicles` counts every row, locomotives included; `total_coaches` counts neither.\n- `GET /v1/fares/unreserved`: `routes[].fare` is a number of rupees, where it was a string such as `\"15.00\"`. New `from_station_code` and `to_station_code`. `from` and `to` are still sent, but are deprecated and will be removed in a later release.\n- `X-RailCore-RateLimit-Limit`, `-Remaining` and `-Reset` are sent only when the plan has a per-minute limit. A plan without one (Enterprise), and a request refused before the key was read (a bad request, a missing or wrong key), no longer gets `0`, `0` and `0`, which read like a block. The `X-RailCore-RateLimit-Day-*` headers are unchanged.\n- `POST /v1/jobs/route-scan` and `POST /v1/jobs/hopping`: a `callback_url` must be an `https` URL on a public host (port 443 or 1024 and up, no user name or password, not a localhost, private, link-local, CGNAT or metadata address). It is checked when the job is submitted (`400 VALIDATION_ERROR`, field `callback_url`) and again after the host is resolved, before each send. Redirects are not followed.\n- Job callbacks are signed. The 202 answer carries `webhook_secret` (`whsec_…`), shown once. Each callback is a POST of `{ job_id, status, result }` or `{ job_id, status, error }` with `X-RailCore-Webhook-Id`, `-Timestamp`, `-Attempt` and `-Signature: v1=<hex>`, the HMAC-SHA256 of `<timestamp>.<raw body>`. After a 5xx, 408, 429, timeout or dropped connection it is sent 3 more times, after 2, 8 and 30 seconds. The job's `callback_status` is `pending` until the callback is settled, then `sent` or `failed`, and `callback_attempts` counts the sends. [Webhooks](https://railcore.tech/docs/webhooks) shows how to check a signature.\n\nCheck your integration\n\nRead `window` on the station board, and expect trains up to 2 hours old on it. When a field is missing, read `notes` for why before treating it as an error. Check `timing_basis` before showing an expected time as a forecast: `scheduled` means it is the booked time. Show `rescheduled_minutes` as a new departure time, not as a delay. If you need only trains between the two stations you asked for, send `match=station` and handle its 404. Treat a missing arrival at the first station and a missing departure at the last as \"none\", on live train status and on schedules. Parse `routes[].fare` on unreserved fares as a number, and move from `from` and `to` to `from_station_code` and `to_station_code`. Read the per-minute rate-limit headers only when they are present. If you use job callbacks, save `webhook_secret` and check the signature of every callback.\n\n## November 12, 2026: Push-pull trains on coach position\n\n- `GET /v1/trains/{train_number}/coach-position`: a push-pull train has a locomotive at each end, and the answer now shows it. `push_pull` is `true`, `locomotives` is 2, the `formation` ends with `ENG`, and the list closes with a second locomotive row. Every locomotive row carries `locomotive_end`: `FRONT` or `REAR`.\n- Indian Railways publishes no list of push-pull trains, so RailCore marks one on evidence and says which in `push_pull_basis`: `train_design` (an Amrit Bharat Express, built as a push-pull rake), `railway_announcement` (the railway announced it for that train) or `rake_composition` (the train's coach composition, refreshed every 15 minutes, lists a locomotive at each end).\n- Every other train answers `push_pull: false` and `locomotives: 1` (0 for a self-propelled set). `total_coaches` still counts coaches only.\n\n## November 12, 2026: No nulls on schedules, coach position and live trains\n\n- `/schedule`, `/stops` and `/route`: every stop has a `stop_type` (`ORIGIN`, `HALT`, `PASSING` or `DESTINATION`). The first station's `arrival_time` is its departure time and the last station's `departure_time` is its arrival time; both were `null`.\n- The same three endpoints leave out a field the timetable has no value for. A station the train runs through has no `platform_number` and no typical delay, so those fields are absent there, where they were `null` (803 nulls on one train's full route).\n- `GET /v1/trains/{train_number}/coach-position`: the locomotive is the first row of every loco-hauled train, and the coaches count from 2. Trains whose coach list the railway numbers from 1, such as 12656, came back with no locomotive. A self-propelled set (Vande Bharat, MEMU) still has none.\n- Coach position also carries `train_name`, `train_type`, `source_station` and `destination_station` with their names, `rake_type`, `total_coaches`, the `formation` written out (`ENG-SLRD-GEN-S5-…`), `class_summary` (the rake counted by class, the locomotive first) and `reversal_stations`. Every row has a `class_name` and a `coach_type`.\n- `GET /v1/trains/{train_number}/live`: every station has an `eta`, an `etd` and both delays. The live feed times halts only, so the stations a train runs through carried `null`; RailCore now works their times out from the delay at the timed stations either side. The new `timing_basis` says which each is: `reported`, `predicted`, `estimated` or `scheduled`.\n- Live train status has no `null` left anywhere. A field with nothing to report is left out: `actual_arrival` before the train has been reported at a station, `platform_number` where none is named, `last_reported_at` before a run starts, `official_notice` when the railway reports nothing. The first station's arrival is its departure, and the last station's departure is its arrival.\n\nCheck your integration\n\nOn these five endpoints a field that was `null` is now either filled or absent. If your code tests `field === null`, test for a missing field as well (`field == null` in JavaScript covers both). On coach position, `position_from_engine` of a train that had no locomotive row moves up by one, and `sequence` is now the row number. On live train status, an `eta` marked `estimated` is RailCore's calculation, not a report.\n\n## November 12, 2026: A reason with every refusal\n\n- `GET /v1/routes/trains` and `GET /v1/journeys/search` answer `404 NO_TRAINS_FOUND`, not counted, when no train is found between the two stations: no through train, or a station code that does not exist. They answered 200 with an empty `trains` list, and the request was counted. On `POST /v1/journeys/compare` such a route is an inline `error: \"NO_TRAINS_FOUND\"`.\n- `GET /v1/availability/seats`: an enquiry that could never succeed says why. `422 CLASS_NOT_AVAILABLE` lists the classes the train carries, `422 TRAIN_NOT_RUNNING` lists the days it runs from the boarding station, and `422 BOOKING_NOT_OPEN` says the date has not opened for booking yet and names the day it does (a date opens 60 days ahead, at 8:00 AM in India). They answered a retryable 503, or \"does not serve the selected journey\". None is counted.\n- `POST /v1/availability/seats/batch`: an item that names no classes is checked, and counted, in the classes its train carries. It was always checked in SL, 3A, 2A and 1A, so an item for a Shatabdi failed and counted four.\n- `GET /v1/fares/unreserved`: with no `date` the fare is for today in India. It was for tomorrow, which suburban sections do not quote, so Mumbai, Kolkata and Chennai suburban pairs failed by default. The same station as `from` and `to` answers `400 VALIDATION_ERROR`.\n- `GET /v1/availability/calendar`: each day carries `catering_charge` and `total_fare`. `fare` leaves compulsory catering out, so a Rajdhani day read 2765 where the ticket costs 3165.\n- `GET /v1/stations/{station_code}/live`: each train carries `extended_train_name`, its full name, and its first and last stations are named in full (`Chhatrapati Shivaji Maharaj Terminus`, not `C SHIVAJI MAH T`).\n- `/schedule`, `/stops` and `/route` answer `404 TRAIN_NOT_FOUND` for the numbers `00000` to `00009`, which a schedule source uses for test entries.\n- Enterprise: a request counts as it does on every other plan. A seat enquiry, a live train or a route search counted as 5 requests, a station board or an availability calendar as 4, a fare as 3 and a schedule as 2; each now counts as 1. Vacant berths, hopping and route scan count as 3, 4 and 8, where they counted as 8, 10 and 25. Your balance keeps its number, so it covers more requests than it did.\n\nCheck your integration\n\nA route search with no train is now a 404: handle `NO_TRAINS_FOUND` where you handled an empty list. If you call unreserved fares without `date` and want tomorrow's fare, send the date. Treat `CLASS_NOT_AVAILABLE`, `TRAIN_NOT_RUNNING` and `BOOKING_NOT_OPEN` as final: do not retry them.\n\n## November 11, 2026: Clearer errors, and 404 where nothing was found\n\n- A journey date that has passed in India answers `400 VALIDATION_ERROR` on trains between stations, journey search, seat availability, available classes and fare search. It answered `503 UPSTREAM_UNAVAILABLE`, which told clients to retry a request that could never succeed.\n- `GET /v1/routes/trains` and `GET /v1/fares/search` without `date`, and `GET /v1/availability/classes` without `train_number` or `date`, answer `400 VALIDATION_ERROR` naming the parameter. They answered a 400 that did not say which one. One-letter station codes such as `J` (Jalna) are accepted on trains between stations.\n- `GET /v1/trains/{train_number}/coach-position` answers `404 TRAIN_NOT_FOUND` at once for a number RailCore does not list. It waited five seconds and answered 503.\n- `GET /v1/stations/{station_code}/live` answers `404 STATION_NOT_FOUND` for a code no station has, and `GET /v1/availability/calendar` answers `404 TRAIN_NOT_FOUND` for an unlisted train. Both answered 200 with nothing in it, and the request was counted.\n- `GET /v1/fares/estimate`: `class` now narrows the answer to that class; it was checked and then ignored. When there is no fare for the train, journey, class and quota the request answers `404 NOT_FOUND` and is not counted. It answered 200 with an empty `fares` list.\n- `GET /v1/trains/{train_number}/live`: a run that has finished carries `distance_km`, `day`, `halt_minutes`, `latitude` and `longitude` on every station, as a running one does; they were `null`. `freshness.upstream_served_from_cache` is left out unless the live feed says; it was always `null`. A 404 now says that no run was found for that date.\n- `GET /v1/stations/{station_code}/live`: every train's `cancellation` is an object with `status`, `fully_cancelled` and `message`, as on live train status. It was `null` when nothing was cancelled.\n- `/schedule`, `/stops` and `/route`: `valid_from` and `valid_to` are present only when the railway dated the timetable. `valid_to` was `null` on almost every train.\n- `availability_summary[].last_updated_at` on trains between stations, journey search and compare carries its `+05:30` offset. It was the only instant in the API without one.\n\nCheck your integration\n\nIf your code reads a non-null `cancellation` on the station board as \"cancelled\", switch to `cancellation.status`. If it passes `class` to the fare estimate and expects every class back, drop `class`. Treat `valid_from`, `valid_to` and `freshness.upstream_served_from_cache` as optional, and handle 404 from coach position, the station board, the seat calendar and the fare estimate.\n\n## November 11, 2026: Fewer nulls across trains, journeys and seat availability\n\n- `GET /v1/trains/{train_number}/live`: `cancellation` is always an object. `cancellation.status` is `NOT_CANCELLED`, `PARTIALLY_CANCELLED` or `CANCELLED`, with the same in words in `cancellation.message`. It was `null` when nothing was cancelled.\n- `speed_kmph` is filled. The live feed carries no locomotive speed, so RailCore works out the average from the last station the train was timed at to its latest position; it reads 0 for a train that is standing. The new `speed_basis` says which. It was always `null`.\n- Every station has a `stop_type`: `ORIGIN`, `HALT`, `PASSING` or `DESTINATION`. A station the train has passed carries its actual times in `eta` and `etd`, and a passing station has its booked times in `scheduled_arrival` and `scheduled_departure`. The origin's arrival and the destination's departure stay `null`: they do not exist.\n- `train_type`, `train_type_label` and `travel_classes` come from RailCore's train catalog when the live feed leaves them out. `rescheduled_minutes` is 0, not `null`, for a start that was not moved.\n- `GET /v1/trains/{train_number}/coach-position`: a loco-hauled train's list starts with the locomotive (`coach_name: \"ENG\"`, `class_code: \"LOCO\"`, `position_from_engine: 1`). Every row has `is_locomotive`, and `has_locomotive` says whether the train has one.\n- `/schedule`, `/stops` and `/route`: `classes` lists the train's classes from the train catalog; it was an empty array. `/route` now carries `catering`, `pantry`, `rake_type` and each halt's platform and typical delays, as `/schedule` does.\n- `GET /v1/routes/trains`, `GET /v1/journeys/search` and `POST /v1/journeys/compare`: `extended_train_name` is the train's full name from RailCore's train catalog (`Navjeevan SF Express`, beside `train_name`'s `NAVJEEVAN SF EXP`). It was always `null`. `on_time_rating` is removed.\n- `GET /v1/availability/seats`, `POST /v1/availability/seats/batch` and `GET /v1/availability/calendar`: `confirmation_probability` is filled whenever the status settles it. An available class reads 100 with the text `Available`, and a class that cannot be booked reads 0 with the reason. It was `null` unless the class was waitlisted or RAC, and it stays `null` only when such a class has no forecast.\n- `wl_pool` and `wl_pool_position` are present only when the railway names the booking pool. They were `null` on every class with no pool to name.\n- `enquiry_checked_at`, `enquiry_completed_at` and `inventory_updated_at` are removed from seat availability. `classes[].last_updated_at` still says when each figure was read, and `meta.timestamp` when RailCore answered. `days[].alternate` is removed from the calendar: it was always `null`.\n- `fare_breakdown` has a new part, `rounding`. The railway charges a fare's parts rounded up to the next ₹5, and a fare with any rounding came back with no breakdown at all, about one in three. Every fare the railway itemises now has one, and its parts add up to `total_fare`.\n- The docs' request console has a calendar for date parameters. The box still takes a typed `YYYY-MM-DD`.\n\nCheck your integration\n\nIf your code reads a non-null `cancellation` as \"cancelled\", switch to `cancellation.status` or `cancellation.fully_cancelled`. If it draws coaches from `coach_position`, skip the row where `is_locomotive` is true, or draw it as the engine. Stop reading `on_time_rating`, `enquiry_checked_at`, `enquiry_completed_at`, `inventory_updated_at` and `days[].alternate`, and treat `wl_pool` and `wl_pool_position` as optional. If you show a forecast whenever `confirmation_probability` is not null, check `status` too: an available class now reads 100 and a closed one 0. If you add up `fare_breakdown` yourself, include `rounding`.\n\n## November 10, 2026: Redesigned documentation\n\n- The docs have a new layout. Guides and the API reference share one sidebar, every endpoint page shows its example request and response beside the reference, and search (Ctrl K, or ⌘K on a Mac) finds any page, endpoint or error code.\n- Request samples now come in PHP, Go and Java as well as cURL, Node.js and Python. A Key header switch writes every sample with `X-RailCore-Key`, `Authorization: Bearer` or `X-Api-Key`.\n- The [playground](https://railcore.tech/docs/playground) is now a request console. It shows the status, the request's own time, the size and what the request counted as, and it can draw a response (a live train along its route, a station board, a seat calendar) as well as show the JSON.\n- [Check a signature](https://railcore.tech/docs/hmac#check-a-signature), in the HMAC guide, builds the signing payload and the signature for any request in your browser, to compare with what your code produces.\n- Every page is also served as Markdown at its own address with `.md` added. Copy page, beside each title, copies it or opens it in ChatGPT, Claude, Perplexity or Gemini.\n- Every page says when it last changed.\n- Nothing about the API changed in this release.\n\n## November 7, 2026: Per-request pricing, 503 for upstream failures\n\n- Plans now count requests. A request to any core endpoint counts as 1: stations, trains, schedules, stops, routes, coach position, live station boards, live train status, trains between stations, journey search, seat availability, calendars, classes and fares.\n- Monthly requests: Free 2,000, Starter 40,000, Growth 1,50,000 and Scale 5,00,000 (Free became 500 on November 13, 2026). [Requests and billing](https://railcore.tech/docs/credits) lists prices and every cost.\n- Paid plans have no daily cap. Free accounts keep 300 requests a day (Free became 100 a day on November 13, 2026).\n- `POST /v1/availability/seats/batch` counts as 1 request per distinct class per item, minimum 1 request, with 4 classes counted for an item that leaves classes out. `POST /v1/journeys/compare` counts as 1 request per route compared, minimum 1 request.\n- Chart status counts as 1 request, vacant berths 3 requests, berth hopping 4 requests and a route scan 8 requests. Async jobs count the same at submission; polling, listing, streaming and cancelling count as 0 requests.\n- The headers keep their names: `X-RailCore-Credits-Cost` and `X-RailCore-Credits-Remaining` now count requests. One credit is one request.\n- Upstream failures answer `503` with a `Retry-After` header, where they answered 502 (`UPSTREAM_UNAVAILABLE`) and 504 (`UPSTREAM_TIMEOUT`). The RailCore error body, request ID and headers now always reach you. The codes are unchanged, and the request is not counted.\n- Rate limits are per account. The per-minute budget, the Free daily budget, and the caps on `/v1/charts/*` and seat batches are shared by every key on the account. A new key no longer starts with limits of its own.\n- The API takes the key in `X-RailCore-Key`, as `Authorization: Bearer`, or in `X-Api-Key`. Two headers with different keys answer `401 AMBIGUOUS_API_KEY`.\n- A signature's body hash is checked against the exact bytes you send, so indented JSON signs correctly. Before, only a compact body verified.\n- The docs playground works on every plan. Signed in, [Use my account](https://railcore.tech/docs/playground) runs requests as your account with a short-lived token and no signing.\n\nCheck your integration\n\nIf you retry on HTTP 502 or 504, retry on 503 as well, after the `Retry-After` seconds. Better, branch on `error.code`: `METERING_UNAVAILABLE` is also a 503.\n\n## November 7, 2026: Typical delay on train schedules\n\n- `stops[].arrival_delay_minutes` and `stops[].departure_delay_minutes` on `GET /v1/trains/{train_number}/schedule`, `/stops` and `/route` were described as live delay. They are a fixed typical-delay profile: the same on every date and every request.\n- New fields `typical_arrival_delay_minutes` and `typical_departure_delay_minutes` carry the same values under names that say what they are.\n- The old names are deprecated aliases with the same values. They stay until at least December 7, 2026, 30 days after this notice.\n\nMigration required\n\nRead `typical_arrival_delay_minutes` and `typical_departure_delay_minutes` instead of the old names before December 7, 2026. For how late a run is now, call [live train status](https://railcore.tech/docs/api/live-train).\n\n## November 3, 2026: Signed requests, fresh seat checks, seat calendar\n\n- Growth, Scale, and Enterprise keys must now sign every request with `X-RailCore-Timestamp`, `X-RailCore-Nonce` and `X-RailCore-Signature`. An unsigned request answers `401 SIGNATURE_INVALID` and says which headers to send. Free and Starter keys are unchanged.\n- New and rotated keys on those plans come with a one-time signing secret. A key issued before November 3, 2026 has none: rotate it in the dashboard to get one. Until then its requests are refused.\n- `GET /v1/availability/seats` asks afresh on every request, with no RailCore cache. The upstream can still answer with a figure it read earlier, so `inventory_updated_at` and `classes[].last_updated_at` now say when the figure was read; `enquiry_checked_at` says when RailCore asked.\n- `GET /v1/availability/calendar` returned no days. It now asks each date the train runs, from `date` (new, default today in India) for `days` days, and each day says when its figure was read. Dates the train does not run on are left out.\n- A bad `class` or `quota` on the seat, calendar and fare endpoints now answers `400 VALIDATION_ERROR` naming the parameter and the allowed codes, and costs nothing.\n\nAction required on Growth and above\n\nSign every request. If your key was issued before November 3, 2026, rotate it to get a signing secret first.\n\n## November 3, 2026: One live train endpoint\n\n- `GET /v1/trains/{train_number}/live` now returns full live status: where the train is, how late it is, and the scheduled, expected and actual times at every station on its route, including the ones it passes without stopping. It is still a `live:read` operation. It counted as five credits at the time, and counts as one request since November 7, 2026.\n- `date` is still required. `from` and `to` are now optional: RailCore uses the train's own first and last stations, so pass them only for a train missing from the train catalog.\n- Answers can be up to 10 seconds older than the live feed: RailCore may reuse its own read of the same run, and says so in `freshness.railcore_cache: reused` with that read's `retrieved_at`. Pass `max_age=0` for a fresh read. Every response now carries a `Server-Timing` header showing where its time went.\n- New fields: `source_station_code`, `destination_station_code`, `approaching_station_code` and `approaching_station_name`, `distance_from_current_station_km`, `distance_to_approaching_station_km`, `position_anchor_station_code`, `started_at`, `start_date`, `scheduled_duration_minutes`, `rescheduled_minutes`, `train_type`, `train_type_label` and `travel_classes`.\n- Removed fields: `current_station`, `previous_station`, `route_stations`, `position`, `route`, `geojson` and `geometry_accuracy`. Use `current_station_code`, `previous_station_code`, `latitude`, `longitude` and `stations[]` instead. `speed_kmph` stays but is always `null`.\n- In `freshness`, `fetched_at` is now `retrieved_at`, and `railcore_cache` and `upstream_served_from_cache` are new. `stations[]` and `next_stop` keep their fields.\n- `GET /v1/trains/{train_number}/live-status` and `GET /v1/trains/{train_number}/running` are retired. They answer `410 ENDPOINT_RETIRED` with `Deprecation`, `Sunset` and a `Link` header naming `/live`, and are not counted. Their documentation pages now open the live train status page.\n\nMigration required\n\nPoint `/live-status` and `/running` requests at `/live`; the `/live-status` query works unchanged. If you read `/live` before November 3, 2026, switch the removed fields to their replacements above.\n\n## October 24, 2026: Train schedules from the RailCore timetable\n\n- `GET /v1/trains/{train_number}/schedule`, `/stops` and `/route` now come from the same timetable as the RailCore site and apps, refreshed every 15 minutes.\n- Halts, times and running days follow the current timetable. Some trains gain or lose halts, and a few times move.\n- The source station's `arrival_time` and the destination's `departure_time` are always `null`, as documented. Some trains returned `\"00:00\"` before.\n- Station codes follow the current names, for example `CSMT` (was `CSTM`).\n- `/route` lists every station the train passes, with times placed between halts. Trains whose full route was unavailable before, for example 12932 and 12009, now return it.\n- Around 270 trains, mostly suburban locals, have no published running days, so `running_days` is `[]`.\n\nCheck your integration\n\nTreat `null` times at the ends of a route as \"no time\", and don't assume `running_days` is non-empty.\n\n## October 18, 2026: Station search ranking\n\n- `GET /v1/stations/search` returns results in a new order. A station whose name has the query as a later word now ranks with names that start with it, and busier stations win ties. For example, `q=delhi` now returns NDLS (New Delhi) first.\n- Ticket booking offices, out agencies, goods sheds, sidings, cabins and staff codes (names ending in OA, CB, CBO, MG, GR, SDG, CABIN and similar) now come after every passenger station. An exact code match still comes first.\n- A former name that matches the query only in part, such as `Delhi Main` for DLI, is no longer pinned above every other result. It is ranked with the other strong matches by how busy the station is. A former name typed in full, such as `VT` for CSMT, still comes first.\n- `confidence` values are unchanged, so results are no longer always in descending `confidence` order. A later-word match (0.88) can now appear above a name-prefix match (0.95).\n- `station_name` no longer contains repeated spaces. A few stations change, for example DE is now `DELHI MG` (was `DELHI MG`). This applies to `GET /v1/stations/search` and `GET /v1/stations/{station_code}`.\n- `GET /v1/charts/vacant-berths/route-scan` and route-scan jobs resolve a free-text `from` or `to` with the same rules, so they never pick a booking office or goods shed. Station codes resolve exactly as before.\n\nCheck your integration\n\nResponse shapes are unchanged. If you take the first search result as the match, or sort results by `confidence`, check a few common queries. For an exact station, pass its code.\n\n## October 7, 2026: Full train catalog and new train names\n\n- `GET /v1/trains/search` and `GET /v1/trains/{train_number}` now cover about 13,700 trains, up from about 4,100. Suburban locals are included, and the catalog is refreshed every 15 minutes.\n- Every train now carries its source station, destination station and running days. These follow the current timetable, including temporary diversions and extensions.\n- `train_name` is now the full published name in title case instead of an abbreviation in capitals. For example, 12951 is `New Delhi Tejas Rajdhani Express` (was `NDLS TEJAS RAJ`) and 11020 is `Konark Express` (was `KONARK EXPRESS`). `display_name` changes the same way.\n- Search ranking is predictable. Exact and leading train-number matches come first, then name matches, and suburban locals follow long-distance trains of equal relevance.\n\nCheck your integration\n\nIdentify trains by `train_number`, never by `train_name`. If you compare or parse the old upper-case names, switch to the number or compare case-insensitively against the new names.\n\n## September 9, 2026: One canonical station board\n\n- Consolidated the public station-board surface into `GET /v1/stations/{station_code}/live`. It remains a `live:read` operation. It counted as four credits at the time, and counts as one request since November 7, 2026.\n- Removed the duplicate public `/departures` and `/trains` station-board routes. Their former documentation URLs now open the live station board page.\n- Corrected lifecycle classification so a train is reported as moving only when live operational evidence supports it. Upcoming origin departures use `NOT_STARTED`; unobserved or overdue runs use `UNKNOWN`.\n- Expanded each board row with source and destination station names, normalized train type, current-station state, stop type, and cancellation details while preserving the existing response envelope.\n- Removed internal data-source identity and routing metadata from public station-board responses.\n\nMigration required\n\nIf your integration uses a retired station-board path, change it to `/v1/stations/{station_code}/live`. The retired API paths now return 404.\n\n## July 30, 2026: API and developer docs launch\n\n- Released the production Developer API at ir.railcore.tech/v1, with operations across stations, trains, journeys, availability, fares, charts, and asynchronous jobs. The reference lists the 30 operations it has today.\n- Published complete endpoint references at railcore.tech/docs, including every request field, response schema, error, scope, cost, plan limit, and implementation note.\n- Added a direct browser playground for standard API keys with local validation, cancellation, timeout handling, response headers, latency, JSON, and server-sent event inspection.\n- Added dedicated cURL, Node.js, and Python examples to every endpoint page. Samples use environment variables and never include the key entered in the playground.\n- Published the canonical OpenAPI YAML, deep-linked prerendered routes, route-specific metadata, and complete docs sitemap coverage.\n- Added responsive navigation and an accessible light and dark documentation theme that follows the system preference and supports a saved manual choice.\n\n## July 30, 2026: Launch safeguards\n\n- API-key authentication includes least-privilege scopes, HMAC request signing (required on Growth, Scale and Enterprise since November 3, 2026), IP allowlists, rate limits, and request metering.\n- Shared success and error envelopes include request IDs, trace IDs, freshness metadata, stable error codes, and retry guidance.\n- Playground credentials remain in memory only and are excluded from analytics capture and session replay.\n\nSource: https://railcore.tech/docs/changelog\nLast updated: 20 Nov 2026\n"}],"errors":[{"code":"INVALID_INPUT","status":400,"category":"VALIDATION","retryable":false,"description":"Generic schema or input validation failure.","fix":"Read error.message, correct the value it names and send the request again. On a seat enquiry it can also mean the train does not serve that journey: check that it stops at both stations.","docs_url":"https://railcore.tech/docs/errors-reference#error-INVALID_INPUT","endpoints":[]},{"code":"VALIDATION_ERROR","status":400,"category":"VALIDATION","retryable":false,"description":"A request field is missing or invalid. The message names it, and error.details[].field names the parameter (date, items[2].date, match, callback_url).","fix":"Correct each field that error.details[].field names (for example date or items[2].date) and send the request again. It is not counted.","docs_url":"https://railcore.tech/docs/errors-reference#error-VALIDATION_ERROR","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"INVALID_STATION_CODE","status":400,"category":"VALIDATION","retryable":false,"description":"Station code format or reference validation failed.","fix":"Send a station code of 1 to 6 letters or digits, such as NDLS, or J for Jalna. Look a code up with GET /stations/search.","docs_url":"https://railcore.tech/docs/errors-reference#error-INVALID_STATION_CODE","endpoints":[]},{"code":"INVALID_TRAIN_NUMBER","status":400,"category":"VALIDATION","retryable":false,"description":"Train number format validation failed.","fix":"Send the train number as 4 to 6 digits or capital letters, such as 12951. Find a number with GET /trains/search.","docs_url":"https://railcore.tech/docs/errors-reference#error-INVALID_TRAIN_NUMBER","endpoints":[]},{"code":"INVALID_DATE","status":400,"category":"VALIDATION","retryable":false,"description":"Date format or allowed window validation failed.","fix":"Send the date as YYYY-MM-DD in India time (IST), inside the window the endpoint's page gives.","docs_url":"https://railcore.tech/docs/errors-reference#error-INVALID_DATE","endpoints":[]},{"code":"INVALID_QUOTA","status":400,"category":"VALIDATION","retryable":false,"description":"Unknown quota code.","fix":"Use a quota code the endpoint's page lists, such as GN or TQ.","docs_url":"https://railcore.tech/docs/errors-reference#error-INVALID_QUOTA","endpoints":[]},{"code":"INVALID_CLASS_CODE","status":400,"category":"VALIDATION","retryable":false,"description":"Unknown class code.","fix":"Use a class code the endpoint's page lists, such as SL, 3A or 2A.","docs_url":"https://railcore.tech/docs/errors-reference#error-INVALID_CLASS_CODE","endpoints":[]},{"code":"MISSING_API_KEY","status":401,"category":"AUTH","retryable":false,"description":"No key in X-RailCore-Key, Authorization: Bearer or X-Api-Key, or the key is too short.","fix":"Send your key in X-RailCore-Key (or Authorization: Bearer, or X-Api-Key). Keys are at least 20 characters long; create one under API keys in the developer dashboard.","docs_url":"https://railcore.tech/docs/errors-reference#error-MISSING_API_KEY","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"AMBIGUOUS_API_KEY","status":401,"category":"AUTH","retryable":false,"description":"More than one key header was sent, with different keys. Send the key in one header.","fix":"Send the key in one header only, or make every key header carry the same key.","docs_url":"https://railcore.tech/docs/errors-reference#error-AMBIGUOUS_API_KEY","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"INVALID_API_KEY","status":401,"category":"AUTH","retryable":false,"description":"The credential is unknown or revoked.","fix":"Check the key for a typo or a missing part. If it was revoked or rotated, use the current key from the developer dashboard.","docs_url":"https://railcore.tech/docs/errors-reference#error-INVALID_API_KEY","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"API_KEY_DISABLED","status":401,"category":"AUTH","retryable":false,"description":"The credential was disabled by policy or an operator.","fix":"Use another active key from the developer dashboard, or contact support to find out why this one was disabled.","docs_url":"https://railcore.tech/docs/errors-reference#error-API_KEY_DISABLED","endpoints":[]},{"code":"API_KEY_EXPIRED","status":401,"category":"AUTH","retryable":false,"description":"Credential expiry has passed.","fix":"Create or rotate a key in the developer dashboard and update your configuration with the new one.","docs_url":"https://railcore.tech/docs/errors-reference#error-API_KEY_EXPIRED","endpoints":[]},{"code":"SIGNATURE_INVALID","status":401,"category":"AUTH","retryable":false,"description":"HMAC signature missing or not verified. Growth, Scale and Enterprise keys must sign every request; a key with no signing secret must be rotated.","fix":"Rebuild the signature: method, path with /v1, the canonical query (sorted by key then value), the SHA-256 hex of the exact body bytes sent, the timestamp and the nonce, one per line; HMAC-SHA256 with your signing secret, base64. A key with no signing secret must be rotated to get one.","docs_url":"https://railcore.tech/docs/errors-reference#error-SIGNATURE_INVALID","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"TIMESTAMP_EXPIRED","status":401,"category":"AUTH","retryable":false,"description":"Signed timestamp is outside the five-minute window.","fix":"Send the current Unix time in seconds in X-RailCore-Timestamp and keep your server clock in sync (NTP). It must be within five minutes of RailCore's clock.","docs_url":"https://railcore.tech/docs/errors-reference#error-TIMESTAMP_EXPIRED","endpoints":[]},{"code":"NONCE_REUSED","status":401,"category":"AUTH","retryable":false,"description":"The signed nonce already appeared in the replay window.","fix":"Generate a new random nonce of 16 to 128 characters for every request, retries included.","docs_url":"https://railcore.tech/docs/errors-reference#error-NONCE_REUSED","endpoints":[]},{"code":"PLAYGROUND_TOKEN_EXPIRED","status":401,"category":"AUTH","retryable":false,"description":"A docs playground token has expired or is not valid. They last 15 minutes; the playground gets a new one by itself.","fix":"Get a new playground token: the docs console does this by itself, or sign in again. Tokens last 15 minutes.","docs_url":"https://railcore.tech/docs/errors-reference#error-PLAYGROUND_TOKEN_EXPIRED","endpoints":[]},{"code":"IP_NOT_ALLOWED","status":403,"category":"AUTH","retryable":false,"description":"Caller IP is not in the key allowlist.","fix":"Send requests from an address on the key's IP allowlist, or add this address to the allowlist in the developer dashboard.","docs_url":"https://railcore.tech/docs/errors-reference#error-IP_NOT_ALLOWED","endpoints":[]},{"code":"SCOPE_MISSING","status":403,"category":"AUTH","retryable":false,"description":"The key lacks the operation scope.","fix":"Use a key whose scopes include the scope on this endpoint's page, or create a key with that scope.","docs_url":"https://railcore.tech/docs/errors-reference#error-SCOPE_MISSING","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"PLAN_INACTIVE","status":403,"category":"AUTH","retryable":false,"description":"The subscription is paused, past due, or cancelled.","fix":"Renew, resume or reactivate the subscription in the developer dashboard's billing section. Requests work again as soon as it is active.","docs_url":"https://railcore.tech/docs/errors-reference#error-PLAN_INACTIVE","endpoints":[]},{"code":"PLAN_ENDPOINT_DISABLED","status":403,"category":"FORBIDDEN","retryable":false,"description":"The current plan does not include the endpoint.","fix":"Move to a plan that includes this endpoint (see railcore.tech/pricing), or use an endpoint your plan includes.","docs_url":"https://railcore.tech/docs/errors-reference#error-PLAN_ENDPOINT_DISABLED","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"CREDITS_EXHAUSTED","status":402,"category":"QUOTA","retryable":false,"description":"The month's requests are used up, or too few are left for this request. Nothing is fetched.","fix":"Wait for your monthly requests to renew, or upgrade your plan. Check X-RailCore-Credits-Remaining before large requests such as seat batches.","docs_url":"https://railcore.tech/docs/errors-reference#error-CREDITS_EXHAUSTED","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"RATE_LIMITED","status":429,"category":"RATE_LIMIT","retryable":true,"description":"The account's per-minute budget, or a Free account's daily budget, is used up. Every key on the account shares it. Honor Retry-After.","fix":"Wait for the seconds in Retry-After, then retry with jitter. Limits belong to the account and are shared by all of its keys: spread requests out, or move to a plan with a higher limit.","docs_url":"https://railcore.tech/docs/errors-reference#error-RATE_LIMITED","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"JOB_LIMIT_EXCEEDED","status":429,"category":"RATE_LIMIT","retryable":true,"description":"Five async jobs are already active on the account, across all of its keys.","fix":"Wait for an active job to finish, or cancel one with DELETE /jobs/{job_id}, then submit again. An account can run five jobs at once.","docs_url":"https://railcore.tech/docs/errors-reference#error-JOB_LIMIT_EXCEEDED","endpoints":["submit-route-scan-job","submit-hopping-job"]},{"code":"TRAIN_NOT_FOUND","status":404,"category":"NOT_FOUND","retryable":false,"description":"No train has that number, on any /trains/{train_number}/ path but /live. The message names it: Train 99999 not found. Check the train number.","fix":"Check the train number. Find the right one by name or number with GET /trains/search.","docs_url":"https://railcore.tech/docs/errors-reference#error-TRAIN_NOT_FOUND","endpoints":["get-train","train-schedule","train-stops","train-route","coach-position","availability-calendar"]},{"code":"STATION_NOT_FOUND","status":404,"category":"NOT_FOUND","retryable":false,"description":"A station code or name could not be resolved. The message names it: Station ZZZZ not found. Check the station code.","fix":"Check the station code. Find it by name with GET /stations/search.","docs_url":"https://railcore.tech/docs/errors-reference#error-STATION_NOT_FOUND","endpoints":["get-station","live-station-board","route-vacancy-scan"]},{"code":"COACH_POSITION_NOT_FOUND","status":404,"category":"NOT_FOUND","retryable":false,"description":"On /trains/{train_number}/coach-position: the train exists, but no source RailCore reads publishes its coach composition. The message names it: No coach composition is published for train 12345. Not counted.","fix":"No source publishes this train's coach composition. Retrying soon will not help; try again on another day.","docs_url":"https://railcore.tech/docs/errors-reference#error-COACH_POSITION_NOT_FOUND","endpoints":["coach-position"]},{"code":"NO_TRAINS_FOUND","status":404,"category":"NOT_FOUND","retryable":false,"description":"No train matches the route and date.","fix":"Try another date, nearby stations, or match=city to include every station in both cities.","docs_url":"https://railcore.tech/docs/errors-reference#error-NO_TRAINS_FOUND","endpoints":["route-trains","journey-search"]},{"code":"NOT_FOUND","status":404,"category":"NOT_FOUND","retryable":false,"description":"Nothing matches the request: a train with no run on the date asked for on live train status, no fare for a fare estimate, or a path the API does not have.","fix":"Nothing matches the request. Check the identifiers and the date (a train may not run that day), then ask again.","docs_url":"https://railcore.tech/docs/errors-reference#error-NOT_FOUND","endpoints":["live-train","fare-estimate"]},{"code":"JOB_NOT_FOUND","status":404,"category":"NOT_FOUND","retryable":false,"description":"The async job does not exist or expired.","fix":"Check the job ID. Jobs and their results expire, so submit the job again if it is gone.","docs_url":"https://railcore.tech/docs/errors-reference#error-JOB_NOT_FOUND","endpoints":["get-job","cancel-job"]},{"code":"CHART_NOT_PREPARED","status":409,"category":"NOT_FOUND","retryable":true,"description":"The chart is not ready yet.","fix":"Ask again later: the chart is prepared a few hours before the train leaves.","docs_url":"https://railcore.tech/docs/errors-reference#error-CHART_NOT_PREPARED","endpoints":["chart-status","vacant-berths","vacant-berths-hopping"]},{"code":"TATKAL_NOT_OPEN","status":422,"category":"VALIDATION","retryable":false,"description":"Tatkal booking has not opened for the journey yet. error.opens_at (IST) says when, if known. Not counted.","fix":"Ask again after the time in error.opens_at (IST). Tatkal opens the day before the train leaves its origin, at 10:00 for AC classes and 11:00 for the rest.","docs_url":"https://railcore.tech/docs/errors-reference#error-TATKAL_NOT_OPEN","endpoints":["seat-availability"]},{"code":"QUOTA_NOT_AVAILABLE","status":422,"category":"VALIDATION","retryable":false,"description":"The train does not offer that quota in that class for the journey. Not counted.","fix":"Choose another quota or class: the train does not offer this quota in this class.","docs_url":"https://railcore.tech/docs/errors-reference#error-QUOTA_NOT_AVAILABLE","endpoints":["seat-availability"]},{"code":"QUOTA_NOT_SUPPORTED","status":422,"category":"VALIDATION","retryable":false,"description":"Seat availability is not offered for that quota on any train: it answers GN, TQ, SS and LD only. Premium Tatkal (PT), HP, DP, HO, YU and FT can be checked on IRCTC. RailCore refuses it before the seat provider is asked. Not counted.","fix":"Use GN, TQ, SS or LD. Other quotas, Premium Tatkal included, cannot be checked through RailCore; check them on IRCTC.","docs_url":"https://railcore.tech/docs/errors-reference#error-QUOTA_NOT_SUPPORTED","endpoints":["seat-availability","batch-seat-availability","availability-calendar"]},{"code":"CLASS_NOT_AVAILABLE","status":422,"category":"VALIDATION","retryable":false,"description":"The train does not carry that class. error.message lists the classes it does. Not counted.","fix":"Choose one of the classes the message lists for this train.","docs_url":"https://railcore.tech/docs/errors-reference#error-CLASS_NOT_AVAILABLE","endpoints":["seat-availability"]},{"code":"TRAIN_NOT_RUNNING","status":422,"category":"VALIDATION","retryable":false,"description":"The train does not leave the boarding station on that date. error.message lists the days it does. Not counted.","fix":"Choose one of the days the message lists, or check the boarding station.","docs_url":"https://railcore.tech/docs/errors-reference#error-TRAIN_NOT_RUNNING","endpoints":["seat-availability"]},{"code":"BOOKING_NOT_OPEN","status":422,"category":"VALIDATION","retryable":false,"description":"The date has not opened for booking: reservations open 60 days before the journey, at 8:00 AM in India. RailCore refuses it before the seat provider is asked. error.message names the day it opens. Not counted.","fix":"Choose a date inside the booking window: reservations open 60 days before the journey, at 08:00 IST.","docs_url":"https://railcore.tech/docs/errors-reference#error-BOOKING_NOT_OPEN","endpoints":["seat-availability","batch-seat-availability","availability-calendar"]},{"code":"JOB_ALREADY_FINISHED","status":409,"category":"NOT_FOUND","retryable":false,"description":"The job is already terminal and cannot be cancelled.","fix":"There is nothing to cancel. Read the job's result with GET /jobs/{job_id} instead.","docs_url":"https://railcore.tech/docs/errors-reference#error-JOB_ALREADY_FINISHED","endpoints":["cancel-job"]},{"code":"API_VERSION_SUNSET","status":410,"category":"NOT_FOUND","retryable":false,"description":"The requested API major has reached its announced sunset date. Migrate to a supported version.","fix":"Move to a supported API version. The changelog names the current one.","docs_url":"https://railcore.tech/docs/errors-reference#error-API_VERSION_SUNSET","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"ENDPOINT_RETIRED","status":410,"category":"NOT_FOUND","retryable":false,"description":"The endpoint no longer answers API keys. The Link header and error.details name the endpoint to use instead.","fix":"Use the endpoint the Link header and error.details name. For live train status that is GET /trains/{train_number}/live.","docs_url":"https://railcore.tech/docs/errors-reference#error-ENDPOINT_RETIRED","endpoints":[]},{"code":"UPSTREAM_UNAVAILABLE","status":503,"category":"UPSTREAM","retryable":true,"description":"Every live-data route for the request failed. Sent with Retry-After; not counted.","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted.","docs_url":"https://railcore.tech/docs/errors-reference#error-UPSTREAM_UNAVAILABLE","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"UPSTREAM_TIMEOUT","status":503,"category":"UPSTREAM","retryable":true,"description":"The live-data source ran past its deadline. Sent with Retry-After; not counted.","fix":"Wait for the seconds in Retry-After, then retry with exponential backoff and jitter (about 500 ms, 1 s, 2 s, 4 s) and stop after five attempts. The request is not counted.","docs_url":"https://railcore.tech/docs/errors-reference#error-UPSTREAM_TIMEOUT","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]},{"code":"INTERNAL","status":500,"category":"INTERNAL","retryable":true,"description":"Unexpected server error.","fix":"Retry with backoff. If it keeps happening, contact support with the X-RailCore-Request-ID.","docs_url":"https://railcore.tech/docs/errors-reference#error-INTERNAL","endpoints":[]},{"code":"METERING_UNAVAILABLE","status":503,"category":"INTERNAL","retryable":true,"description":"The request could not be counted, so the data was withheld.","fix":"Retry with backoff. The request was not counted and no data was sent.","docs_url":"https://railcore.tech/docs/errors-reference#error-METERING_UNAVAILABLE","endpoints":["search-stations","get-station","live-station-board","search-trains","get-train","train-schedule","train-stops","train-route","coach-position","live-train","route-trains","journey-search","compare-journeys","seat-availability","batch-seat-availability","availability-calendar","available-classes","fare-estimate","search-fares","unreserved-fare","chart-status","vacant-berths","vacant-berths-hopping","route-vacancy-scan","submit-route-scan-job","submit-hopping-job","get-job","cancel-job","stream-job","list-jobs"]}],"openapi":{"url":"https://railcore.tech/railcore-developer-api-v1.openapi.yaml","sha256":"7112c6e2dff8ce24a3c71e8e4efc1df4faedf8d62c437521ac1619d8d05627e0","yaml":"openapi: 3.1.0\ninfo:\n  title: RailCore Developer API\n  version: \"1.0.0\"\n  summary: RailCore railway intelligence API for India.\n  description: |\n    RailCore is a normalized, live-data railway API for Indian Railways. All endpoints return the same envelope shape.\n    Authentication is required on every endpoint. Send the API key in an `X-RailCore-Key` header, or as `Authorization: Bearer <key>`, or in an `X-Api-Key` header; two headers carrying different keys answer `401 AMBIGUOUS_API_KEY`. Growth, Scale and Enterprise keys must also sign every request with HMAC-SHA256 (`X-RailCore-Timestamp`, `X-RailCore-Nonce`, `X-RailCore-Signature`; see https://railcore.tech/docs/hmac). The signature's body hash is over the exact bytes of the request body as sent.\n\n    ### Base URL\n      * production — `https://ir.railcore.tech/v1`\n      * sandbox    — not applicable in v1; production keys are the only tier.\n\n    ### Envelope\n    Every response is `application/json` with the following top-level shape:\n    ```json\n    {\n      \"success\": true,\n      \"data\": { ... },\n      \"meta\": { \"api_version\": \"v1\", \"request_id\": \"req_...\", \"trace_id\": \"trc_...\", \"timestamp\": \"...\", \"freshness\": { \"mode\": \"live\", \"retrieved_at\": \"...\" } }\n    }\n    ```\n    Errors:\n    ```json\n    { \"success\": false, \"error\": { \"code\": \"STATION_NOT_FOUND\", \"message\": \"Station ZZZZ not found. Check the station code.\", \"category\": \"NOT_FOUND\", \"retryable\": false }, \"meta\": { ... } }\n    ```\n    A 404 names what it could not find (`Station ZZZZ not found. Check the station code.`, `Train 99999 not found. Check the train number.`). A `400 VALIDATION_ERROR` lists each problem in `error.details`, whose `field` names the parameter or body field, for example `date`, `items[2].date`, `match` or `callback_url`.\n\n    ### Freshness\n    RailCore serves **live data**. Every response emits:\n    ```\n    Cache-Control: no-store, no-cache, must-revalidate, private\n    Pragma: no-cache\n    Expires: 0\n    ```\n    Do not cache RailCore responses.\n\n    ### Rate limiting\n    Every rate limit is per account: the per-minute budget, the Free plan's daily budget and the extra caps of 30 requests a minute on `/charts/*` and on `/availability/seats/batch` are shared by every key on the account, and creating a new key does not reset them. `X-RailCore-RateLimit-Limit`, `X-RailCore-RateLimit-Remaining` and `X-RailCore-RateLimit-Reset` give the account's per-minute budget, and are sent only when the plan has a per-minute limit. A plan without one (Enterprise), and a request refused before the key was read (a malformed request, a missing or wrong key), get none of the three; until 2026-11-13 they read `0`. `X-RailCore-RateLimit-Day-*` headers are sent only on keys with a daily cap (the Free plan); a key without a daily cap receives no `Day-*` headers and never a daily 429. When rate-limited, RailCore returns HTTP 429 with `Retry-After`. Limits per plan: https://railcore.tech/docs/rate-limits\n\n    ### Requests\n    Pricing is per request, and most operations count as 1 request; each operation's cost is in its `x-railcore-cost` field. Only successful (2xx) responses are counted: failed requests are free. A batch or comparison that answers 200 is counted at the size it asked for, even when some of its items fail inside the response. Every response carries `X-RailCore-Credits-Cost` (what this request counted as) and `X-RailCore-Credits-Remaining` (the requests left); one credit is one request. Plans and prices: https://railcore.tech/docs/credits\n\n    ### Upstream failures\n    When a live-data source fails or times out, RailCore returns HTTP 503 with `error.code` `UPSTREAM_UNAVAILABLE` or `UPSTREAM_TIMEOUT` and a `Retry-After` header. These are not counted. `METERING_UNAVAILABLE` is also a 503, so branch on `error.code`.\n\n    ### Webhooks\n    `POST /jobs/route-scan` and `POST /jobs/hopping` take a `callback_url`. When the job ends, RailCore POSTs `{ job_id, status, result }` or `{ job_id, status, error }` to it, signed in `X-RailCore-Webhook-Signature` with the `webhook_secret` the 202 answer returns once. See the `JobFinished` callback below and https://railcore.tech/docs/webhooks.\n\n    ### Version sunset\n    When an API major reaches its announced sunset date, requests return HTTP `410 Gone` with `error.code = \"API_VERSION_SUNSET\"`. Migrate to a supported major version instead of retrying unchanged.\n\n  contact:\n    name: RailCore Developer Support\n    url: https://railcore.tech/docs\n    email: hi@railcore.tech\n  license:\n    name: Proprietary\n  termsOfService: https://railcore.tech/legal/api-terms\n\nservers:\n  - url: https://ir.railcore.tech/v1\n    description: Production\n\nsecurity:\n  - RailCoreKey: []\n  - RailCoreBearer: []\n  - RailCoreApiKey: []\n  - RailCoreKeyWithHmac: []\n\npaths:\n  # ------------------------------ Stations ------------------------------\n  /stations/search:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Search stations\n      tags: [Stations]\n      parameters:\n        - $ref: '#/components/parameters/queryString'\n        - $ref: '#/components/parameters/limit'\n      responses:\n        '200':\n          description: OK\n          headers:\n            $ref: '#/components/headers/AllStandard'\n          content:\n            application/json:\n              schema: { $ref: '#/components/schemas/EnvelopeStationSearch' }\n        '400': { $ref: '#/components/responses/ValidationError' }\n        '401': { $ref: '#/components/responses/AuthError' }\n        '429': { $ref: '#/components/responses/RateLimited' }\n        '503': { $ref: '#/components/responses/UpstreamError' }\n\n  /stations/{station_code}:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Get one station\n      tags: [Stations]\n      parameters:\n        - $ref: '#/components/parameters/pathStationCode'\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeStation' }}}}\n        '404': { $ref: '#/components/responses/StationNotFound' }\n        '401': { $ref: '#/components/responses/AuthError' }\n\n  /stations/{station_code}/live:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Live station board — trains arriving/departing in a rolling window\n      description: |\n        Returns one canonical station board for trains arriving at, departing\n        from, starting at, or terminating at the station. `NOT_STARTED` means\n        the train has not departed its origin. Scheduled timestamps alone never\n        imply movement; when the scheduled origin departure has passed without\n        live movement evidence, status is `UNKNOWN` rather than `ON_ROUTE`.\n        Internal data-source identities and routing details are not exposed.\n\n        The board lists a train when any of its times at the station (expected\n        or booked, arriving or leaving) falls inside `window`: from 2 hours ago\n        to `window_hours` ahead. A departure that crosses midnight is dated the\n        next day. A field with no value is left out, never null, and each\n        train's `notes` says why. A train that has not started and has no\n        forecast yet shows its booked times as the expected ones\n        (`timing_basis: scheduled`). A train RailCore's train catalog lists\n        takes its first and last stations, and its name when the live feed\n        named other ends, from the catalog.\n      tags: [Stations, Live]\n      parameters:\n        - $ref: '#/components/parameters/pathStationCode'\n        - name: window_hours\n          in: query\n          description: How far ahead the board looks, in hours. It lists trains due at the station from 2 hours ago until this many hours later, by expected or booked time. Any value other than 4 is read as 8; the response's `window_hours` and `window` say which was applied.\n          schema: { type: integer, enum: [4, 8], default: 8 }\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeStationBoard' }}}}\n        '404': { $ref: '#/components/responses/StationNotFound' }\n        '503': { $ref: '#/components/responses/UpstreamError' }\n\n  # ------------------------------ Trains ------------------------------\n  /trains/search:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Search trains by name or number\n      description: >-\n        Ranked search over RailCore's train catalog (about 13,700 trains, suburban locals\n        included, refreshed every 15 minutes). Names are published title case, for example\n        \"New Delhi Tejas Rajdhani Express\". A live provider is consulted only when the\n        catalog has fewer matches than the limit.\n      tags: [Trains]\n      parameters:\n        - $ref: '#/components/parameters/queryString'\n        - $ref: '#/components/parameters/limit'\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeTrainSearch' }}}}\n\n  /trains/{train_number}:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Train details\n      tags: [Trains]\n      parameters: [{ $ref: '#/components/parameters/pathTrainNumber' }]\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeTrain' }}}}\n        '404': { $ref: '#/components/responses/TrainNotFound' }\n\n  /trains/{train_number}/schedule:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Full train schedule\n      tags: [Trains]\n      parameters:\n        - { $ref: '#/components/parameters/pathTrainNumber' }\n        - name: include_intermediate\n          in: query\n          schema: { type: boolean, default: false }\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeTrainSchedule' }}}}\n        '404': { $ref: '#/components/responses/TrainNotFound' }\n\n  /trains/{train_number}/stops:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Booking-relevant stops (subset of schedule where is_stop=true)\n      tags: [Trains]\n      parameters: [{ $ref: '#/components/parameters/pathTrainNumber' }]\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeTrainSchedule' }}}}\n        '404': { $ref: '#/components/responses/TrainNotFound' }\n\n  /trains/{train_number}/route:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Full train route (including non-stop pass-through stations)\n      tags: [Trains]\n      parameters: [{ $ref: '#/components/parameters/pathTrainNumber' }]\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeTrainSchedule' }}}}\n        '404': { $ref: '#/components/responses/TrainNotFound' }\n\n  /trains/{train_number}/coach-position:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Coach position from engine (composition)\n      description: The rake from the front. Every vehicle is listed in its place, power cars (LPR, EOG) included, so `position_from_engine` runs without a gap.\n      tags: [Trains]\n      parameters: [{ $ref: '#/components/parameters/pathTrainNumber' }]\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeCoachPosition' }}}}\n        '404': { description: \"`TRAIN_NOT_FOUND`: no train has this number. `COACH_POSITION_NOT_FOUND`: the train exists, but no source RailCore reads publishes its coach composition (message \\\"No coach composition is published for train {number}.\\\"). Not counted, and not worth retrying soon.\", content: { application/json: { schema: { $ref: '#/components/schemas/ErrorEnvelope' }}}}\n\n  /trains/{train_number}/live:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Live train status\n      description: |\n        Where a train is right now, how late it is, and its times at every\n        station on the route. Returns one run of a train: its status and\n        position, its delay, when it should reach its last station, and the\n        scheduled, expected and actual times at every station on its route,\n        including the ones it passes without stopping.\n\n        A train reports about once a minute, so by default RailCore may answer\n        from its own read of the same run made up to 10 seconds earlier. Such an\n        answer says so: `freshness.railcore_cache` is `reused` and\n        `freshness.retrieved_at` is when that read was made. Pass `max_age=0`\n        for a fresh read. It counts as 1 request either way. Anything\n        RailCore cannot establish for a run is left out, never filled in from\n        the timetable. The `Server-Timing` response header shows where the time went.\n\n        The first station has no arrival and the last no departure: their\n        arrival and departure fields are left out, and `stop_type` says why.\n        A finished run whose arrival at its last station was reported has\n        `confidence: high`. Station names are written as the RailCore site\n        writes them (\"New Delhi\", \"Mumbai Central\").\n\n        This endpoint replaced `/trains/{train_number}/live-status` and\n        `/trains/{train_number}/running` on 2026-11-03. Those paths answer\n        `410 ENDPOINT_RETIRED` with `Deprecation`, `Sunset` and `Link` headers.\n      tags: [Trains, Live]\n      parameters:\n        - { $ref: '#/components/parameters/pathTrainNumber' }\n        - name: date\n          in: query\n          required: false\n          description: \"The day the train leaves its first station, as YYYY-MM-DD in IST. A train that left late last night is still running under last night's date. Leave it out for the run on its way now (one that has left its first station and is not more than 3 hours past its booked arrival at the last; with two on the way, the one that left most recently), or else the next run to leave. `journey_date` in the answer says which run it is.\"\n          schema: { type: string, format: date }\n        - name: from\n          in: query\n          required: false\n          description: The run's first station. Leave it out to use the train's own first station; needed only for a train missing from the train catalog.\n          schema: { $ref: '#/components/schemas/StationCode' }\n        - name: to\n          in: query\n          required: false\n          description: The run's last station. Leave it out to use the train's own last station; needed only for a train missing from the train catalog.\n          schema: { $ref: '#/components/schemas/StationCode' }\n        - name: max_age\n          in: query\n          required: false\n          description: The oldest RailCore read of this run, in seconds, you accept. 0 asks for a fresh read of the live feed.\n          schema: { type: integer, minimum: 0, maximum: 10, default: 10 }\n      responses:\n        '200': { description: \"The run's live status\", content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeLiveTrainStatus' }}}}\n        '400': { $ref: '#/components/responses/ValidationError' }\n        '401': { $ref: '#/components/responses/AuthError' }\n        '404': { description: \"`NOT_FOUND`: the train has no run on that date, for example a weekly train on a day it does not run.\", content: { application/json: { schema: { $ref: '#/components/schemas/ErrorEnvelope' }}}}\n        '429': { $ref: '#/components/responses/RateLimited' }\n        '503': { $ref: '#/components/responses/UpstreamError' }\n\n  # ------------------------------ Routes / journeys ------------------------------\n  /routes/trains:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Trains between two stations on a date\n      tags: [Journeys]\n      parameters:\n        - { name: from,  in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: to,    in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: date,  in: query, required: true, schema: { type: string, format: date }}\n        - { name: quota, in: query, schema: { $ref: '#/components/schemas/Quota' }}\n        - { name: match, in: query, required: false, schema: { type: string, enum: [city, station], default: city }, description: \"city: trains between any station of the two cities (a search from MMCT to NDLS also lists BDTS to NZM trains). station: only trains between the two stations asked for. The answer's `matched_by` says which it is.\" }\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeRouteTrains' }}}}\n        '404': { description: \"`NO_TRAINS_FOUND`: no train was found between the two stations on that date (with `match=station`, between those two stations only), or a station code does not exist. Not counted. `trains` is never empty.\", content: { application/json: { schema: { $ref: '#/components/schemas/ErrorEnvelope' }}}}\n\n  /journeys/search:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Journey search (same shape as /routes/trains, ranked for search UX)\n      tags: [Journeys]\n      parameters:\n        - { name: from,  in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: to,    in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: date,  in: query, required: true, schema: { type: string, format: date }}\n        - { name: match, in: query, required: false, schema: { type: string, enum: [city, station], default: city }, description: \"city: trains between any station of the two cities (a search from MMCT to NDLS also lists BDTS to NZM trains). station: only trains between the two stations asked for. The answer's `matched_by` says which it is.\" }\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeRouteTrains' }}}}\n        '404': { description: \"`NO_TRAINS_FOUND`: no train was found between the two stations on that date (with `match=station`, between those two stations only), or a station code does not exist. Not counted. `trains` is never empty.\", content: { application/json: { schema: { $ref: '#/components/schemas/ErrorEnvelope' }}}}\n\n  /journeys/compare:\n    post:\n      x-railcore-cost: \"1 request per route.\"\n      summary: Compare multiple journey queries in one request\n      description: Counted at the number of routes in `journeys` when the request answers 200, even when some routes fail inside the response. A request refused as a whole (4xx or 5xx) is free. Each result carries `matched_by`; a comparison matches by city, as `/routes/trains` does by default. A route with no train is an inline failure whose `error` is `NO_TRAINS_FOUND`, with a `message`.\n      tags: [Journeys]\n      requestBody:\n        required: true\n        content:\n          application/json:\n            schema:\n              type: object\n              required: [journeys]\n              properties:\n                journeys:\n                  type: array\n                  minItems: 1\n                  maxItems: 5\n                  items:\n                    type: object\n                    required: [from, to, date]\n                    properties:\n                      from: { $ref: '#/components/schemas/StationCode' }\n                      to:   { $ref: '#/components/schemas/StationCode' }\n                      date: { type: string, format: date }\n                      quota: { $ref: '#/components/schemas/Quota' }\n      responses:\n        '200':\n          description: OK\n          content:\n            application/json:\n              schema:\n                type: object\n                properties:\n                  success: { type: boolean }\n                  data:\n                    type: object\n                    properties:\n                      results: { type: array, items: { $ref: '#/components/schemas/RouteTrains' }}\n                  meta: { $ref: '#/components/schemas/Meta' }\n\n  # ------------------------------ Availability ------------------------------\n  /availability/seats:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Latest seat-availability snapshot for a single class and quota\n      description: A fresh availability enquiry on every request, with no RailCore cache. The upstream can still answer with a figure it read from IRCTC earlier; `classes[].last_updated_at` says when that figure was read, and `meta.timestamp` when RailCore answered. The payload is a timestamped availability snapshot, not a direct PRS connection. Upstream identity is intentionally not exposed.\n      tags: [Availability]\n      parameters:\n        - { name: train_number, in: query, required: true, schema: { $ref: '#/components/schemas/TrainNumber' }}\n        - { name: from,         in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: to,           in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: date,         in: query, required: true, schema: { type: string, format: date }}\n        - { name: class,        in: query, required: true, schema: { $ref: '#/components/schemas/ClassCode' }}\n        - { name: quota,        in: query, description: \"Seat availability answers GN (General), TQ (Tatkal), SS (Lower berth / senior citizen) and LD (Ladies). Any other quota, Premium Tatkal (PT) included, is refused for every train with 422 `QUOTA_NOT_SUPPORTED` before it is asked, and is not counted.\", schema: { $ref: '#/components/schemas/Quota' }}\n        - { name: fresh,        in: query, deprecated: true, schema: { type: boolean }, description: \"Ignored since 2026-11-03: every request is a fresh enquiry.\" }\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeAvailability' }}}}\n        '422': { description: \"The enquiry was refused for this journey, and is not counted. `TATKAL_NOT_OPEN`: Tatkal (`TQ`) booking has not opened yet; `error.opens_at` (IST) says when, if known. It opens the day before the train leaves its origin, at 10:00 for AC classes and 11:00 for the rest. `QUOTA_NOT_AVAILABLE`: the train does not offer that quota in that class. `QUOTA_NOT_SUPPORTED`: the quota is not one seat availability answers (only GN, TQ, SS and LD), for any train; check it on IRCTC. The seat provider is not asked. `CLASS_NOT_AVAILABLE`: the train does not carry that class; the message lists the ones it does. `TRAIN_NOT_RUNNING`: the train does not leave the boarding station on that date; the message lists the days it does. `BOOKING_NOT_OPEN`: the date is past the booking window (reservations open 60 days before the journey, at 08:00 IST; the foreign tourist quota FT is exempt), refused before the seat provider is asked. `INVALID_INPUT`: the train does not serve the journey.\", content: { application/json: { schema: { $ref: '#/components/schemas/ErrorEnvelope' }}}}\n\n  /availability/seats/batch:\n    post:\n      x-railcore-cost: \"1 request per distinct class per item (none or empty counts as 4).\"\n      summary: Seat availability for many train+class combinations\n      description: \"Counted at one request per distinct class on each item (classes compare case-insensitively, so `[\\\"SL\\\", \\\"sl\\\", \\\"SL\\\"]` counts once; an item with `classes` left out or empty counts as 4) when the request answers 200, even when some items fail inside the response. A request refused as a whole (4xx or 5xx) is free. An item whose date is past the booking window (60 days ahead, from 08:00 IST; FT is exempt) is not asked and not counted; it comes back in its place in `results` as a failed item with `error: BOOKING_NOT_OPEN`. When every item is past the window, the request answers 422 `BOOKING_NOT_OPEN`.\"\n      tags: [Availability]\n      requestBody:\n        required: true\n        content:\n          application/json:\n            schema:\n              type: object\n              required: [items]\n              properties:\n                items:\n                  type: array\n                  minItems: 1\n                  maxItems: 25\n                  items:\n                    type: object\n                    required: [train_number, from, to, date]\n                    properties:\n                      train_number: { $ref: '#/components/schemas/TrainNumber' }\n                      from: { $ref: '#/components/schemas/StationCode' }\n                      to: { $ref: '#/components/schemas/StationCode' }\n                      date: { type: string, format: date }\n                      classes: { type: array, maxItems: 8, items: { $ref: '#/components/schemas/ClassCode' }, description: \"Up to 8 classes; a class repeated in one item is asked and counted once. Left out or empty, the 4 default classes (SL, 3A, 2A, 1A) are asked and counted.\" }\n                      quota: { $ref: '#/components/schemas/Quota' }\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeAvailabilityBatch' }}}}\n        '422': { description: \"Every item was refused before it was asked, and nothing is counted. `QUOTA_NOT_SUPPORTED`: no item names a quota seat availability answers (GN, TQ, SS, LD). `BOOKING_NOT_OPEN`: every item's date is past the booking window.\", content: { application/json: { schema: { $ref: '#/components/schemas/ErrorEnvelope' }}}}\n\n  /availability/calendar:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Availability for each date the train runs in a window of days\n      description: \"Finds the dates the train runs from `date` (default today in India) for `days` days, then makes one seat enquiry per running date, four at a time. Dates the train does not run on are left out, so a window with no runs answers an empty `days` list. The upstream can answer an enquiry from its own cache, so each day's `last_updated_at` says when its figure was read from IRCTC. A date whose own enquiry fails shows the upstream calendar listing's figure, with no fare and `last_updated_at` null; if every date fails, the request answers 503 and is not counted. Bookings open 60 days ahead, from 08:00 IST (FT is exempt): a `date` past that answers 422 `BOOKING_NOT_OPEN`, not counted, and a window that runs past the last open date stops at it, so `days` can hold fewer dates than asked for.\"\n      tags: [Availability]\n      parameters:\n        - { name: train_number, in: query, required: true, schema: { $ref: '#/components/schemas/TrainNumber' }}\n        - { name: from, in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: to,   in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: class, in: query, required: true, schema: { $ref: '#/components/schemas/ClassCode' }}\n        - { name: quota, in: query, schema: { $ref: '#/components/schemas/Quota' }}\n        - { name: date,  in: query, description: \"First date of the window, today or later; defaults to today in India.\", schema: { type: string, format: date }}\n        - { name: days,  in: query, schema: { type: integer, minimum: 1, maximum: 30, default: 7 }}\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeAvailabilityCalendar' }}}}\n        '404': { $ref: '#/components/responses/TrainNotFound' }\n        '422': { description: \"`BOOKING_NOT_OPEN`: `date` is past the booking window. Not counted.\", content: { application/json: { schema: { $ref: '#/components/schemas/ErrorEnvelope' }}}}\n\n  /availability/classes:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Classes offered for a given train on a route\n      tags: [Availability]\n      parameters:\n        - { name: train_number, in: query, required: true, schema: { $ref: '#/components/schemas/TrainNumber' }}\n        - { name: from, in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: to, in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: date, in: query, required: true, schema: { type: string, format: date }}\n      responses:\n        '200':\n          description: OK\n          content:\n            application/json:\n              schema:\n                type: object\n                properties:\n                  success: { type: boolean }\n                  data:\n                    type: object\n                    properties:\n                      train_number: { $ref: '#/components/schemas/TrainNumber' }\n                      classes: { type: array, items: { $ref: '#/components/schemas/ClassCode' }}\n                  meta: { $ref: '#/components/schemas/Meta' }\n\n  # ------------------------------ Fares ------------------------------\n  /fares/estimate:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Fare per class for a train on a route\n      tags: [Fares]\n      parameters:\n        - { name: train_number, in: query, required: true, schema: { $ref: '#/components/schemas/TrainNumber' }}\n        - { name: from, in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: to,   in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: class, in: query, description: \"Narrows the answer to this class. Left out, every class with a fare is returned.\", schema: { $ref: '#/components/schemas/ClassCode' }}\n        - { name: quota, in: query, schema: { $ref: '#/components/schemas/Quota' }}\n      responses:\n        '200': { description: \"OK. `fares` is never empty.\", content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeFareEstimate' }}}}\n        '404': { description: \"`NOT_FOUND`: no fare is published for this train, journey, class and quota. Not counted.\", content: { application/json: { schema: { $ref: '#/components/schemas/ErrorEnvelope' }}}}\n\n  /fares/search:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Fares across trains on a route\n      tags: [Fares]\n      parameters:\n        - { name: from, in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: to,   in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: date, in: query, required: true, schema: { type: string, format: date }}\n        - { name: quota, in: query, schema: { $ref: '#/components/schemas/Quota' }}\n      responses:\n        '200':\n          description: OK\n          content:\n            application/json:\n              schema:\n                type: object\n                properties:\n                  success: { type: boolean }\n                  data:\n                    type: object\n                    properties:\n                      from_station_code: { $ref: '#/components/schemas/StationCode' }\n                      to_station_code: { $ref: '#/components/schemas/StationCode' }\n                      journey_date: { type: string, format: date }\n                      quota: { $ref: '#/components/schemas/Quota' }\n                      trains:\n                        type: array\n                        items:\n                          type: object\n                          properties:\n                            train_number: { $ref: '#/components/schemas/TrainNumber' }\n                            fares: { type: array, items: { $ref: '#/components/schemas/FareItem' }}\n                  meta: { $ref: '#/components/schemas/Meta' }\n\n  # ------------------------------ Charts ------------------------------\n  /charts/status:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Chart preparation status\n      tags: [Charts]\n      parameters:\n        - { name: train_number, in: query, required: true, schema: { $ref: '#/components/schemas/TrainNumber' }}\n        - { name: date, in: query, required: true, schema: { type: string, format: date }}\n        - { name: station, in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeChartStatus' }}}}\n        '409': { $ref: '#/components/responses/ChartNotReady' }\n\n  /charts/vacant-berths:\n    get:\n      x-railcore-cost: \"Counts as 3 requests.\"\n      summary: Post-chart vacant berths per coach/class\n      tags: [Charts]\n      parameters:\n        - { name: train_number, in: query, required: true, schema: { $ref: '#/components/schemas/TrainNumber' }}\n        - { name: from, in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: to,   in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: date, in: query, required: true, schema: { type: string, format: date }}\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeVacantBerths' }}}}\n        '409': { $ref: '#/components/responses/ChartNotReady' }\n\n  /charts/vacant-berths/hopping:\n    get:\n      x-railcore-cost: \"Counts as 4 requests.\"\n      summary: Post-chart vacant berths + a hopping plan when no single berth covers the full segment\n      description: |\n        Same upstream chain as `/charts/vacant-berths`: `trainComposition` +\n        one `vacantBerth` request per class. Additionally computes a **hopping\n        plan** per class using a minimum-count interval-cover algorithm — when\n        no single berth is vacant end-to-end, we stitch multiple consecutive\n        vacant sub-segments on the same train into a chain that covers the\n        caller's `from → to`, minimizing seat changes.\n\n        `via=CODE,CODE` (comma-separated or repeated query) pins intermediate\n        stations that the chain must pass through, in journey order.\n        `max_hops` (default 6, max 12) caps chain length.\n\n        A response with `hopping.disabled=true, disabled_reason=\"SCHEDULE_UNAVAILABLE\"`\n        indicates the train schedule could not be fetched — direct-only\n        results are still returned. A per-class option with `is_covered=false`\n        includes a machine-readable `reason` field (`NO_VACANT_BERTHS`,\n        `GAP_UNREACHABLE`, `MAX_HOPS_EXCEEDED`, `VIA_GAP_UNREACHABLE`) plus\n        the earliest unreachable stop so the caller can suggest a change.\n      tags: [Charts]\n      parameters:\n        - { name: train_number, in: query, required: true, schema: { $ref: '#/components/schemas/TrainNumber' }}\n        - { name: from, in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: to,   in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: date, in: query, required: true, schema: { type: string, format: date }}\n        - { name: via, in: query, required: false,\n            schema: { type: string },\n            description: \"Comma-separated pinned intermediate station codes, in journey order (e.g. `via=JL,AN`).\" }\n        - { name: max_hops, in: query, required: false,\n            schema: { type: integer, minimum: 1, maximum: 12, default: 6 },\n            description: \"Cap on chain length. Chains exceeding this are reported as `MAX_HOPS_EXCEEDED`.\" }\n        - name: prefer_berth\n          in: query\n          required: false\n          schema: { type: string }\n          description: |\n            Comma-separated preferred berth codes. Accepts canonical\n            (`L`, `M`, `U`, `SL`, `SU`, `R`, `P`, `W`, `A`) or aliases\n            (`LB`, `MB`, `UB`, `SLB`, `SUB`, `LOWER`, `MIDDLE`, `UPPER`,\n            `SIDE-LOWER`, `SIDE-UPPER`, `CABIN`, `COUPE`, `WINDOW`,\n            `AISLE`, `ROOMETTE`). Hard-filters `direct.options[].berths`\n            to only these codes; used as a soft tie-break bias in the\n            hopping algorithm (never sacrifices reach, so a covering\n            plan is still returned even if all berths are non-preferred).\n            Unknown tokens are silently dropped. Example: `LB,SLB`.\n        - name: avoid_berth\n          in: query\n          required: false\n          schema: { type: string }\n          description: |\n            Comma-separated berth codes to avoid. Same alias set as\n            `prefer_berth`. Hard-filtered out of `direct.options`;\n            treated as a soft negative bias (-5) in the hopping tie-break\n            — an avoided berth is still picked when it is the only way\n            to cover the segment. If a code appears in both `prefer_berth`\n            and `avoid_berth`, avoid wins. Example: `UB,SUB`.\n        - name: prefer_class\n          in: query\n          required: false\n          schema: { type: string }\n          description: |\n            Comma-separated preferred class codes (`SL`, `3A`, `2A`,\n            `1A`, `3E`, `CC`, `EC`, `2S`, `FC`). Reorders the fan-out so\n            preferred classes are polled first (results surface earlier\n            under bounded concurrency) and reorders `hopping.options[]`\n            and `direct.options[]` so preferred classes appear first.\n            Unknown tokens are silently dropped. Example: `SL,3E`.\n        - name: avoid_class\n          in: query\n          required: false\n          schema: { type: string }\n          description: |\n            Comma-separated class codes to skip entirely. Each skipped\n            class skips one upstream `vacantBerth` lookup (the request\n            costs the same, see `x-railcore-cost`). Skipped classes\n            never appear in `hopping.options` or `direct.options`.\n            Example: `1A` to skip AC First Class. Classes actually\n            dropped are echoed in `_meta.preferences_applied.classes_skipped`.\n        - name: include_fare\n          in: query\n          required: false\n          schema: { type: string, enum: [\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"] }\n          description: |\n            When `true`, each hop is decorated with `fare_inr`, each hopping\n            option with `total_fare_inr`, and each direct option with\n            `fare_inr`. Adds one upstream `fare-estimate` lookup per unique\n            `(train, from, to)` tuple across the response; the request\n            costs the same (`x-railcore-cost`). Failures degrade\n            gracefully to `null` fares — the response is never blocked on\n            fare data. Defaults to `false`.\n        - name: include_alternate_boarding\n          in: query\n          required: false\n          schema: { type: string, enum: [\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"] }\n          description: |\n            When `true`, populate `alternate_boarding.candidates[]` with\n            same-train boarding stations near the caller's `from` (window of\n            2 stops before + 2 after, clipped to the requested segment).\n            Each candidate summarises direct-vacancy counts by class and\n            which classes are reachable via hopping. Uses only in-memory\n            data — no additional upstream chart lookups. If `include_fare`\n            is also `true`, each candidate's `fare_inr_by_class` is\n            populated for `(candidate → to)`.\n        - name: strategies\n          in: query\n          required: false\n          schema: { type: string }\n          description: |\n            Comma-separated list of optimisation strategies to compute per\n            class. Each option in `hopping.options[i]` gains a\n            `strategies[]` array with one entry per requested strategy.\n            Values:\n            - `min_hops` (default) — fewest logical hops, current behaviour\n            - `min_seat_changes` — same-berth continuity, best for elderly/family\n            - `cheapest` — Dijkstra shortest-path over fare weights;\n              auto-enables `include_fare=true`\n            Alias: `all` expands to all supported strategies. Unknown\n            tokens are silently dropped. Example: `strategies=min_hops,cheapest`.\n        - name: alternate_boarding_mode\n          in: query\n          required: false\n          schema: { type: string, enum: [\"lightweight\", \"extended\"], default: \"lightweight\" }\n          description: |\n            How much upstream work to do when\n            `include_alternate_boarding=true`:\n            - `lightweight` (default) — re-project existing berth data.\n              No extra upstream chart lookups. Fast but approximate.\n            - `extended` — fresh `chart-composition` + per-class\n              `vacantBerth` fan-out for each top-N candidate. Authoritative\n              data (real chart-2 timing, quota-specific berths); adds\n              ~800ms-2s latency and 1-5 upstream chart lookups. Either\n              mode costs the same (`x-railcore-cost`).\n        - name: alternate_boarding_max_candidates\n          in: query\n          required: false\n          schema: { type: integer, minimum: 1, maximum: 5, default: 3 }\n          description: |\n            Cap on the number of `alternate_boarding_mode=extended`\n            candidates to query upstream. Clamped to [1, 5]. Default 3.\n            Ignored in lightweight mode. Each candidate adds one\n            chart-composition + one vacantBerth lookup per class upstream;\n            the request costs the same.\n        - name: include_cross_class\n          in: query\n          required: false\n          schema: { type: string, enum: [\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"] }\n          description: |\n            When `true`, populate `cross_class` with a single plan that\n            allows switching classes between hops. Useful when no\n            single-class chain covers the requested segment. No\n            additional upstream lookups — reuses the same per-class\n            vacantBerth data already fetched. Default `false`.\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeVacantBerthsHopping' }}}}\n        '400': { $ref: '#/components/responses/ValidationError' }\n        '409': { $ref: '#/components/responses/ChartNotReady' }\n\n  /charts/vacant-berths/route-scan:\n    get:\n      x-railcore-cost: \"Counts as 8 requests.\"\n      summary: Route-first multi-train vacant-berth scanner (with per-train hopping)\n      description: |\n        Route-first, multi-train version of `/charts/vacant-berths/hopping`.\n        Where the hopping endpoint answers \"for THIS train, what's vacant\n        and how do I stitch berths?\", this one answers \"for THIS `from → to`\n        journey on THIS date, which train should I board?\" — the intent of\n        an urgent traveller who cares about reaching the destination, not\n        a specific train.\n\n        **Flow.**\n        1. Resolve `from` / `to` — accepts a station **code** (`PUNE`) or a\n           station **name** (`Pune Jn`, `nagpur`, `poona`). Fuzzy hits above\n           the 0.55 confidence threshold are accepted; alternates are echoed\n           in `from.alternates[]` / `to.alternates[]` so callers can render a\n           disambiguation prompt when the top hit isn't obvious.\n        2. Call `routes-trains` for the route + date.\n        3. Filter by `only_running` (weekly-schedule match), `train_types`\n           / `avoid_train_types`.\n        4. Sort by `sort_by` (default `departure`) and cap to `max_trains`\n           (default 100, maximum 100). Trains beyond the cap appear in\n           `matches[]` with `scan_status=\"SKIPPED_CAP_EXCEEDED\"` — visible\n           but without scan detail.\n        5. Fan out per-train (bounded concurrency = 2) to the hopping\n           handler, passing through every user preference (`prefer_class`,\n           `include_fare`, `strategies`, `include_alternate_boarding`,\n           `include_cross_class`, etc.). Individual train failures never\n           fail the whole request — they land in `_meta.partial_failures`.\n        6. Score each scanned train `[0, 100]` on chart readiness, direct\n           vacancy, hopping coverage, seat-change penalty, and preference\n           matches (see `score_breakdown`).\n        7. Build a plain-English one-liner per train\n           (`recommendation` + optional `urgency_hint`) suitable for direct\n           display in a consumer UI.\n        8. Optionally filter by `min_score`, `only_chart_prepared`.\n        9. Re-sort matches by the caller's `sort_by` and return.\n\n        **Upstream work.** One `routes-trains` lookup, then per scanned\n        train: one `chart-status`, one `train-schedule`, one\n        `coach-position`, and one `vacantBerth` lookup per class\n        discovered. With `include_fare=true` add ~1 `fare-estimate` per\n        unique `(train, from, to)` tuple; with\n        `alternate_boarding_mode=extended` add up to 5 candidate\n        chart-status + vacantBerth fan-outs per train. None of this\n        changes what the request costs: it is the flat\n        `x-railcore-cost` whatever these options are.\n\n        **Errors.**\n        - `400 INVALID_INPUT` — missing / malformed query params.\n        - `404 STATION_NOT_FOUND` — `from` or `to` could not be resolved\n          to a canonical station code above the confidence threshold. The\n          error body includes `field` (`\"from\"` or `\"to\"`) and `input`.\n        - `503 UPSTREAM_UNAVAILABLE` — the `routes-trains` upstream failed\n          entirely. Per-train failures degrade gracefully — see\n          `_meta.partial_failures[]`.\n      tags: [Charts]\n      parameters:\n        - name: from\n          in: query\n          required: true\n          schema: { type: string, minLength: 1, maxLength: 60 }\n          description: |\n            Boarding station — either a canonical station code (`PUNE`) or\n            a station name (`Pune Jn`, case-insensitive). Fuzzy hits above\n            confidence 0.55 are accepted; alternates surface in\n            `from.alternates`.\n        - name: to\n          in: query\n          required: true\n          schema: { type: string, minLength: 1, maxLength: 60 }\n          description: Destination station. Same resolution rules as `from`.\n        - name: date\n          in: query\n          required: true\n          schema: { type: string, format: date }\n          description: Journey date, `YYYY-MM-DD`. Determines the running-day filter.\n        - name: quota\n          in: query\n          required: false\n          schema: { type: string, default: \"GN\" }\n        - name: max_trains\n          in: query\n          required: false\n          schema: { type: integer, minimum: 1, maximum: 100, default: 100 }\n          description: |\n            Cap on how many trains are actually fanned out for a full\n            per-train scan. Default is `100`, effectively \"scan every\n            train on the route\" — even the busiest Indian Railways\n            routes rarely see more than ~30 trains per day. Lower this\n            explicitly if you want a faster answer (the request costs the same); trains\n            beyond the cap still appear in `matches[]` with\n            `scan_status=\"SKIPPED_CAP_EXCEEDED\"`. Hard cap 100 guards\n            against runaway upstream work.\n        - name: min_score\n          in: query\n          required: false\n          schema: { type: number, minimum: 0, maximum: 100, default: 0 }\n          description: |\n            Drop matches with `score < min_score` from `matches[]`. The\n            train count is still reflected in\n            `_meta.trains_dropped_by_score_filter`.\n        - name: only_running\n          in: query\n          required: false\n          schema: { type: string, enum: [\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"], default: \"true\" }\n          description: |\n            When `true` (default), drop trains whose `running_days` don't\n            include `date`'s weekday. When `false`, include them with\n            `runs_on_date=false` and a running-day penalty applied to the\n            score.\n        - name: only_chart_prepared\n          in: query\n          required: false\n          schema: { type: string, enum: [\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"], default: \"false\" }\n          description: |\n            When `true`, drop trains where neither chart 1 nor chart 2 is\n            prepared. Useful for \"book right now\" UIs.\n        - name: sort_by\n          in: query\n          required: false\n          schema: { type: string, enum: [departure, departure_desc, duration, score, chart_ready], default: departure }\n          description: |\n            Sort key applied to `matches[]`:\n            - `departure` (default) — earliest departure first.\n            - `departure_desc` — latest first.\n            - `duration` — shortest journey first.\n            - `score` — highest composite score first.\n            - `chart_ready` — chart-2 prepared > chart-1 only > neither;\n              then score, then departure.\n            `SKIPPED_CAP_EXCEEDED` entries are always sorted last\n            regardless of key.\n        - name: include_detail\n          in: query\n          required: false\n          schema: { type: string, enum: [\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"], default: \"true\" }\n          description: |\n            When `true` (default), each match's `hopping_detail` field\n            contains the full `/charts/vacant-berths/hopping` response\n            body. When `false`, only the compact `classes_summary` is\n            emitted per match — ~10× smaller responses.\n        - name: train_types\n          in: query\n          required: false\n          schema: { type: string }\n          description: |\n            Comma-separated allow list of train types (e.g.\n            `SF,RAJDHANI,VANDE_BHARAT`). Empty = accept all.\n        - name: avoid_train_types\n          in: query\n          required: false\n          schema: { type: string }\n          description: |\n            Comma-separated deny list (e.g. `PASSENGER,MEMU,DEMU`).\n            Deny always wins over allow.\n        - name: max_hops\n          in: query\n          required: false\n          schema: { type: integer, minimum: 1, maximum: 12, default: 6 }\n          description: Forwarded to the per-train hopping handler.\n        - name: prefer_berth\n          in: query\n          required: false\n          schema: { type: string }\n          description: Forwarded to the per-train hopping handler.\n        - name: avoid_berth\n          in: query\n          required: false\n          schema: { type: string }\n          description: Forwarded to the per-train hopping handler.\n        - name: prefer_class\n          in: query\n          required: false\n          schema: { type: string }\n          description: |\n            Forwarded to the per-train hopping handler AND used in the\n            scoring formula — direct/hopping coverage in a preferred\n            class earns a bigger bonus than an arbitrary class.\n        - name: avoid_class\n          in: query\n          required: false\n          schema: { type: string }\n          description: |\n            Forwarded to the per-train hopping handler. Skipped classes\n            skip one `vacantBerth` lookup per train; the request costs\n            the same.\n        - name: include_fare\n          in: query\n          required: false\n          schema: { type: string, enum: [\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"] }\n          description: |\n            When `true`, populate hop-level and direct-option fares in\n            every match's `hopping_detail`. Adds one `fare-estimate`\n            lookup per unique `(train, from, to)` tuple across the\n            response; the request costs the same.\n        - name: include_alternate_boarding\n          in: query\n          required: false\n          schema: { type: string, enum: [\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"] }\n          description: |\n            Forwarded to the per-train hopping handler. See\n            `/charts/vacant-berths/hopping` for details on lightweight\n            vs. extended modes.\n        - name: strategies\n          in: query\n          required: false\n          schema: { type: string }\n          description: |\n            Forwarded to the per-train hopping handler. `cheapest`\n            auto-enables `include_fare`.\n        - name: alternate_boarding_mode\n          in: query\n          required: false\n          schema: { type: string, enum: [\"lightweight\", \"extended\"], default: \"lightweight\" }\n        - name: alternate_boarding_max_candidates\n          in: query\n          required: false\n          schema: { type: integer, minimum: 1, maximum: 5, default: 3 }\n        - name: include_cross_class\n          in: query\n          required: false\n          schema: { type: string, enum: [\"true\", \"false\", \"1\", \"0\", \"yes\", \"no\"] }\n      responses:\n        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/EnvelopeVacantBerthsRouteScan' }}}}\n        '400': { $ref: '#/components/responses/ValidationError' }\n        '404':\n          description: A station input could not be resolved.\n          content:\n            application/json:\n              schema:\n                type: object\n                properties:\n                  error: { type: string, enum: [STATION_NOT_FOUND] }\n                  message: { type: string }\n                  field: { type: string, enum: [from, to] }\n                  input: { type: string }\n\n  # ------------------------------ Runtime additions ------------------------------\n  /fares/unreserved:\n    get:\n      x-railcore-cost: \"Counts as 1 request.\"\n      summary: Unreserved and season-ticket fare enquiry\n      tags: [Fares]\n      parameters:\n        - { name: from, in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: to, in: query, required: true, schema: { $ref: '#/components/schemas/StationCode' }}\n        - { name: date, in: query, required: false, schema: { type: string, format: date }, description: \"Today, tomorrow or the day after, in India (IST): fares are quoted for those three days only. Defaults to today when omitted. With train_type T (MMTS), today only. Any other day is refused with 400 `VALIDATION_ERROR` and is not counted.\" }\n        - { name: class, in: query, required: false, schema: { type: string, enum: [II, FC], default: II }, description: \"II = Second Class; FC = First Class.\" }\n        - { name: train_type, in: query, required: false, schema: { type: string, enum: [O, E, S, T], default: O }, description: \"Ordinary, Mail/Express, Superfast, or MMTS. MMTS fares are quoted for today only.\" }\n        - { name: ticket_type, in: query, required: false, schema: { type: string, enum: [J, M, Q, H, Y], default: J }, description: \"Journey, Monthly, Quarterly, Half Yearly, or Yearly.\" }\n        - { name: adult, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 9, default: 1 }}\n        - { name: child, in: query, required: false, schema: { type: integer, minimum: 0, maximum: 9, default: 0 }}\n        - { name: concession, in: query, required: false, schema: { type: string }, description: \"Applicable UTS concession code.\" }\n      responses:\n        '200':\n          description: Unreserved fare routes\n          content:\n            application/json:\n              schema:\n                type: object\n                properties:\n                  success: { type: boolean }\n                  data:\n                    type: object\n                    properties:\n                      from_station_code: { $ref: '#/components/schemas/StationCode' }\n                      to_station_code: { $ref: '#/components/schemas/StationCode' }\n                      from: { allOf: [{ $ref: '#/components/schemas/StationCode' }], deprecated: true, description: \"Deprecated: the same code as from_station_code. Still sent; removed in a later release.\" }\n                      to: { allOf: [{ $ref: '#/components/schemas/StationCode' }], deprecated: true, description: \"Deprecated: the same code as to_station_code. Still sent; removed in a later release.\" }\n                      date: { type: string, format: date }\n                      class: { type: string, enum: [II, FC] }\n                      train_type: { type: string, enum: [O, E, S, T] }\n                      ticket_type: { type: string, enum: [J, M, Q, H, Y] }\n                      adult: { type: integer }\n                      child: { type: integer }\n                      routes:\n                        type: array\n                        items:\n                          type: object\n                          properties:\n                            route: { type: string }\n                            fare: { type: number, description: \"Fare in rupees, for example 15 or 17.5 (a string such as \\\"15.00\\\" until 2026-11-13).\" }\n                  meta: { $ref: '#/components/schemas/Meta' }\n        '400': { $ref: '#/components/responses/ValidationError' }\n        '401': { $ref: '#/components/responses/AuthError' }\n        '429': { $ref: '#/components/responses/RateLimited' }\n        '503': { $ref: '#/components/responses/UpstreamError' }\n\n  /jobs/route-scan:\n    post:\n      x-railcore-cost: \"Counts as 8 requests.\"\n      summary: Submit an asynchronous route vacancy scan\n      tags: [Charts, Jobs]\n      requestBody:\n        required: true\n        content:\n          application/json:\n            schema:\n              allOf:\n                - $ref: '#/components/schemas/RouteScanJobInput'\n      callbacks:\n        jobFinished: { $ref: '#/components/callbacks/JobFinished' }\n      responses:\n        '202': { $ref: '#/components/responses/JobAccepted' }\n        '400': { $ref: '#/components/responses/ValidationError' }\n        '401': { $ref: '#/components/responses/AuthError' }\n        '429': { $ref: '#/components/responses/RateLimited' }\n\n  /jobs/hopping:\n    post:\n      x-railcore-cost: \"Counts as 4 requests.\"\n      summary: Submit an asynchronous vacant-berth hopping analysis\n      tags: [Charts, Jobs]\n      requestBody:\n        required: true\n        content:\n          application/json:\n            schema:\n              allOf:\n                - $ref: '#/components/schemas/HoppingJobInput'\n      callbacks:\n        jobFinished: { $ref: '#/components/callbacks/JobFinished' }\n      responses:\n        '202': { $ref: '#/components/responses/JobAccepted' }\n        '400': { $ref: '#/components/responses/ValidationError' }\n        '401': { $ref: '#/components/responses/AuthError' }\n        '429': { $ref: '#/components/responses/RateLimited' }\n\n  /jobs/{job_id}:\n    parameters:\n      - $ref: '#/components/parameters/pathJobId'\n    get:\n      x-railcore-cost: \"Free (0 requests).\"\n      summary: Poll an async job and retrieve its completed result\n      tags: [Jobs]\n      responses:\n        '200':\n          description: Current job state or terminal result\n          content:\n            application/json:\n              schema: { $ref: '#/components/schemas/EnvelopeJob' }\n        '400': { $ref: '#/components/responses/ValidationError' }\n        '404': { $ref: '#/components/responses/NotFound' }\n    delete:\n      x-railcore-cost: \"Free (0 requests).\"\n      summary: Cancel a pending or processing async job\n      tags: [Jobs]\n      responses:\n        '200':\n          description: Job cancelled\n          content:\n            application/json:\n              schema: { $ref: '#/components/schemas/EnvelopeJob' }\n        '400': { $ref: '#/components/responses/ValidationError' }\n        '404': { $ref: '#/components/responses/NotFound' }\n        '409':\n          description: Job is already in a terminal state (`JOB_ALREADY_FINISHED`, not retryable). An unknown or expired job is 404 `JOB_NOT_FOUND`.\n          content:\n            application/json:\n              schema: { $ref: '#/components/schemas/ErrorEnvelope' }\n\n  /jobs/{job_id}/stream:\n    get:\n      x-railcore-cost: \"Free (0 requests).\"\n      summary: Stream async job progress with server-sent events\n      tags: [Jobs]\n      parameters:\n        - $ref: '#/components/parameters/pathJobId'\n      responses:\n        '200':\n          description: Progress events followed by one complete or failed event\n          content:\n            text/event-stream:\n              schema:\n                type: string\n                description: \"Named SSE events: progress, complete, and failed.\"\n        '400': { $ref: '#/components/responses/ValidationError' }\n        '404': { $ref: '#/components/responses/NotFound' }\n\n  /jobs:\n    get:\n      x-railcore-cost: \"Free (0 requests).\"\n      summary: List recent async jobs\n      tags: [Jobs]\n      parameters:\n        - { name: status, in: query, required: false, schema: { $ref: '#/components/schemas/JobStatus' }}\n        - { name: type, in: query, required: false, schema: { type: string, enum: [route-scan, hopping] }}\n        - { name: limit, in: query, required: false, schema: { type: integer, minimum: 1, maximum: 100, default: 20 }}\n      responses:\n        '200':\n          description: Compact job lifecycle rows\n          content:\n            application/json:\n              schema:\n                type: object\n                properties:\n                  success: { type: boolean }\n                  data:\n                    type: object\n                    properties:\n                      jobs:\n                        type: array\n                        items: { $ref: '#/components/schemas/Job' }\n                      count: { type: integer }\n                  meta: { $ref: '#/components/schemas/Meta' }\n        '401': { $ref: '#/components/responses/AuthError' }\n        '429': { $ref: '#/components/responses/RateLimited' }\n\ncomponents:\n  securitySchemes:\n    RailCoreKey:\n      type: apiKey\n      in: header\n      name: X-RailCore-Key\n      description: |\n        Every plan. 24+ character opaque key, created under API keys in the developer dashboard: https://railcore.tech/dashboard?view=developer&section=keys. Free and Starter keys send it alone; Growth, Scale and Enterprise keys must also sign (RailCoreKeyWithHmac). The same key can be sent as RailCoreBearer or RailCoreApiKey instead; two headers carrying different keys answer 401 AMBIGUOUS_API_KEY.\n    RailCoreBearer:\n      type: http\n      scheme: bearer\n      description: |\n        The API key as `Authorization: Bearer <key>`, an alternative to `X-RailCore-Key`. Growth, Scale and Enterprise keys must still sign.\n    RailCoreApiKey:\n      type: apiKey\n      in: header\n      name: X-Api-Key\n      description: |\n        The API key in an `X-Api-Key` header, an alternative to `X-RailCore-Key`. Growth, Scale and Enterprise keys must still sign.\n    RailCoreKeyWithHmac:\n      type: apiKey\n      in: header\n      name: X-RailCore-Key\n      description: |\n        Growth, Scale and Enterprise plans require HMAC-SHA256 signing in addition to the API key.\n        Include headers `X-RailCore-Timestamp`, `X-RailCore-Nonce`, and `X-RailCore-Signature`.\n        Keys made before 2026-11-03 have no signing secret: rotate the key in the dashboard to get one.\n        Signature payload: `METHOD\\nPATH\\nCANONICAL_QUERY\\nSHA256(BODY)\\nTIMESTAMP\\nNONCE`, where BODY is the exact bytes of the request body as sent (any JSON formatting) and an empty body hashes zero bytes.\n\n  parameters:\n    queryString:\n      name: q\n      in: query\n      required: true\n      schema: { type: string, minLength: 1, maxLength: 80 }\n    limit:\n      name: limit\n      in: query\n      schema: { type: integer, minimum: 1, maximum: 50, default: 10 }\n    pathStationCode:\n      name: station_code\n      in: path\n      required: true\n      schema: { $ref: '#/components/schemas/StationCode' }\n    pathTrainNumber:\n      name: train_number\n      in: path\n      required: true\n      schema: { $ref: '#/components/schemas/TrainNumber' }\n    pathJobId:\n      name: job_id\n      in: path\n      required: true\n      schema: { type: string, pattern: '^job_[A-Za-z0-9]+$' }\n      description: Job identifier returned by an async submission endpoint.\n\n  headers:\n    AllStandard:\n      X-RailCore-Request-ID:\n        schema: { type: string }\n      X-RailCore-Trace-ID:\n        schema: { type: string }\n      X-RailCore-Plan:\n        schema: { type: string }\n      X-RailCore-RateLimit-Limit:\n        description: The account's per-minute budget, shared by every key on the account. Sent only when the plan has a per-minute limit.\n        schema: { type: integer }\n      X-RailCore-RateLimit-Remaining:\n        description: Requests left in the account's current minute. Sent only when the plan has a per-minute limit.\n        schema: { type: integer }\n      X-RailCore-RateLimit-Reset:\n        description: When the minute resets, in Unix seconds. Sent only when the plan has a per-minute limit.\n        schema: { type: integer }\n      X-RailCore-Credits-Cost:\n        description: What this request counted as. One credit is one request; failed requests use none.\n        schema: { type: integer }\n      X-RailCore-Credits-Remaining:\n        description: Requests left on the account.\n        schema: { type: integer }\n      X-RailCore-Confidence:\n        description: Live-data confidence. On live train status, a finished run whose arrival at its last station was reported is high.\n        schema: { type: string, enum: [high, medium, low] }\n      Server-Timing:\n        description: Where the request spent its time, as `name;dur=milliseconds` entries in the order they ran (for example `key`, `limits`, `credits`, `upstream`), then `total`.\n        schema: { type: string }\n\n  responses:\n    ValidationError:\n      description: Request failed schema validation\n      content:\n        application/json:\n          schema: { $ref: '#/components/schemas/ErrorEnvelope' }\n    AuthError:\n      description: Authentication failed. `MISSING_API_KEY` (no key in `X-RailCore-Key`, `Authorization` or `X-Api-Key`), `AMBIGUOUS_API_KEY` (two headers with different keys), `INVALID_API_KEY`, `API_KEY_DISABLED`, `API_KEY_EXPIRED`, `SIGNATURE_INVALID`, `TIMESTAMP_EXPIRED`, `NONCE_REUSED` or `PLAYGROUND_TOKEN_EXPIRED` (a docs playground token that has expired).\n      content:\n        application/json:\n          schema: { $ref: '#/components/schemas/ErrorEnvelope' }\n    NotFound:\n      description: Resource not found\n      content:\n        application/json:\n          schema: { $ref: '#/components/schemas/ErrorEnvelope' }\n    TrainNotFound:\n      description: \"`TRAIN_NOT_FOUND`: no train has that number. The message names it: `Train 99999 not found. Check the train number.` Not counted.\"\n      content:\n        application/json:\n          schema: { $ref: '#/components/schemas/ErrorEnvelope' }\n    StationNotFound:\n      description: \"`STATION_NOT_FOUND`: no station has that code. The message names it: `Station ZZZZ not found. Check the station code.` Not counted.\"\n      content:\n        application/json:\n          schema: { $ref: '#/components/schemas/ErrorEnvelope' }\n    RateLimited:\n      description: One of the account's rate limits is used up (`RATE_LIMITED`). Limits are shared by every key on the account. Wait for `Retry-After`.\n      content:\n        application/json:\n          schema: { $ref: '#/components/schemas/ErrorEnvelope' }\n    UpstreamError:\n      description: A live-data source failed (UPSTREAM_UNAVAILABLE) or timed out (UPSTREAM_TIMEOUT). Wait for Retry-After, then retry with backoff. Not counted.\n      headers:\n        Retry-After:\n          description: Seconds to wait before retrying.\n          schema: { type: integer, minimum: 0 }\n        X-RailCore-Request-ID:\n          schema: { type: string }\n      content:\n        application/json:\n          schema: { $ref: '#/components/schemas/ErrorEnvelope' }\n    ChartNotReady:\n      description: Chart has not been prepared yet\n      content:\n        application/json:\n          schema: { $ref: '#/components/schemas/ErrorEnvelope' }\n    JobAccepted:\n      description: Async job accepted for processing\n      content:\n        application/json:\n          schema:\n            type: object\n            properties:\n              success: { type: boolean }\n              data:\n                type: object\n                properties:\n                  job_id: { type: string }\n                  status: { type: string, enum: [processing] }\n                  poll_url: { type: string }\n                  stream_url: { type: string }\n                  message: { type: string }\n                  webhook_secret: { type: string, description: \"Present when the job was submitted with a callback_url: the secret that signs this job's callbacks (whsec_...). Shown once and not stored by RailCore.\" }\n              meta: { $ref: '#/components/schemas/Meta' }\n\n  callbacks:\n    JobFinished:\n      '{$request.body#/callback_url}':\n        post:\n          summary: The job's outcome, sent once when it ends\n          description: |\n            Sent to `callback_url` when the job completes or fails. Check the\n            signature before trusting the body: `X-RailCore-Webhook-Signature`\n            is `v1=` and the lower-case hex HMAC-SHA256 of\n            `<X-RailCore-Webhook-Timestamp>.<raw body>`, keyed with the job's\n            `webhook_secret`. Compare it in constant time and refuse a\n            timestamp more than 5 minutes old.\n\n            The address is checked again after its host is resolved, before\n            every send, and redirects are not followed. After a 5xx, 408, 429,\n            timeout (5 seconds) or dropped connection the callback is sent\n            again, 3 more times, after 2, 8 and 30 seconds; any other answer is\n            final. The job's status is saved before the callback is sent, so a\n            poll can see the result first.\n          parameters:\n            - { name: X-RailCore-Webhook-Id, in: header, required: true, description: \"The job id.\", schema: { type: string } }\n            - { name: X-RailCore-Webhook-Timestamp, in: header, required: true, description: \"When this send was signed, in Unix seconds.\", schema: { type: string, pattern: '^[0-9]+$' } }\n            - { name: X-RailCore-Webhook-Attempt, in: header, required: true, description: \"Which send this is.\", schema: { type: integer, minimum: 1, maximum: 4 } }\n            - { name: X-RailCore-Webhook-Signature, in: header, required: true, description: \"`v1=<hex>`: HMAC-SHA256 of `<timestamp>.<raw body>` with the job's webhook_secret.\", schema: { type: string, pattern: '^v1=[0-9a-f]{64}$' } }\n          requestBody:\n            required: true\n            content:\n              application/json:\n                schema:\n                  oneOf:\n                    - type: object\n                      required: [job_id, status, result]\n                      properties:\n                        job_id: { type: string }\n                        status: { type: string, enum: [complete] }\n                        result: { type: object, additionalProperties: true, description: \"The job's result, as polling the job returns it.\" }\n                    - type: object\n                      required: [job_id, status, error]\n                      properties:\n                        job_id: { type: string }\n                        status: { type: string, enum: [failed] }\n                        error: { type: object, additionalProperties: true }\n          responses:\n            '2XX': { description: \"Received. The callback is settled as sent.\" }\n            '5XX': { description: \"Sent again, up to 3 more times. 408 and 429 are sent again too; any other status is final.\" }\n\n  schemas:\n    StationCode:\n      type: string\n      pattern: '^[A-Z0-9]{1,6}$'\n      example: BSL\n    TrainNumber:\n      type: string\n      pattern: '^[0-9A-Z]{4,6}$'\n      example: '12656'\n    ClassCode:\n      type: string\n      enum: [1A, 2A, 3A, 3E, CC, EC, SL, 2S, GS, GEN, SLR, PC, HP, GEN_RSVD, FC, UNKNOWN]\n    Quota:\n      type: string\n      enum: [GN, TQ, PT, LD, SS, HP, DP, HO, YU, FT]\n    RunningDay:\n      type: string\n      enum: [MON, TUE, WED, THU, FRI, SAT, SUN]\n\n    JobStatus:\n      type: string\n      enum: [pending, processing, complete, failed, cancelled]\n\n    RouteScanJobInput:\n      type: object\n      required: [from, to, date]\n      properties:\n        from: { type: string, description: \"Station code or name.\" }\n        to: { type: string, description: \"Station code or name.\" }\n        date: { type: string, format: date }\n        quota: { $ref: '#/components/schemas/Quota' }\n        max_trains: { type: integer, minimum: 1, maximum: 100, default: 100 }\n        min_score: { type: number, minimum: 0, maximum: 100, default: 0 }\n        only_running: { type: boolean, default: true }\n        only_chart_prepared: { type: boolean, default: false }\n        sort_by: { type: string, enum: [departure, departure_desc, duration, score, chart_ready], default: departure }\n        include_detail: { type: boolean, default: true }\n        train_types: { type: string, description: \"Comma-separated allow list.\" }\n        avoid_train_types: { type: string, description: \"Comma-separated deny list.\" }\n        max_hops: { type: integer, minimum: 1, maximum: 12, default: 6 }\n        prefer_berth: { type: string }\n        avoid_berth: { type: string }\n        prefer_class: { type: string }\n        avoid_class: { type: string }\n        include_fare: { type: boolean, default: false }\n        include_alternate_boarding: { type: boolean, default: false }\n        strategies: { type: string }\n        alternate_boarding_mode: { type: string, enum: [lightweight, extended], default: lightweight }\n        alternate_boarding_max_candidates: { type: integer, minimum: 1, maximum: 5, default: 3 }\n        include_cross_class: { type: boolean, default: false }\n        callback_url: { type: string, format: uri, maxLength: 2048, description: \"Where to POST the job's outcome when it finishes (see the JobFinished callback). An https URL on a public host, port 443 or 1024 and up, without a user name or password. localhost, private, link-local, CGNAT and metadata addresses are refused with 400 VALIDATION_ERROR (details[].field callback_url) when the job is submitted, and the host is checked again after it is resolved, before every send. Redirects are not followed.\" }\n\n    HoppingJobInput:\n      type: object\n      required: [train_number, from, to, date]\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        from: { $ref: '#/components/schemas/StationCode' }\n        to: { $ref: '#/components/schemas/StationCode' }\n        date: { type: string, format: date }\n        quota: { $ref: '#/components/schemas/Quota' }\n        via: { type: string, description: \"Comma-separated station codes.\" }\n        max_hops: { type: integer, minimum: 1, maximum: 12, default: 6 }\n        prefer_berth: { type: string }\n        avoid_berth: { type: string }\n        prefer_class: { type: string }\n        avoid_class: { type: string }\n        include_fare: { type: boolean, default: false }\n        include_alternate_boarding: { type: boolean, default: false }\n        include_cross_class: { type: boolean, default: false }\n        strategies: { type: string }\n        callback_url: { type: string, format: uri, maxLength: 2048, description: \"Where to POST the job's outcome when it finishes (see the JobFinished callback). An https URL on a public host, port 443 or 1024 and up, without a user name or password. localhost, private, link-local, CGNAT and metadata addresses are refused with 400 VALIDATION_ERROR (details[].field callback_url) when the job is submitted, and the host is checked again after it is resolved, before every send. Redirects are not followed.\" }\n\n    Job:\n      type: object\n      properties:\n        job_id: { type: string }\n        status: { $ref: '#/components/schemas/JobStatus' }\n        type: { type: string, enum: [route-scan, hopping] }\n        created_at: { type: string, format: date-time }\n        completed_at: { type: string, format: date-time }\n        progress: { type: string }\n        callback_status: { type: string, enum: [pending, sent, failed, not_configured], description: \"not_configured: no callback_url. pending: the callback is not settled yet (the job's status is saved before the callback is sent, so a poll can see the result first). sent: the receiver answered 2xx. failed: it never did, an answer was final, or the address was refused.\" }\n        callback_attempts: { type: integer, minimum: 0, maximum: 4, description: \"How many times the callback was sent. Present once it is settled.\" }\n        data: { type: object, additionalProperties: true }\n        error:\n          type: object\n          properties:\n            code: { type: string }\n            message: { type: string }\n\n    EnvelopeJob:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/Job' }\n        meta: { $ref: '#/components/schemas/Meta' }\n\n    Meta:\n      type: object\n      required: [api_version, request_id, trace_id, timestamp]\n      properties:\n        api_version: { type: string, example: v1 }\n        request_id:  { type: string, example: req_01HXYZABC }\n        trace_id:    { type: string, example: trc_01HXYZABC }\n        timestamp:   { type: string, format: date-time }\n        freshness:\n          type: object\n          properties:\n            mode: { type: string, enum: [live] }\n            retrieved_at: { type: string, format: date-time }\n            sources:\n              type: array\n              items:\n                type: object\n                properties:\n                  confidence: { type: string, enum: [high, medium, low] }\n                  last_reported_at: { type: string, format: date-time }\n\n    ErrorEnvelope:\n      type: object\n      required: [success, error, meta]\n      properties:\n        success: { type: boolean, example: false }\n        error:\n          type: object\n          required: [code, message, category, retryable]\n          properties:\n            code:     { type: string, example: STATION_NOT_FOUND }\n            message:  { type: string }\n            category: { type: string, enum: [VALIDATION, AUTH, QUOTA, RATE_LIMIT, UPSTREAM, INTERNAL, NOT_FOUND, FORBIDDEN] }\n            retryable: { type: boolean }\n            details:\n              type: array\n              description: On a 400 VALIDATION_ERROR, one entry per problem.\n              items:\n                type: object\n                properties:\n                  field: { type: string, description: \"The parameter or body field, for example date, items[2].date, match or callback_url.\" }\n                  issue: { type: string }\n        meta: { $ref: '#/components/schemas/Meta' }\n\n    Station:\n      type: object\n      properties:\n        station_code: { $ref: '#/components/schemas/StationCode' }\n        station_name: { type: string }\n        display_name: { type: string }\n        city: { type: [string, \"null\"] }\n        state: { type: [string, \"null\"] }\n        country: { type: string, default: \"IN\" }\n        latitude: { type: [number, \"null\"] }\n        longitude: { type: [number, \"null\"] }\n        aliases: { type: array, items: { type: string }}\n        is_major: { type: boolean }\n        confidence: { type: number, minimum: 0, maximum: 1 }\n\n    Train:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        train_name: { type: string }\n        display_name: { type: string }\n        source_station_code: { $ref: '#/components/schemas/StationCode' }\n        destination_station_code: { $ref: '#/components/schemas/StationCode' }\n        train_type: { type: string }\n        running_days: { type: array, items: { $ref: '#/components/schemas/RunningDay' }}\n\n    ScheduleStop:\n      type: object\n      description: A station on the train's route. No field is null; one the timetable has no value for is left out.\n      properties:\n        sequence: { type: integer }\n        station_code: { $ref: '#/components/schemas/StationCode' }\n        station_name: { type: string, description: \"Written as the RailCore site writes it (New Delhi, Mumbai Central), not the upper-case booking name.\" }\n        stop_type: { type: string, enum: [ORIGIN, HALT, PASSING, DESTINATION], description: \"What the station is to the train. ORIGIN: the train starts here. DESTINATION: it ends here. HALT: it stops. PASSING: it runs through without stopping (listed by /route, and by /schedule with include_intermediate=true).\" }\n        notes:\n          type: object\n          description: \"At the first and last stations only: in place of the time the train does not have there.\"\n          properties:\n            arrival: { type: string, description: \"At the ORIGIN, for example `Starts at Mumbai Central: departs only, no arrival`.\" }\n            departure: { type: string, description: \"At the DESTINATION, for example `Ends at New Delhi: arrives only, no departure`.\" }\n        arrival_time: { type: string, description: \"Booked arrival, HH:MM in India. Left out at the ORIGIN, where the train does not arrive (from November 12 to 13, 2026 it carried the departure time).\" }\n        departure_time: { type: string, description: \"Booked departure, HH:MM in India. Left out at the DESTINATION, where the train does not leave (from November 12 to 13, 2026 it carried the arrival time).\" }\n        halt_minutes: { type: integer, description: \"Booked halt. 0 at the origin, the destination and a passing station.\" }\n        day: { type: integer }\n        distance_km: { type: number, description: \"From the first station, in km. At a halt, the railway timetable's whole kilometres; at a passing station, worked out to 0.1 km.\" }\n        platform_number: { type: string, description: \"The platform the timetable names. Left out where it names none, and at a station the train runs through.\" }\n        latitude: { type: number }\n        longitude: { type: number }\n        typical_arrival_delay_minutes:\n          type: integer\n          description: Typical arrival delay at this stop in minutes, from a fixed delay profile. The same on every date and every request, never a live reading. Left out when there is no profile for the stop, and at a station the train runs through. For live delay, use /trains/{train_number}/live.\n        typical_departure_delay_minutes:\n          type: integer\n          description: Typical departure delay at this stop in minutes, from the same fixed delay profile, and left out with it. Not live.\n        arrival_delay_minutes:\n          type: integer\n          deprecated: true\n          description: Deprecated alias of typical_arrival_delay_minutes, with the same value and left out with it. Not live delay. Removed no earlier than 2026-12-07 (30 days after the 2026-11-07 notice).\n        departure_delay_minutes:\n          type: integer\n          deprecated: true\n          description: Deprecated alias of typical_departure_delay_minutes, with the same value and left out with it. Not live delay. Removed no earlier than 2026-12-07 (30 days after the 2026-11-07 notice).\n        is_stop: { type: boolean }\n\n    TrainSchedule:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        train_name: { type: string }\n        source_station_code: { $ref: '#/components/schemas/StationCode' }\n        destination_station_code: { $ref: '#/components/schemas/StationCode' }\n        running_days: { type: array, items: { $ref: '#/components/schemas/RunningDay' }}\n        classes: { type: array, items: { $ref: '#/components/schemas/ClassCode' }, description: \"Classes the train carries, highest first, from RailCore's train catalog. GS is the unreserved general class. Empty only for a train the catalog has no classes for.\" }\n        total_duration_minutes: { type: integer }\n        distance_km: { type: number }\n        catering: { type: boolean, description: \"Whether food can be ordered on the train. Left out until RailCore has read the train's extras; the next request has them.\" }\n        pantry: { type: boolean, description: \"Whether the train carries a pantry car. Left out until RailCore has read the train's extras.\" }\n        rake_type: { type: string, description: \"Coach build, for example LHB or ICF. Left out until RailCore has read the train's extras.\" }\n        valid_from: { type: string, format: date, description: \"First day this timetable applies. Present only when the railway dated it.\" }\n        valid_to: { type: string, format: date, description: \"Last day this timetable applies. Present only when the railway dated it; most timetables have no end date.\" }\n        stops: { type: array, items: { $ref: '#/components/schemas/ScheduleStop' }}\n\n    CoachSlot:\n      type: object\n      properties:\n        sequence: { type: integer, description: \"Row number in this list, from 1.\" }\n        coach_name: { type: string, description: \"The coach's label, for example B1. ENG for the locomotive.\" }\n        class_code: { type: string, description: \"The coach's class (a ClassCode value), LOCO for the locomotive, or the vehicle's own code where it has no travel class (LPR or EOG for a power car, VP for a parcel van).\" }\n        class_name: { type: string, description: \"The class or vehicle in words, for example Third AC, General (unreserved), Pantry car, Power car, Generator car, Locomotive.\" }\n        coach_type: { type: string, enum: [LOCOMOTIVE, RESERVED, UNRESERVED, PANTRY, LUGGAGE_BRAKE, POWER_CAR, PARCEL, OTHER], description: \"What the vehicle is for. RESERVED: seats or berths booked in a class. UNRESERVED: general coaches.\" }\n        position_from_engine: { type: integer, description: \"Place in the rake counted from the front. The locomotive is 1 and the first coach 2; on a self-propelled set the first coach is 1. Every vehicle is listed, power cars included, so the numbers run without a gap (until 2026-11-13 power cars were left out).\" }\n        is_locomotive: { type: boolean, description: \"True for a locomotive row, false for a coach.\" }\n        locomotive_end: { type: string, enum: [FRONT, REAR], description: \"On a locomotive row only: which end of the rake it is at. A push-pull train has one of each.\" }\n\n    CoachPositionStation:\n      type: object\n      properties:\n        code: { $ref: '#/components/schemas/StationCode' }\n        name: { type: string, description: \"The station's name written out in full.\" }\n\n    CoachClassSummary:\n      type: object\n      properties:\n        class_code: { type: string }\n        class_name: { type: string }\n        coach_type: { type: string }\n        coaches: { type: integer, minimum: 1, description: \"How many vehicles of this class the rake has. 1 for the locomotive, 2 on a push-pull train.\" }\n\n    CoachReversalStation:\n      type: object\n      properties:\n        station_code: { $ref: '#/components/schemas/StationCode' }\n        station_name: { type: string, description: \"The station's name written out in full.\" }\n\n    CoachPosition:\n      type: object\n      description: The train's rake from the front. The train's own details (name, type, stations, rake type) are left out on the rare request that RailCore could not read its catalog in time.\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        train_name: { type: string, description: \"The train's name from RailCore's train catalog.\" }\n        train_type: { type: string, description: \"Category code, for example SF or RAJDHANI.\" }\n        source_station: { $ref: '#/components/schemas/CoachPositionStation' }\n        destination_station: { $ref: '#/components/schemas/CoachPositionStation' }\n        rake_type: { type: string, enum: [LHB, ICF, TRAINSET], description: \"Coach build. TRAINSET for a self-propelled set.\" }\n        has_locomotive: { type: boolean, description: \"True for a loco-hauled train, whose list starts with the locomotive. False for a self-propelled set (Vande Bharat, MEMU, DEMU, EMU), which has no locomotive row.\" }\n        locomotives: { type: integer, enum: [0, 1, 2], description: \"Locomotive rows in the list: 0 for a self-propelled set, 1 for a loco-hauled train, 2 for a push-pull train.\" }\n        push_pull: { type: boolean, description: \"True for a push-pull train: a locomotive at each end of the rake, so the list starts and ends with a locomotive row. Indian Railways publishes no list of such trains; RailCore marks one on evidence and says which in push_pull_basis. A train that is not marked may still be worked push-pull.\" }\n        push_pull_basis: { type: string, enum: [train_design, railway_announcement, rake_composition], description: \"Present when push_pull is true: what the mark rests on. train_design: the train is an Amrit Bharat Express, built as a push-pull rake. railway_announcement: the railway announced push-pull working for this train. rake_composition: the train's coach composition, refreshed every 15 minutes, lists a locomotive at each end.\" }\n        total_coaches: { type: integer, minimum: 0, description: \"Coaches in the list, not counting locomotives or power cars.\" }\n        power_cars: { type: integer, minimum: 0, description: \"Power cars (LPR, EOG) in the list, each a row with coach_type POWER_CAR. Listed in their places since 2026-11-13; they used to be left out.\" }\n        total_vehicles: { type: integer, minimum: 0, description: \"Every row in the list: locomotives, coaches and power cars.\" }\n        formation: { type: string, description: \"The rake written out from the front, for example ENG-SLRD-GEN-S5-S4-PC-B1-A1-H1-GEN. A push-pull train's ends with ENG too.\" }\n        class_summary: { type: array, items: { $ref: '#/components/schemas/CoachClassSummary' }, description: \"The rake counted by class, in rake order. On a loco-hauled train the first entry is the locomotive (class_code LOCO, coaches 1; 2 on a push-pull train). Power cars are counted too, so the counts add up to total_vehicles.\" }\n        reversal_stations: { type: array, items: { $ref: '#/components/schemas/CoachReversalStation' }, description: \"Stations where the engine changes ends, so the coach order is the other way round from there on. Empty when RailCore knows of none.\" }\n        coach_position: { type: array, items: { $ref: '#/components/schemas/CoachSlot' }, description: \"The rake from the front: the locomotive first on a loco-hauled train, then every coach, then the second locomotive on a push-pull train.\" }\n\n    StationBoardTrain:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        train_name: { type: string, description: \"The name the live feed gives, often abbreviated (`GKP DR EXP`). When the feed's first or last station is not the train's in RailCore's train catalog, the feed's row was for another train with the same number, and this is the catalog's name.\" }\n        extended_train_name: { type: string, description: \"The train's full name from RailCore's train catalog (`Dadar Central Express`). The same as `train_name` for a train the catalog does not list.\" }\n        source_station_code: { allOf: [{ $ref: '#/components/schemas/StationCode' }], description: \"The train's first station, from RailCore's train catalog when it lists the train (it wins over the live feed, which reuses numbers for other local trains).\" }\n        destination_station_code: { allOf: [{ $ref: '#/components/schemas/StationCode' }], description: \"The train's last station, from the train catalog when it lists the train.\" }\n        source_station_name: { type: string, description: \"The first station's name written out in full (`Chhatrapati Shivaji Maharaj Terminus`, not the booking name `C SHIVAJI MAH T`).\" }\n        destination_station_name: { type: string, description: \"The last station's name written out in full.\" }\n        train_type: { type: string }\n        scheduled_arrival: { type: string, format: date-time, description: \"Booked arrival at the station, India time. Left out at the train's origin; notes.arrival says why.\" }\n        scheduled_departure: { type: string, format: date-time, description: \"Booked departure, India time. A departure after midnight is dated the next day. Left out at the train's destination; notes.departure says why.\" }\n        estimated_arrival: { type: string, format: date-time, description: \"Latest expected arrival. Before the live feed forecasts the train, the booked time (timing_basis scheduled).\" }\n        estimated_departure: { type: string, format: date-time, description: \"Before the live feed forecasts a train that has not started, the booked time (timing_basis scheduled).\" }\n        timing_basis: { type: string, enum: [live, scheduled], description: \"live: the expected times come from the live feed. scheduled: no forecast yet, so they are the booked times, with a delay of 0.\" }\n        rescheduled_minutes: { type: integer, minimum: 15, description: \"How far the railway moved a train that has not started yet, worked out from the gap between its booked and expected times that its delay does not explain. Its delay counts from the new time.\" }\n        platform_basis: { type: string, enum: [announced, expected, usual], description: \"platform_basis says where the platform comes from: announced (the live station board names it), expected (not on the board yet; the railway's running status of this run names it) or usual (neither does; the train's usual platform from the timetable, not confirmed for today). They can differ: on 2026-11-12 64114's usual platform at NDLS was 11 and its expected one 10.\" }\n        platform_number: { type: string, description: \"Left out until a platform is announced; notes.platform says so.\" }\n        arrival_delay_minutes: { type: integer, description: \"Minutes late arriving. 0 when the expected time is the booked one (timing_basis scheduled).\" }\n        departure_delay_minutes: { type: integer, description: \"Minutes late leaving. For a rescheduled train, counted from the new time.\" }\n        scheduled_halt_minutes: { type: integer }\n        actual_halt_minutes: { type: integer, description: \"Left out until observed; notes.halt says why.\" }\n        start_date: { type: string, format: date }\n        status: { type: string, enum: [NOT_STARTED, ON_ROUTE, AT_STATION, ARRIVED, DEPARTED, SEVERELY_DELAYED, CANCELLED, DIVERTED, UNKNOWN] }\n        current_station_code: { allOf: [{ $ref: '#/components/schemas/StationCode' }], description: \"Where the train is. For a train that has not started, its first station.\" }\n        departed_current_station: { type: boolean, description: \"Whether the train has left current_station_code. false for a train that has not started.\" }\n        stop_type: { type: string, enum: [ORIGIN, INTERMEDIATE, DESTINATION] }\n        cancellation: { $ref: '#/components/schemas/LiveTrainCancellation' }\n        confidence: { type: string, enum: [high, medium, low] }\n        last_reported_at: { type: string, format: date-time, description: \"Left out before the train has been reported; notes.last_reported says so.\" }\n        notes:\n          type: object\n          description: \"In place of a field that has no value, why not. A time field only ever holds a real time; when one is missing, the note for its group says why. Present only with at least one note.\"\n          properties:\n            arrival: { type: string, description: \"Why there is no arrival here, for example `Starts at New Delhi: departs only, no arrival`.\" }\n            departure: { type: string, description: \"Why there is no departure here, for example `Ends at New Delhi: arrives only, no departure`.\" }\n            halt: { type: string, description: \"Why there is no halt time: the train starts or ends here, or has not stopped here yet.\" }\n            platform: { type: string, description: \"`Platform not announced yet` when no source names one; with platform_basis expected, `Expected platform from the running status: not announced on the board yet`; with usual, `Usual platform from the timetable: not announced for today yet`.\" }\n            last_reported: { type: string, description: \"`Not reported yet`, or `Not reported yet: the train has not started`.\" }\n            position: { type: string, description: \"`Not started yet: at its first station, <name>` (current_station_code is then that station), or `Position not reported yet`.\" }\n            expected: { type: string, description: \"`No live forecast yet: the expected times are the booked ones` when the expected times were filled from the timetable (timing_basis scheduled).\" }\n            rescheduled: { type: string, description: \"For example `Rescheduled by 6 h 20 min: now departs at 01:30 on 13 Nov`.\" }\n\n    StationBoard:\n      type: object\n      description: No field is null; one with no value is left out (since 2026-11-13).\n      properties:\n        station_code: { $ref: '#/components/schemas/StationCode' }\n        window_hours: { type: integer, enum: [4, 8], description: \"How far ahead the board looks, in hours from now.\" }\n        window:\n          type: object\n          description: The bounds the board was cut to, as India-time instants (+05:30). A train is listed when any of its times at the station, expected or booked, arriving or leaving, falls between from and to.\n          properties:\n            from: { type: string, format: date-time, description: \"2 hours before the request.\" }\n            to: { type: string, format: date-time, description: \"window_hours after the request.\" }\n            hours_back: { type: integer, enum: [2] }\n            hours_ahead: { type: integer, enum: [4, 8] }\n        trains: { type: array, items: { $ref: '#/components/schemas/StationBoardTrain' }}\n\n    StationBoardCancellation:\n      type: object\n      required: [fully_cancelled]\n      properties:\n        fully_cancelled:\n          type: boolean\n          description: True only when the complete train run is cancelled.\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code: { $ref: '#/components/schemas/StationCode' }\n\n    LiveTrainStop:\n      type: object\n      description: A station on the run. No field is null; one with nothing to report is left out.\n      properties:\n        sequence: { type: integer, minimum: 0, description: \"Position on the route, from 1.\" }\n        station_code: { $ref: '#/components/schemas/StationCode' }\n        station_name: { type: string, description: \"Written as the RailCore site writes it (New Delhi, Mumbai Central), not the upper-case booking name.\" }\n        stop_type: { type: string, enum: [ORIGIN, HALT, PASSING, DESTINATION], description: \"What the station is to this run. ORIGIN has no arrival fields and DESTINATION no departure fields. PASSING is a station the train runs through: it has booked times and a worked-out time, but no platform.\" }\n        scheduled_arrival: { type: string, format: date-time, description: \"Timetabled arrival. At a passing station, the booked time the train runs through. Left out at the ORIGIN.\" }\n        scheduled_departure: { type: string, format: date-time, description: \"Timetabled departure. Left out at the DESTINATION.\" }\n        eta: { type: string, format: date-time, description: \"When the train reaches the station: the expected time while it is ahead, the actual arrival once the train has been there. Left out at the ORIGIN, with delay_arrival_minutes (until 2026-11-13 they copied the departure). timing_basis says where the time comes from.\" }\n        etd: { type: string, format: date-time, description: \"When the train leaves the station: the expected time while it is ahead, the actual departure once it has left. Left out at the DESTINATION, with delay_departure_minutes (until 2026-11-13 they copied the arrival).\" }\n        timing_basis: { type: string, enum: [reported, predicted, estimated, scheduled, cancelled], description: \"Where eta and etd come from. reported: the train was reported at the station. predicted: the live feed's forecast. estimated: RailCore worked at least one of the two out, from the delay at the timed stations either side (the feed times halts only, and not always both ends of one). scheduled: nothing on the run is timed yet, so the booked time stands. cancelled: the run is cancelled and the station has no eta, etd or delay.\" }\n        actual_arrival: { type: string, format: date-time, description: \"Reported arrival. Present once the train has been reported arriving here; never at the ORIGIN.\" }\n        actual_departure: { type: string, format: date-time, description: \"Reported departure. Present once the train has been reported leaving here; never at the DESTINATION.\" }\n        delay_arrival_minutes: { type: integer, description: \"Minutes late arriving, eta against scheduled_arrival. Negative when early. Left out at the ORIGIN.\" }\n        delay_departure_minutes: { type: integer, description: \"Minutes late leaving, etd against scheduled_departure. Negative when early. Left out at the DESTINATION.\" }\n        platform_number: { type: string, description: \"Expected platform. Platforms can change at short notice. Left out where none is named, and at a station the train runs through.\" }\n        halt_minutes: { type: integer, minimum: 0, description: \"Booked halt in minutes.\" }\n        day: { type: integer, minimum: 1, description: \"Day of the run; 1 is the day it starts.\" }\n        distance_km: { type: number, minimum: 0, description: \"Distance from the first station.\" }\n        is_stopping: { type: boolean, description: \"False for a station the train passes without stopping.\" }\n        is_diverted: { type: boolean, description: \"True for a station on a diversion rather than the booked route.\" }\n        has_arrived: { type: boolean, description: \"Whether the train has reached this station.\" }\n        has_departed: { type: boolean, description: \"Whether the train has left this station.\" }\n        travelled: { type: boolean, description: \"Whether the train has covered this station.\" }\n        latitude: { type: number, minimum: -90, maximum: 90 }\n        longitude: { type: number, minimum: -180, maximum: 180 }\n        last_reported_at: { type: string, format: date-time, description: \"When the train was last reported at this station. Present once it has been.\" }\n        notes:\n          type: object\n          description: \"At the first and last stations only: in place of the time the train does not have there.\"\n          properties:\n            arrival: { type: string, description: \"At the ORIGIN, for example `Starts at Mumbai Central: departs only, no arrival`.\" }\n            departure: { type: string, description: \"At the DESTINATION, for example `Ends at New Delhi: arrives only, no departure`.\" }\n\n    LiveTrainCancellation:\n      type: object\n      description: Whether the run is cancelled. Always an object, never null; read status.\n      required: [status, fully_cancelled, message]\n      properties:\n        status: { type: string, enum: [NOT_CANCELLED, PARTIALLY_CANCELLED, CANCELLED], description: \"NOT_CANCELLED: nothing is cancelled. PARTIALLY_CANCELLED: the section between from_station_code and to_station_code does not run. CANCELLED: the whole run.\" }\n        fully_cancelled: { type: boolean, description: \"True only when the whole run is cancelled.\" }\n        message: { type: string, description: \"The same in words, for example No cancellation reported for this run.\" }\n        from_station_code: { allOf: [{ $ref: '#/components/schemas/StationCode' }], description: \"First station of the section that does not run. Left out when nothing is cancelled.\" }\n        to_station_code: { allOf: [{ $ref: '#/components/schemas/StationCode' }], description: \"Last station of the section that does not run. Left out when nothing is cancelled.\" }\n\n    LiveTrainFreshness:\n      type: object\n      required: [railcore_cache, retrieved_at, state]\n      properties:\n        railcore_cache: { type: string, enum: [bypassed, reused], description: \"bypassed: read from the live feed for this request. reused: RailCore's read of the same run made within max_age seconds; retrieved_at says when.\" }\n        retrieved_at: { type: string, format: date-time, description: \"When RailCore read the live feed.\" }\n        last_reported_at: { type: string, format: date-time, description: \"The report time the live feed gave back. Left out before the run has been reported.\" }\n        age_seconds: { type: integer, minimum: 0, description: \"Age of that report. Left out with last_reported_at.\" }\n        state: { type: string, enum: [fresh, aging, stale, unknown], description: \"What the report's age makes it.\" }\n        upstream_served_from_cache: { type: boolean, description: \"True when the live feed said it answered from its own cache. Present only when the feed says; it is left out otherwise.\" }\n\n    LiveTrainOfficialNotice:\n      type: object\n      description: What the railway's own running status says differs from the timetable.\n      properties:\n        checked_at: { type: string, format: date-time, description: \"When RailCore last read the railway's running status for this run.\" }\n        reason: { type: string, description: \"The railway's reason, in its own words.\" }\n        message: { type: string, description: \"The railway's notice, in its own words.\" }\n        new_source_station_code: { $ref: '#/components/schemas/StationCode' }\n        new_destination_station_code: { $ref: '#/components/schemas/StationCode' }\n        new_departure: { type: string, format: date-time, description: \"When the run now leaves its first station. Tentative.\" }\n        new_arrival: { type: string, format: date-time, description: \"When a run cut short now reaches its new last station.\" }\n        diverted: { type: boolean, description: \"Whether the train runs on a diversion.\" }\n\n    LiveTrainStatus:\n      type: object\n      description: Where a run stands. No field is null, at any depth; one with nothing to report is left out (a train that has not started has no last_reported_at, for example).\n      required: [train_number, journey_date, status, stations, freshness]\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        train_name: { type: string, description: \"The train's published name.\" }\n        journey_date: { type: string, format: date, description: \"The day the run left, or leaves, its first station: the date asked for, or, without date, the run RailCore picked.\" }\n        source_station_code: { $ref: '#/components/schemas/StationCode' }\n        destination_station_code: { $ref: '#/components/schemas/StationCode' }\n        train_type: { type: string, description: \"Category code, for example SF or RAJDHANI: the live feed's, else RailCore's train catalog's. Left out only for a train the catalog does not have.\" }\n        train_type_label: { type: string, description: \"Readable category, for example superfast. Left out only when train_type is.\" }\n        travel_classes: { type: array, items: { type: string, pattern: '^[A-Z0-9]{1,4}$' }, description: \"Classes the train carries: the live feed's, else the train catalog's.\" }\n        scheduled_duration_minutes: { type: integer, minimum: 0, description: \"Timetabled time from first to last station.\" }\n        started_at: { type: string, format: date-time, description: \"When the train actually left its first station. Left out before it leaves.\" }\n        start_date: { type: string, format: date, description: \"The run's start date as the live feed gives it.\" }\n        status: { type: string, enum: [NOT_STARTED, RUNNING, AT_STATION, COMPLETED, CANCELLED, DIVERTED, UNKNOWN], description: \"Where the run stands. CANCELLED means the whole run; a part cancellation stays RUNNING or AT_STATION and is in cancellation.\" }\n        status_text: { type: string, description: \"A ready-to-show line, for example Running 22 minutes late.\" }\n        current_station_code: { $ref: '#/components/schemas/StationCode' }\n        current_station_name: { type: string, description: \"The station the train is at, or the last one it passed, written as the RailCore site writes it (New Delhi).\" }\n        previous_station_code: { $ref: '#/components/schemas/StationCode' }\n        previous_station_name: { type: string, description: \"The halt behind the train, written as the RailCore site writes it. Left out when the live feed names none.\" }\n        next_station_code: { $ref: '#/components/schemas/StationCode' }\n        approaching_station_code: { $ref: '#/components/schemas/StationCode' }\n        approaching_station_name: { type: string, description: \"The next station on the line ahead, even one the train will pass without stopping, written as the RailCore site writes it.\" }\n        distance_from_current_station_km: { type: number, minimum: 0, description: \"How far the train is past the current station. Left out when the position is not precise enough.\" }\n        distance_to_approaching_station_km: { type: number, minimum: 0, description: \"How far the train is short of the approaching station. Left out when the position is not precise enough.\" }\n        latitude: { type: number, minimum: -90, maximum: 90, description: \"The train's last reported position.\" }\n        longitude: { type: number, minimum: -180, maximum: 180, description: \"The train's last reported position.\" }\n        position_anchor_station_code: { $ref: '#/components/schemas/StationCode' }\n        progress_percent: { type: number, minimum: 0, maximum: 100, description: \"Share of the route covered.\" }\n        distance_covered_km: { type: number, minimum: 0, description: \"Distance covered so far.\" }\n        total_distance_km: { type: number, minimum: 0, description: \"Length of the route.\" }\n        speed_kmph: { type: number, minimum: 0, maximum: 160, description: \"RailCore's own figure, not a locomotive reading: the average speed from the last station the train was timed at to its latest reported position. 0 while it stands at a station, before it starts and after it ends. Left out only when speed_basis is unavailable.\" }\n        speed_basis: { type: string, enum: [average_since_last_report, stationary, unavailable], description: \"How speed_kmph was worked out. unavailable: the run has no timed point at least two minutes old to measure from.\" }\n        delay_minutes: { type: integer, description: \"How late the train is at the last station it reached. Negative when early.\" }\n        eta_destination_at: { type: string, format: date-time, description: \"Expected arrival at the last station; the actual time once complete. Left out for a cancelled run.\" }\n        rescheduled_minutes: { type: integer, minimum: 0, description: \"How far the railway moved the run's start, in minutes. 0 when the start was not moved.\" }\n        last_reported_at: { type: string, format: date-time, description: \"When the live feed last reported this train.\" }\n        confidence: { type: string, enum: [high, medium, low], description: \"How far to trust the answer, from its age and source. A finished run whose arrival at its last station was reported is high, as is X-RailCore-Confidence.\" }\n        cancellation: { $ref: '#/components/schemas/LiveTrainCancellation' }\n        official_notice:\n          description: What the railway reports differs from the timetable. Present only when it reports a difference.\n          allOf:\n            - { $ref: '#/components/schemas/LiveTrainOfficialNotice' }\n        next_stop:\n          description: The next station the train halts at. Left out once there is none.\n          allOf:\n            - { $ref: '#/components/schemas/LiveTrainStop' }\n        stations: { type: array, items: { $ref: '#/components/schemas/LiveTrainStop' }, description: \"Every station on the route in order, including the ones the train passes without stopping.\" }\n        freshness: { $ref: '#/components/schemas/LiveTrainFreshness' }\n\n    AvailabilityMini:\n      type: object\n      properties:\n        class_code: { $ref: '#/components/schemas/ClassCode' }\n        status: { type: string, enum: [AVAILABLE, RAC, WAITLIST, REGRET, NOT_AVAILABLE, TRAIN_CANCELLED, TRAIN_DEPARTED, UNKNOWN] }\n        text: { type: string }\n        fare: { type: [integer, \"null\"] }\n        confidence: { type: string, enum: [high, medium, low] }\n        last_updated_at: { type: [string, \"null\"], format: date-time, description: \"When the figure was read, in India time with its offset (+05:30). It can be days old: this is a summary, not a fresh enquiry.\" }\n\n    RouteTrain:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        train_name: { type: string }\n        extended_train_name: { type: string, description: \"The train's full name from RailCore's train catalog (`Navjeevan SF Express`), where `train_name` is the short name printed on reservation charts (`NAVJEEVAN SF EXP`). The same as `train_name` for a train the catalog does not list.\" }\n        from_station_code: { allOf: [{ $ref: '#/components/schemas/StationCode' }], description: \"Where this train is boarded. With match=city, a station of the from city that need not be the one asked for.\" }\n        from_station_name: { type: string }\n        to_station_code: { allOf: [{ $ref: '#/components/schemas/StationCode' }], description: \"Where this train is left. With match=city, a station of the to city that need not be the one asked for.\" }\n        to_station_name: { type: string }\n        departure_time: { type: string }\n        arrival_time: { type: string }\n        duration_minutes: { type: integer }\n        distance_km: { type: [number, \"null\"] }\n        train_type: { type: string }\n        classes: { type: array, items: { $ref: '#/components/schemas/ClassCode' }}\n        running_days: { type: array, items: { $ref: '#/components/schemas/RunningDay' }}\n        has_pantry: { type: [boolean, \"null\"] }\n        availability_summary: { type: array, items: { $ref: '#/components/schemas/AvailabilityMini' }}\n\n    RouteTrains:\n      type: object\n      properties:\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code: { $ref: '#/components/schemas/StationCode' }\n        journey_date: { type: string, format: date }\n        quota: { $ref: '#/components/schemas/Quota' }\n        matched_by: { type: string, enum: [station, city], description: \"station: every train runs between the two stations asked for. city: some run between other stations of the same two cities (see each train's from_station_code and to_station_code).\" }\n        trains: { type: array, items: { $ref: '#/components/schemas/RouteTrain' }}\n\n    ConfirmationProbability:\n      type: [object, \"null\"]\n      description: \"The chance that a ticket booked now is confirmed. 100 (`Available`) when seats are available; 0 with the reason in `text` when no ticket can be booked (`Waitlist full (regret)` for a REGRET class: the waitlist is full, which is not the same as booking closed; not available; train departed or cancelled); the forecast for a waitlisted or RAC ticket. Null only for a waitlisted or RAC class the forecast does not cover.\"\n      properties:\n        percentage: { type: number, minimum: 0, maximum: 100 }\n        label: { type: string, enum: [LOW, MEDIUM, HIGH] }\n        text: { type: string }\n\n    AvailabilityDetail:\n      type: object\n      properties:\n        class_code: { $ref: '#/components/schemas/ClassCode' }\n        status: { type: string, enum: [AVAILABLE, RAC, WAITLIST, REGRET, NOT_AVAILABLE, TRAIN_CANCELLED, TRAIN_DEPARTED, UNKNOWN] }\n        availability_text: { type: string }\n        available_count:\n          type: [integer, \"null\"]\n          minimum: 0\n          description: Available berth count. Null when the source reports availability without a quantity.\n        waitlist_count: { type: [integer, \"null\"], description: \"Current waitlist position; null if the source reports a waitlist without a position.\" }\n        rac_count: { type: [integer, \"null\"], description: \"Current RAC position; null if the source reports RAC without a position.\" }\n        wl_pool:\n          type: string\n          enum: [GNWL, PQWL, RLWL, RSWL, TQWL, NLWL, CKWL, RQWL, DPWL, RLGN, LDWL, SSWL, FTWL, HPWL]\n          description: The booking pool the availability text names (`GNWL276/WL185` gives GNWL). Present only when it names one; left out otherwise. It can stay after the status becomes RAC or AVAILABLE.\n        wl_pool_position:\n          type: integer\n          description: The original position in that pool, when the railway gives it; left out otherwise.\n        fare: { type: [integer, \"null\"] }\n        catering_charge: { type: integer }\n        total_fare: { type: [integer, \"null\"] }\n        fare_breakdown:\n          description: The railway's split of `total_fare`, in rupees (to the paisa), from the seat enquiry. The components add up to `total_fare`, with `concession` subtracted and `rounding` added. Absent when the enquiry gave no split; a null component was not given.\n          $ref: '#/components/schemas/FareBreakdown'\n        confirmation_probability: { $ref: '#/components/schemas/ConfirmationProbability' }\n        last_updated_at: { type: [string, \"null\"], format: date-time, description: \"When the figure was read from the railway. It can be hours before the request when the upstream answers from its own cache.\" }\n\n    FareBreakdown:\n      type: object\n      properties:\n        base_fare: { type: [number, \"null\"] }\n        reservation_charge: { type: [number, \"null\"] }\n        superfast_charge: { type: [number, \"null\"] }\n        tatkal_charge: { type: [number, \"null\"] }\n        dynamic_fare: { type: [number, \"null\"], description: \"Flexi or dynamic pricing above the base fare (Rajdhani, Shatabdi, Duronto and similar).\" }\n        fuel_charge: { type: [number, \"null\"] }\n        other_charge: { type: [number, \"null\"] }\n        gst: { type: [number, \"null\"] }\n        catering_charge: { type: [number, \"null\"] }\n        concession: { type: [number, \"null\"], description: \"Subtracted from the other components.\" }\n        rounding: { type: number, minimum: 0, description: \"What the railway added to reach the next ₹5 (0 to 4): it charges the sum of the other components rounded up to a multiple of five.\" }\n\n    AvailabilityResponse:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code: { $ref: '#/components/schemas/StationCode' }\n        journey_date: { type: string, format: date }\n        quota: { $ref: '#/components/schemas/Quota' }\n        classes: { type: array, items: { $ref: '#/components/schemas/AvailabilityDetail' }}\n\n    AvailabilityBatchResponse:\n      type: object\n      properties:\n        results:\n          type: array\n          description: One entry per item, in the order sent. An item that failed is an AvailabilityBatchFailure in its place.\n          items:\n            oneOf:\n              - { $ref: '#/components/schemas/AvailabilityResponse' }\n              - { $ref: '#/components/schemas/AvailabilityBatchFailure' }\n\n    AvailabilityBatchFailure:\n      type: object\n      required: [error, message]\n      properties:\n        error: { type: string, description: \"The item's error code, for example BOOKING_NOT_OPEN for a date past the booking window (that item is not asked and not counted).\" }\n        message: { type: string }\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code: { $ref: '#/components/schemas/StationCode' }\n        journey_date: { type: string, format: date }\n\n    AvailabilityCalendarDay:\n      type: object\n      properties:\n        date: { type: string, format: date }\n        day_of_week: { $ref: '#/components/schemas/RunningDay' }\n        status: { type: string }\n        availability_text: { type: string }\n        available_count:\n          type: [integer, \"null\"]\n          minimum: 0\n          description: Available berth count. Null when the source reports availability without a quantity.\n        waitlist_count: { type: [integer, \"null\"] }\n        wl_pool: { type: string, description: \"The booking pool the availability text names (`GNWL276/WL185` gives GNWL). Present only when it names one.\" }\n        wl_pool_position: { type: integer, description: \"The original position in that pool. Present only when the text gives it.\" }\n        fare: { type: [integer, \"null\"], description: \"The fare without compulsory catering. Null when the day was read from the upstream's listing.\" }\n        catering_charge: { type: integer, description: \"Catering included in total_fare. Present on a day read from its own enquiry.\" }\n        total_fare: { type: [integer, \"null\"], description: \"What the ticket costs: fare plus catering_charge. Present on a day read from its own enquiry.\" }\n        confirmation_probability: { $ref: '#/components/schemas/ConfirmationProbability' }\n        last_updated_at: { type: [string, \"null\"], format: date-time }\n\n    AvailabilityCalendar:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code: { $ref: '#/components/schemas/StationCode' }\n        class_code: { $ref: '#/components/schemas/ClassCode' }\n        quota: { $ref: '#/components/schemas/Quota' }\n        days: { type: array, items: { $ref: '#/components/schemas/AvailabilityCalendarDay' }}\n\n    FareItem:\n      type: object\n      properties:\n        class_code: { $ref: '#/components/schemas/ClassCode' }\n        fare: { type: integer }\n        currency: { type: string, enum: [INR] }\n\n    FareEstimate:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code: { $ref: '#/components/schemas/StationCode' }\n        quota: { $ref: '#/components/schemas/Quota' }\n        fares: { type: array, items: { $ref: '#/components/schemas/FareItem' }}\n\n    ChartCoachSummary:\n      type: object\n      properties:\n        coach_name: { type: string }\n        class_code: { $ref: '#/components/schemas/ClassCode' }\n        position_from_engine: { type: integer }\n        vacant_berths: { type: integer }\n\n    ChartStatus:\n      type: object\n      properties:\n        chart_one_prepared: { type: boolean }\n        chart_two_prepared: { type: boolean }\n        chart_one_date: { type: [string, \"null\"], format: date-time }\n        chart_two_date: { type: [string, \"null\"], format: date-time }\n\n    ChartStatusResponse:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        train_name: { type: string }\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code: { $ref: '#/components/schemas/StationCode' }\n        train_start_date: { type: string, format: date }\n        remote_station_code: { $ref: '#/components/schemas/StationCode' }\n        next_remote_station_code: { $ref: '#/components/schemas/StationCode' }\n        destination_station_code: { $ref: '#/components/schemas/StationCode' }\n        chart_status: { $ref: '#/components/schemas/ChartStatus' }\n        coach_summary: { type: array, items: { $ref: '#/components/schemas/ChartCoachSummary' }}\n\n    VacantBerth:\n      type: object\n      properties:\n        coach_name: { type: string }\n        class_code: { $ref: '#/components/schemas/ClassCode' }\n        berth_number: { type: integer }\n        berth_code: { type: string }\n        cabin_coupe: { type: [string, \"null\"] }\n        cabin_coupe_no: { type: [integer, \"null\"] }\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code: { $ref: '#/components/schemas/StationCode' }\n        split_no: { type: integer }\n        covers_requested_segment:\n          type: boolean\n          description: |\n            `true` when this vacant split covers the caller's requested from → to\n            segment end-to-end (i.e. the split's from-station is at or before the\n            request `from` in the train's stop order AND the split's to-station is\n            at or after the request `to`). `false` for splits that only partially\n            overlap. Defaults to `true` when the schedule is unavailable or the\n            caller did not supply from/to.\n\n    VacantBerthsResponse:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        train_name: { type: string }\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code: { $ref: '#/components/schemas/StationCode' }\n        train_start_date: { type: string, format: date }\n        remote_station_code: { $ref: '#/components/schemas/StationCode' }\n        chart_status: { $ref: '#/components/schemas/ChartStatus' }\n        coach_summary: { type: array, items: { $ref: '#/components/schemas/ChartCoachSummary' }}\n        vacant_berths: { type: array, items: { $ref: '#/components/schemas/VacantBerth' }}\n\n    HoppingHop:\n      type: object\n      description: |\n        One leg of a hop chain. `from_*` / `to_*` reflect the passenger's\n        *effective* travel range — clipped to the requested segment and to the\n        previous hop's alighting station. `berth_valid_from_station_code` and\n        `berth_valid_to_station_code` preserve the underlying berth's full\n        vacancy range so callers can see any extra headroom (e.g. a berth\n        vacant AN→AK used by a passenger only travelling AN→BSL).\n      properties:\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code:   { $ref: '#/components/schemas/StationCode' }\n        from_stop_sequence: { type: integer, description: \"Stop sequence along the train's schedule (1 = source).\" }\n        to_stop_sequence:   { type: integer }\n        from_station_name:   { type: [string, \"null\"] }\n        to_station_name:     { type: [string, \"null\"] }\n        from_departure_time: { type: [string, \"null\"], description: \"HH:mm departure from `from_station_code` (null when schedule enrichment failed).\" }\n        to_arrival_time:     { type: [string, \"null\"] }\n        coach_name:   { type: string }\n        class_code:   { $ref: '#/components/schemas/ClassCode' }\n        berth_number: { type: integer }\n        berth_code:   { type: string }\n        berth_code_new:\n          type: [string, \"null\"]\n          description: |\n            Normalized berth code using the updated IRCTC nomenclature (e.g. \"LB\"\n            instead of \"L\"). Null when the mapping is unavailable or the berth\n            code is already in the new format.\n        cabin_coupe:    { type: [string, \"null\"] }\n        cabin_coupe_no: { type: [integer, \"null\"] }\n        split_no: { type: integer }\n        berth_valid_from_station_code:\n          $ref: '#/components/schemas/StationCode'\n        berth_valid_to_station_code:\n          $ref: '#/components/schemas/StationCode'\n        stops_covered:\n          type: integer\n          minimum: 0\n          description: |\n            `to_stop_sequence - from_stop_sequence` — how many stop-order slots\n            this hop covers on the passenger's effective travel.\n        fare_inr:\n          type: [integer, \"null\"]\n          description: |\n            Fare in INR for this hop's `(from_station_code → to_station_code)` in\n            this class. Populated only when the caller passes `include_fare=true`\n            AND the upstream `fare-estimate` lookup succeeded. `null` otherwise.\n        berth_ergonomics:\n          $ref: '#/components/schemas/BerthErgonomics'\n\n    BerthErgonomics:\n      type: object\n      description: |\n        Human-readable guidance about a berth's accessibility, comfort, and\n        typical use cases. Emitted on every hop — always populated regardless\n        of caller flags. Non-technical travellers can filter by\n        `requires_climbing`, `daytime_seating`, etc. without knowing IRCTC\n        berth-code conventions.\n      properties:\n        code: { type: string, description: \"Raw IRCTC berth code (e.g. L, SL, U, P, W).\" }\n        label: { type: string, description: \"Human-friendly label such as 'Lower berth'.\" }\n        position:\n          type: string\n          enum: [cabin, side, chair, unknown]\n        requires_climbing: { type: boolean }\n        daytime_seating: { type: boolean }\n        privacy_tier: { type: string, enum: [high, medium, low] }\n        typical_length_meters: { type: [number, \"null\"] }\n        recommended_for: { type: array, items: { type: string } }\n        avoid_for: { type: array, items: { type: string } }\n        description: { type: string }\n\n    HoppingOption:\n      type: object\n      description: |\n        Result of running the min-hop cover algorithm for one class. When\n        `is_covered=false`, `reason` explains why and `unreachable_from_stop_sequence`\n        marks the earliest stop the algorithm could not reach.\n      properties:\n        class_code: { $ref: '#/components/schemas/ClassCode' }\n        is_covered: { type: boolean }\n        total_hops: { type: integer }\n        physical_seat_changes:\n          type: integer\n          description: |\n            Number of times the passenger must physically move within the chain\n            (consecutive hops that keep the same coach+berth do not count).\n        hops:\n          type: array\n          items: { $ref: '#/components/schemas/HoppingHop' }\n        reason:\n          type: [string, \"null\"]\n          enum: [null, \"NO_VACANT_BERTHS\", \"GAP_UNREACHABLE\", \"MAX_HOPS_EXCEEDED\", \"VIA_GAP_UNREACHABLE\"]\n        unreachable_from_stop_sequence: { type: [integer, \"null\"] }\n        unreachable_from_station_code:  { type: [string, \"null\"] }\n        total_fare_inr:\n          type: [integer, \"null\"]\n          description: |\n            Sum of `hops[i].fare_inr` across the chain when\n            `include_fare=true`. `null` when the flag was off, when the\n            chain is empty, or when any hop's fare lookup failed — we\n            don't ship a misleading total.\n        strategies:\n          type: array\n          items: { $ref: '#/components/schemas/StrategyPlan' }\n          description: |\n            Alternative plans for this class, one per requested strategy\n            (`min_hops`, `min_seat_changes`, `cheapest`). Defaults to a\n            single `min_hops` entry. The top-level fields (`is_covered`,\n            `hops`, `total_fare_inr`, etc.) mirror `strategies[0]` for\n            backward compatibility.\n\n    StrategyPlan:\n      type: object\n      description: |\n        A single strategy's plan for one class. Same shape as the top-level\n        `HoppingOption` fields — consumers can render any strategy with the\n        same code.\n      properties:\n        name:\n          type: string\n          enum: [min_hops, min_seat_changes, cheapest]\n        is_covered: { type: boolean }\n        total_hops: { type: integer }\n        physical_seat_changes: { type: integer }\n        total_fare_inr: { type: [integer, \"null\"] }\n        hops:\n          type: array\n          items: { $ref: '#/components/schemas/HoppingHop' }\n        reason:\n          type: [string, \"null\"]\n          enum: [null, \"NO_VACANT_BERTHS\", \"GAP_UNREACHABLE\", \"MAX_HOPS_EXCEEDED\", \"VIA_GAP_UNREACHABLE\", \"REQUIRES_FARE_DATA\"]\n        unreachable_from_stop_sequence: { type: [integer, \"null\"] }\n        unreachable_from_station_code:  { type: [string, \"null\"] }\n        ranking_reason:\n          type: string\n          description: One-line human-readable summary of what makes this plan special.\n\n    HoppingDirectOption:\n      type: object\n      properties:\n        class_code: { $ref: '#/components/schemas/ClassCode' }\n        berths:\n          type: array\n          items: { $ref: '#/components/schemas/VacantBerth' }\n        fare_inr:\n          type: [integer, \"null\"]\n          description: |\n            Fare in INR for `(from → to)` in this class. Populated only\n            when `include_fare=true` and the fare lookup succeeded. All\n            berths in this option cover the same segment so one fare\n            applies to all of them.\n\n    AlternateBoardingCandidate:\n      type: object\n      description: |\n        Same-train boarding station near the caller's `from`. Emitted only\n        when the caller passes `include_alternate_boarding=true`. No extra\n        upstream chart lookups — vacancy is a re-projection of already-fetched\n        berth data over `(candidate → to)`.\n      properties:\n        station_code: { $ref: '#/components/schemas/StationCode' }\n        station_name: { type: [string, \"null\"] }\n        stop_sequence: { type: integer }\n        is_earlier_boarding:\n          type: boolean\n          description: True when the candidate is *before* the caller's `from` on the route.\n        sequence_delta:\n          type: integer\n          description: |\n            Signed stop-sequence delta from `from` to this candidate.\n            Negative → earlier boarding, positive → later boarding.\n        direct_vacancy_by_class:\n          type: object\n          additionalProperties: { type: integer }\n          description: Per-class direct-vacancy counts for `(candidate → to)`.\n        hopping_covered_classes:\n          type: array\n          items: { type: string }\n          description: |\n            Classes for which a hopping plan exists from `(candidate → to)`.\n        fare_inr_by_class:\n          type: object\n          additionalProperties: { type: integer }\n          description: |\n            Per-class fare for `(candidate → to)`. Populated only when\n            `include_fare=true` and the fare lookup succeeded for this tuple.\n        chart_status:\n          oneOf:\n            - $ref: '#/components/schemas/ChartStatus'\n            - type: \"null\"\n          description: |\n            Fresh chart-status snapshot for this candidate boarding station.\n            Only populated in `alternate_boarding_mode=extended`. Chart-2\n            preparation timing varies per boarding station, so this is what\n            makes \"extended\" mode authoritative.\n        vacancy_delta_vs_user_boarding:\n          type: object\n          additionalProperties: { type: integer }\n          description: |\n            Per-class delta vs the caller's actual boarding station. Positive\n            = candidate has MORE vacancy. Only populated in `extended` mode.\n        notes:\n          type: array\n          items: { type: string }\n          description: |\n            Human-readable insights (e.g. \"3 more SL berths compared to\n            boarding from ADI\", \"Chart 2 already prepared\").\n        recommendation_score:\n          type: integer\n          minimum: 0\n          maximum: 100\n          description: |\n            Composite ranking score. Higher = better candidate.\n\n    AlternateBoardingBlock:\n      type: object\n      properties:\n        enabled:\n          type: boolean\n          description: True iff the caller passed `include_alternate_boarding=true`.\n        mode:\n          type: string\n          enum: [lightweight, extended]\n          description: Which fetch strategy produced the candidates.\n        chart_calls_made:\n          type: integer\n          minimum: 0\n          description: |\n            Number of extra chart-composition calls made (0 in lightweight\n            mode; up to `alternate_boarding_max_candidates` in extended).\n        disabled_reason:\n          type: [string, \"null\"]\n          enum: [null, \"SCHEDULE_UNAVAILABLE\", \"REQUEST_INVALID\", \"NO_CANDIDATES_IN_WINDOW\"]\n        candidates:\n          type: array\n          items: { $ref: '#/components/schemas/AlternateBoardingCandidate' }\n\n    CrossClassPlan:\n      type: object\n      description: |\n        A single cross-class plan — a chain of hops where consecutive hops\n        MAY be in different `class_code` values. The solver still prefers\n        same-class and same-berth continuity; classes only switch when\n        forced by a gap in the current class.\n      properties:\n        is_covered: { type: boolean }\n        total_hops: { type: integer }\n        physical_seat_changes: { type: integer }\n        class_changes:\n          type: integer\n          description: Number of transitions where `class_code` differs from the previous hop.\n        classes_used:\n          type: array\n          items: { type: string }\n          description: Unique classes used, in order of first appearance.\n        hops:\n          type: array\n          items: { $ref: '#/components/schemas/HoppingHop' }\n        reason:\n          type: [string, \"null\"]\n          enum: [null, \"NO_VACANT_BERTHS\", \"GAP_UNREACHABLE\", \"MAX_HOPS_EXCEEDED\", \"VIA_GAP_UNREACHABLE\", \"REQUIRES_FARE_DATA\"]\n        unreachable_from_stop_sequence: { type: [integer, \"null\"] }\n        unreachable_from_station_code:  { type: [string, \"null\"] }\n        total_fare_inr: { type: [integer, \"null\"] }\n        ranking_reason: { type: string }\n\n    CrossClassBlock:\n      type: object\n      description: |\n        Response block for cross-class hopping. `enabled=false` when the\n        caller did not opt in via `include_cross_class=true`. When enabled\n        but no plan exists, `disabled_reason` is set and `plan=null`.\n      properties:\n        enabled: { type: boolean }\n        disabled_reason:\n          type: [string, \"null\"]\n          enum: [null, \"SCHEDULE_UNAVAILABLE\", \"REQUEST_INVALID\", \"NO_VACANT_BERTHS\"]\n        plan:\n          oneOf:\n            - $ref: '#/components/schemas/CrossClassPlan'\n            - type: \"null\"\n\n    VacantBerthsHoppingResponse:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        train_name:   { type: string }\n        from_station_code: { $ref: '#/components/schemas/StationCode' }\n        to_station_code:   { $ref: '#/components/schemas/StationCode' }\n        train_start_date:  { type: string, format: date }\n        remote_station_code: { $ref: '#/components/schemas/StationCode' }\n        next_remote_station_code: { type: [string, \"null\"] }\n        chart_status: { $ref: '#/components/schemas/ChartStatus' }\n        coach_summary: { type: array, items: { $ref: '#/components/schemas/ChartCoachSummary' }}\n        requested_segment:\n          type: object\n          properties:\n            from_stop_sequence: { type: [integer, \"null\"] }\n            to_stop_sequence:   { type: [integer, \"null\"] }\n            stops:\n              type: array\n              items:\n                type: object\n                properties:\n                  sequence:      { type: integer }\n                  station_code:  { $ref: '#/components/schemas/StationCode' }\n                  station_name:  { type: string }\n            via:\n              type: array\n              items: { $ref: '#/components/schemas/StationCode' }\n        direct:\n          type: object\n          properties:\n            available: { type: boolean, description: \"True when at least one class has a berth covering from→to end-to-end.\" }\n            options:\n              type: array\n              items: { $ref: '#/components/schemas/HoppingDirectOption' }\n            all_berths:\n              type: array\n              items: { $ref: '#/components/schemas/VacantBerth' }\n              description: \"Every vacant berth returned by the upstream, regardless of segment coverage.\"\n        hopping:\n          type: object\n          properties:\n            disabled: { type: boolean, description: \"True when the hopping algorithm could not run (see `disabled_reason`).\" }\n            disabled_reason:\n              type: [string, \"null\"]\n              enum: [null, \"SCHEDULE_UNAVAILABLE\", \"REQUEST_INVALID\"]\n            options:\n              type: array\n              items: { $ref: '#/components/schemas/HoppingOption' }\n        alternate_boarding:\n          $ref: '#/components/schemas/AlternateBoardingBlock'\n        cross_class:\n          $ref: '#/components/schemas/CrossClassBlock'\n        _meta:\n          type: object\n          properties:\n            chart_type_used: { type: integer, enum: [1, 2] }\n            classes_requested:\n              type: array\n              items: { type: string }\n            partial_failures:\n              type: array\n              items:\n                type: object\n                properties:\n                  class_code: { type: string }\n                  reason:     { type: string }\n            schedule_enrichment:       { type: string, enum: [success, failed, skipped] }\n            coach_position_enrichment: { type: string, enum: [success, failed, skipped] }\n            max_hops: { type: integer }\n            algorithm_notes:\n              type: array\n              items: { type: string }\n            preferences_applied:\n              type: object\n              description: |\n                Echo of preference filters actually applied (post-normalisation\n                + avoid-wins resolution).\n              properties:\n                prefer_berth: { type: array, items: { type: string } }\n                avoid_berth:  { type: array, items: { type: string } }\n                prefer_class: { type: array, items: { type: string } }\n                avoid_class:  { type: array, items: { type: string } }\n                classes_skipped:\n                  type: array\n                  items: { type: string }\n                  description: |\n                    Intersection of `avoid_class` with classes actually\n                    present on the train — what was really dropped.\n\n    # Envelope helpers — one per endpoint payload\n    EnvelopeStation:\n      allOf:\n        - type: object\n          properties:\n            success: { type: boolean }\n            data: { $ref: '#/components/schemas/Station' }\n            meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeStationSearch:\n      type: object\n      properties:\n        success: { type: boolean }\n        data:\n          type: object\n          properties:\n            query: { type: string }\n            limit: { type: integer }\n            enriched: { type: boolean, description: \"Whether some results' city, state or position were filled in from a second station source. false when every result comes from RailCore's own station reference, as it does today.\" }\n            results: { type: array, items: { $ref: '#/components/schemas/Station' }}\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeTrain:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/Train' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeTrainSearch:\n      type: object\n      properties:\n        success: { type: boolean }\n        data:\n          type: object\n          properties:\n            query: { type: string }\n            limit: { type: integer }\n            results: { type: array, items: { $ref: '#/components/schemas/Train' }}\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeTrainSchedule:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/TrainSchedule' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeCoachPosition:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/CoachPosition' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeStationBoard:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/StationBoard' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeLiveTrainStatus:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/LiveTrainStatus' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeRouteTrains:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/RouteTrains' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeAvailability:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/AvailabilityResponse' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeAvailabilityBatch:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/AvailabilityBatchResponse' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeAvailabilityCalendar:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/AvailabilityCalendar' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeFareEstimate:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/FareEstimate' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeChartStatus:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/ChartStatusResponse' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeVacantBerths:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/VacantBerthsResponse' }\n        meta: { $ref: '#/components/schemas/Meta' }\n    EnvelopeVacantBerthsHopping:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/VacantBerthsHoppingResponse' }\n        meta: { $ref: '#/components/schemas/Meta' }\n\n    EnvelopeVacantBerthsRouteScan:\n      type: object\n      properties:\n        success: { type: boolean }\n        data: { $ref: '#/components/schemas/VacantBerthsRouteScanResponse' }\n        meta: { $ref: '#/components/schemas/Meta' }\n\n    ResolvedStation:\n      type: object\n      properties:\n        station_code: { $ref: '#/components/schemas/StationCode' }\n        station_name: { type: [string, \"null\"] }\n        resolved_from:\n          type: string\n          enum: [code, name, fuzzy]\n          description: |\n            How the raw input matched:\n            - `code` — exact upper-case station code.\n            - `name` — exact case-insensitive name match, or a prefix hit\n              above 0.95 confidence.\n            - `fuzzy` — best hit above the 0.55 confidence threshold.\n        input: { type: string, description: \"Original caller input.\" }\n        confidence: { type: number, minimum: 0, maximum: 1 }\n        alternates:\n          type: array\n          description: |\n            Alternative candidates the resolver considered above threshold.\n            Populated for fuzzy matches to enable UI disambiguation.\n          items:\n            type: object\n            properties:\n              station_code: { $ref: '#/components/schemas/StationCode' }\n              station_name: { type: string }\n              confidence:   { type: number, minimum: 0, maximum: 1 }\n\n    ClassSummary:\n      type: object\n      description: |\n        Compact per-class projection of a train's scan result. Callers\n        that only need to render \"which classes look bookable?\" can rely\n        on this without walking the full `hopping_detail`.\n      properties:\n        class_code:              { $ref: '#/components/schemas/ClassCode' }\n        direct_available:        { type: boolean }\n        direct_berth_count:      { type: integer, minimum: 0 }\n        hopping_covered:         { type: boolean }\n        hopping_hops:            { type: [integer, \"null\"] }\n        physical_seat_changes:   { type: [integer, \"null\"] }\n        cheapest_fare_inr:       { type: [integer, \"null\"] }\n        availability_summary_text:\n          type: [string, \"null\"]\n          description: \"Availability text from routes-trains for this class (e.g. `AVAILABLE 12`, `WL 34`).\"\n        availability_summary_status:\n          type: [string, \"null\"]\n          description: \"Availability status enum (`AVAILABLE`, `RAC`, `WAITLIST`, `REGRET`, `NOT_AVAILABLE`, ...).\"\n\n    ScoreBreakdown:\n      type: object\n      description: |\n        Exposed so consumers can debug why a train ranks where it does, or\n        apply their own weightings on top. Total is clipped to `[0, 100]`.\n      properties:\n        chart_ready_points:       { type: integer, description: \"+30 for chart 2 prepared, +20 for chart 1 only, 0 otherwise.\" }\n        direct_vacancy_points:    { type: integer, description: \"+40 for direct vacancy in a preferred class, +30 for any class, 0 otherwise.\" }\n        hopping_coverage_points:  { type: integer, description: \"+25 preferred / +18 any / +10 cross-class — only when no direct vacancy.\" }\n        seat_changes_penalty:     { type: integer, description: \"-3 per physical seat change, capped at -12.\" }\n        running_day_penalty:      { type: integer, description: \"-10 when the train doesn't run on the requested day and `only_running=false` kept it.\" }\n        alternate_boarding_bonus: { type: integer, description: \"+5 when `include_alternate_boarding=true` returned at least one candidate.\" }\n        no_coverage_penalty:      { type: integer, description: \"-15 when no strategy covers the segment at all.\" }\n        multi_class_direct_bonus: { type: integer, description: \"+8 when direct vacancy exists in multiple travel classes.\" }\n        berth_richness_bonus:     { type: integer, description: \"+5 when the train has high berth diversity (many distinct berth types available).\" }\n        train_departed_penalty:   { type: integer, description: \"-20 when the train has already departed from the boarding station.\" }\n        total:                    { type: integer, minimum: 0, maximum: 100 }\n\n    RouteScanMatch:\n      type: object\n      properties:\n        train_number: { $ref: '#/components/schemas/TrainNumber' }\n        train_name:   { type: string }\n        train_type:\n          type: string\n          description: |\n            Train type — one of the canonical enum values (see\n            `#/components/schemas/RouteTrain.train_type`). Kept as plain\n            string here for schema-tooling compatibility.\n        departure_time: { type: string, description: \"HH:mm at `from` station.\" }\n        arrival_time:   { type: string, description: \"HH:mm at `to` station.\" }\n        duration_minutes: { type: integer }\n        distance_km:      { type: [number, \"null\"] }\n        running_days:     { type: array, items: { $ref: '#/components/schemas/RunningDay' } }\n        runs_on_date:     { type: boolean }\n        chart_status:\n          oneOf:\n            - $ref: '#/components/schemas/ChartStatus'\n            - type: \"null\"\n          description: \"Null when this train wasn't scanned (SKIPPED_*).\"\n        chart_prepared: { type: boolean }\n        recommendation:\n          type: string\n          description: |\n            Human-readable one-liner suitable for direct UI display.\n            Examples:\n            - `Direct berth available in SL and 3A`\n            - `Hopping plan available in 3A — 1 seat change needed`\n            - `Chart not prepared yet. Vacancy data unavailable until charting.`\n        urgency_hint:\n          type: [string, \"null\"]\n          description: |\n            Time-sensitive nudge, or `null`. Examples:\n            - `Chart 2 prepared. Vacancy is authoritative — book immediately.`\n            - `Chart 1 prepared. Chart 2 will refresh vacancy 30 min before departure.`\n        score: { type: integer, minimum: 0, maximum: 100 }\n        score_breakdown: { $ref: '#/components/schemas/ScoreBreakdown' }\n        classes_summary:\n          type: array\n          items: { $ref: '#/components/schemas/ClassSummary' }\n        hopping_detail:\n          oneOf:\n            - $ref: '#/components/schemas/VacantBerthsHoppingResponse'\n            - type: \"null\"\n          description: \"Full hopping response. `null` when `include_detail=false` OR when the train was skipped.\"\n        scan_status:\n          type: string\n          enum:\n            - OK\n            - CHART_NOT_PREPARED\n            - UPSTREAM_FAILED\n            - SKIPPED_NOT_RUNNING\n            - SKIPPED_TRAIN_TYPE\n            - SKIPPED_CAP_EXCEEDED\n            - SKIPPED_SEGMENT_INVALID\n        scan_status_reason:\n          type: [string, \"null\"]\n          description: \"Human-readable explanation for a non-OK scan_status.\"\n\n    VacantBerthsRouteScanResponse:\n      type: object\n      properties:\n        from: { $ref: '#/components/schemas/ResolvedStation' }\n        to:   { $ref: '#/components/schemas/ResolvedStation' }\n        journey_date: { type: string, format: date }\n        quota: { $ref: '#/components/schemas/Quota' }\n        route_summary:\n          type: object\n          description: |\n            Top-line summary for consumers who don't want to loop through\n            `matches[]`. Every count is derived from `matches[]` after all\n            filters have been applied.\n          properties:\n            total_trains_on_route:        { type: integer, minimum: 0 }\n            trains_running_on_date:       { type: integer, minimum: 0 }\n            trains_scanned:               { type: integer, minimum: 0 }\n            trains_with_direct_vacancy:   { type: integer, minimum: 0 }\n            trains_with_hopping_coverage: { type: integer, minimum: 0 }\n            trains_with_no_coverage:      { type: integer, minimum: 0 }\n            trains_with_chart_prepared:   { type: integer, minimum: 0 }\n            best_train_number:            { type: [string, \"null\"] }\n            best_recommendation:          { type: [string, \"null\"] }\n            best_score:                   { type: integer, minimum: 0, maximum: 100 }\n        matches:\n          type: array\n          items: { $ref: '#/components/schemas/RouteScanMatch' }\n        _meta:\n          type: object\n          properties:\n            routes_trains_confidence: { type: string, enum: [high, medium, low] }\n            partial_failures:\n              type: array\n              description: \"Per-train failures. The overall request is never failed because one train's chart fetch died.\"\n              items:\n                type: object\n                properties:\n                  train_number: { $ref: '#/components/schemas/TrainNumber' }\n                  reason:       { type: string }\n            trains_dispatched: { type: integer, minimum: 0, description: \"How many trains were actually fanned out (excludes SKIPPED_*).\" }\n            cap_applied:\n              oneOf:\n                - type: \"null\"\n                - type: object\n                  properties:\n                    trains_available: { type: integer }\n                    trains_scanned:   { type: integer }\n                    reason:           { type: string, enum: [MAX_TRAINS_CAP] }\n            trains_dropped_by_type_filter:    { type: integer, minimum: 0 }\n            trains_dropped_by_running_filter: { type: integer, minimum: 0 }\n            trains_dropped_by_chart_filter:   { type: integer, minimum: 0 }\n            trains_dropped_by_score_filter:   { type: integer, minimum: 0 }\n            algorithm_notes:\n              type: array\n              items: { type: string }\n              description: \"Free-form audit trail of algorithmic decisions (station resolution, drops, cap, sort).\"\n            upstream_failure_summary:\n              type: object\n              nullable: true\n              description: \"Summary of upstream failures during the route-scan. Null when all calls succeeded.\"\n              properties:\n                total_failures: { type: integer, description: \"Total number of failed upstream calls.\" }\n                timeout_count:  { type: integer, description: \"Number of calls that timed out.\" }\n                error_count:    { type: integer, description: \"Number of calls that returned non-timeout errors.\" }\n            preferences_applied:\n              type: object\n              properties:\n                prefer_berth:      { type: array, items: { type: string } }\n                avoid_berth:       { type: array, items: { type: string } }\n                prefer_class:      { type: array, items: { $ref: '#/components/schemas/ClassCode' } }\n                avoid_class:       { type: array, items: { $ref: '#/components/schemas/ClassCode' } }\n                train_types:       { type: array, items: { type: string } }\n                avoid_train_types: { type: array, items: { type: string } }\n            sort_by:                    { type: string, enum: [departure, departure_desc, duration, score, chart_ready] }\n            only_running:               { type: boolean }\n            only_chart_prepared:        { type: boolean }\n            include_detail:             { type: boolean }\n            include_fare:               { type: boolean }\n            include_alternate_boarding: { type: boolean }\n            include_cross_class:        { type: boolean }\n            strategies:                 { type: array, items: { type: string, enum: [min_hops, min_seat_changes, cheapest] } }\n\ntags:\n  - name: Stations\n    description: Reference + live station data\n  - name: Trains\n    description: Train reference, schedule, coach position, live tracking\n  - name: Live\n    description: Live / real-time endpoints (no cache)\n  - name: Journeys\n    description: Trains between two stations\n  - name: Availability\n    description: Seat availability\n  - name: Fares\n    description: Fare calculation\n  - name: Charts\n    description: Post-chart preparation status and vacant berths\n  - name: Jobs\n    description: Asynchronous premium analysis lifecycle\n"}}