Quickstart
From your first API key to your first request.
Before you begin
Create an account and review the models available in this deployment. Model IDs, prices and supported endpoints are listed in Models & pricing.
- Use your default project, or create separate projects for applications and clients.
- Create an API key and select its project, models and quota.
- Keep sufficient balance in the account that pays for the request.
- Use the gateway URL supplied by your operator. Keep API keys on your server.
Configure your server environment
Set AI_BASE_URL to https://easyrouteapi.com and AI_MODEL to an exact Chat Completions model ID from Models & pricing. Enter AI_API_KEY privately; do not paste a real key into command history.
Each example sends one short non-streaming request, limits output to 64 tokens and makes no automatic retries. Run one language example, then check Usage Logs. A token limit does not replace the API key spending cap.
export AI_BASE_URL='https://easyrouteapi.com'
export AI_MODEL='YOUR_MODEL_ID'
read -rs -p 'EasyRouteAPI key: ' AI_API_KEY; printf '\n'
export AI_API_KEYMake a Chat Completions request
Save this as chat.sh and run bash chat.sh with Bash 4+ and curl 7.76+. It prints the full successful JSON response. The key is passed to curl on stdin rather than in its command-line arguments.
#!/usr/bin/env bash
# Bash 4+ and curl 7.76+. API credentials are sent on stdin, not curl's argv.
set +x
set -euo pipefail
base="${AI_BASE_URL:-https://easyrouteapi.com}"
base="${base%/}"
base="${base%/v1}"
if [[ ! "$base" =~ ^https://[a-zA-Z0-9.-]+(:[0-9]+)?$ && ! "$base" =~ ^http://(localhost|127\.0\.0\.1)(:[0-9]+)?$ ]]; then
echo 'AI_BASE_URL must be an HTTPS gateway origin or its /v1 URL. HTTP is only allowed for local tests.' >&2; exit 1
fi
if [[ ! "${AI_API_KEY:-}" =~ ^[a-zA-Z0-9._-]+$ ]]; then
echo 'Set AI_API_KEY in your server environment.' >&2; exit 1
fi
if [[ ! "${AI_MODEL:-}" =~ ^[a-zA-Z0-9_.:/@+-]{1,200}$ || "$AI_MODEL" == 'YOUR_MODEL_ID' ]]; then
echo 'Set AI_MODEL to an available Chat Completions model or route ID.' >&2; exit 1
fi
limit="${AI_MAX_TOKENS:-64}"
if [[ ! "$limit" =~ ^[1-9][0-9]{0,2}$ ]] || (( 10#$limit > 256 )); then
echo 'AI_MAX_TOKENS must be an integer from 1 to 256.' >&2; exit 1
fi
session="${AI_SESSION_ID:-}"
if [[ -n "$session" && ! "$session" =~ ^[a-zA-Z0-9._:-]{1,128}$ ]]; then
echo 'AI_SESSION_ID must be an opaque ASCII identifier, at most 128 characters.' >&2; exit 1
fi
# Ignore local curlrc defaults; keep TLS verification, no retries or redirects.
# Do not add --verbose or --trace.
set +e
result=$(printf 'header = "Authorization: Bearer %s"\n' "$AI_API_KEY" |
curl --disable --config - --silent --show-error --connect-timeout 10 --max-time 30 \
--request POST "$base/v1/chat/completions" \
--header 'Content-Type: application/json' --header "Session-Id: $session" \
--data-binary "{\"model\":\"$AI_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with OK only.\"}],\"max_tokens\":$limit,\"stream\":false}" \
--write-out $'\n%{http_code}')
result_code=$?
set -e
if (( result_code != 0 )); then
echo 'The request did not complete. Check Usage Logs before retrying; the upstream may have processed it.' >&2; exit 1
fi
status="${result##*$'\n'}"
if [[ "$status" != 2[0-9][0-9] ]]; then
printf 'HTTP %s. Check the model, key permissions, balance and Usage Logs. No automatic retry was made.\n' "$status" >&2; exit 1
fi
# Successful output is the full JSON completion, including token usage if supplied.
printf '%s\n' "${result%$'\n'*}"Call from a Python server
Save this as chat.py and run python3 chat.py with Python 3.11 or later. It uses the standard library and prints the assistant text; no pip packages are required.
"""One bounded Chat Completions request; Python 3.11+, no pip packages."""
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None # Never forward the API key to a redirect target.
def chat(env=os.environ):
base = urllib.parse.urlsplit(env.get("AI_BASE_URL", "https://easyrouteapi.com"))
loopback = base.hostname in ("localhost", "127.0.0.1", "::1")
if ((base.scheme != "https" and not (base.scheme == "http" and loopback))
or not base.hostname or base.username is not None or base.password is not None
or base.query or base.fragment or base.path not in ("", "/", "/v1", "/v1/")):
raise ValueError("AI_BASE_URL must be an HTTPS gateway origin or its /v1 URL. HTTP is only allowed for local tests.")
key = env.get("AI_API_KEY", "")
if not key or key.strip() != key or re.search(r"[\x00-\x20\x7f]", key):
raise ValueError("Set AI_API_KEY in your server environment.")
model = env.get("AI_MODEL", "")
if not re.fullmatch(r"[A-Za-z0-9_.:/@+\-]{1,200}", model) or model == "YOUR_MODEL_ID":
raise ValueError("Set AI_MODEL to an available Chat Completions model or route ID.")
limit = env.get("AI_MAX_TOKENS", "64")
if not re.fullmatch(r"[0-9]{1,3}", limit) or not 1 <= int(limit) <= 256:
raise ValueError("AI_MAX_TOKENS must be an integer from 1 to 256.")
headers = {"Authorization": "Bearer " + key, "Content-Type": "application/json"}
session = env.get("AI_SESSION_ID", "")
if session:
if not re.fullmatch(r"[A-Za-z0-9._:\-]{1,128}", session):
raise ValueError("AI_SESSION_ID must be an opaque ASCII identifier, at most 128 characters.")
headers["Session-Id"] = session
payload = json.dumps({"model": model, "messages": [{"role": "user", "content": "Reply with OK only."}], "max_tokens": int(limit), "stream": False}).encode()
request = urllib.request.Request(urllib.parse.urlunsplit((base.scheme, base.netloc, "/v1/chat/completions", "", "")), data=payload, headers=headers, method="POST")
try:
with urllib.request.build_opener(NoRedirect).open(request, timeout=30) as response:
completion = json.load(response)
except urllib.error.HTTPError as error:
raise RuntimeError(f"HTTP {error.code}. Check the model, key permissions, balance and Usage Logs. No automatic retry was made.") from None
except (urllib.error.URLError, TimeoutError, OSError):
raise RuntimeError("The request did not complete. Check Usage Logs before retrying; the upstream may have processed it.") from None
except (ValueError, UnicodeError):
raise RuntimeError("The server returned an invalid JSON response. Check Usage Logs before retrying.") from None
choices = completion.get("choices") if isinstance(completion, dict) else None
message = choices[0].get("message") if isinstance(choices, list) and choices and isinstance(choices[0], dict) else None
content = message.get("content") if isinstance(message, dict) else None
if not isinstance(content, str) or not content.strip():
raise RuntimeError("No text was returned. The output limit may have been spent on reasoning; inspect Usage Logs before changing the limit.")
return content
if __name__ == "__main__":
try:
print(chat())
except (ValueError, RuntimeError) as error:
print(str(error), file=sys.stderr)
sys.exit(1)Call from a Node.js server
Save this as chat.mjs and run node chat.mjs with Node.js 22 or later. It uses built-in fetch and prints the assistant text; no npm packages are required.
import process from 'node:process';
import { pathToFileURL } from 'node:url';
/** One bounded request, with no automatic retries or credential-bearing redirects. */
export async function chat(env = process.env) {
const base = new URL(env.AI_BASE_URL || 'https://easyrouteapi.com');
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname);
if ((base.protocol !== 'https:' && !(base.protocol === 'http:' && loopback)) ||
base.username || base.password || base.search || base.hash ||
!['', '/', '/v1', '/v1/'].includes(base.pathname)) {
throw new Error('AI_BASE_URL must be an HTTPS gateway origin or its /v1 URL. HTTP is only allowed for local tests.');
}
const key = env.AI_API_KEY || '';
if (!key || key.trim() !== key || /[\x00-\x20\x7f]/.test(key)) {
throw new Error('Set AI_API_KEY in your server environment.');
}
const model = env.AI_MODEL || '';
if (!/^[A-Za-z0-9_.:/@+-]{1,200}$/.test(model) || model === 'YOUR_MODEL_ID') {
throw new Error('Set AI_MODEL to an available Chat Completions model or route ID.');
}
const maxTokens = Number(env.AI_MAX_TOKENS || '64');
if (!Number.isInteger(maxTokens) || maxTokens < 1 || maxTokens > 256) {
throw new Error('AI_MAX_TOKENS must be an integer from 1 to 256.');
}
const headers = { Authorization: `Bearer ${key}`, 'Content-Type': 'application/json' };
if (env.AI_SESSION_ID) {
if (!/^[A-Za-z0-9._:-]{1,128}$/.test(env.AI_SESSION_ID)) {
throw new Error('AI_SESSION_ID must be an opaque ASCII identifier, at most 128 characters.');
}
headers['Session-Id'] = env.AI_SESSION_ID;
}
let response;
try {
response = await fetch(new URL('/v1/chat/completions', base), {
method: 'POST', headers, redirect: 'error', signal: AbortSignal.timeout(30_000),
body: JSON.stringify({ model, messages: [{ role: 'user', content: 'Reply with OK only.' }], max_tokens: maxTokens, stream: false }),
});
} catch {
throw new Error('The request did not complete. Check Usage Logs before retrying; the upstream may have processed it.');
}
if (!response.ok) {
// Do not echo an upstream error body; it may contain private request details.
throw new Error(`HTTP ${response.status}. Check the model, key permissions, balance and Usage Logs. No automatic retry was made.`);
}
let completion;
try { completion = await response.json(); } catch {
throw new Error('The server returned an invalid JSON response. Check Usage Logs before retrying.');
}
const content = completion?.choices?.[0]?.message?.content;
if (typeof content !== 'string' || !content.trim()) {
throw new Error('No text was returned. The output limit may have been spent on reasoning; inspect Usage Logs before changing the limit.');
}
return content;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
try { console.log(await chat()); } catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}Troubleshoot your first request
401: check the key and expiry. 403: check model, group and project permissions. 429: check limits or provider capacity. For balance errors, check the payer balance and key quota. For 5xx, timeouts or disconnects, inspect Usage Logs before retrying because processing may already have started.
Empty text can mean the small output budget was used for reasoning. Inspect usage before increasing AI_MAX_TOKENS. Do not log API keys, private prompts or raw upstream error bodies.
Check the result
Review Usage Logs after the request. Project totals are calculated from retained consumption logs; they can change when refunds are recorded.