Calling the API
A Fusion Stack API is plain HTTP and JSON, so any language can call it. This guide covers what every client needs to know, then shows a small client in JavaScript, Laravel and Python. For a typed TypeScript client generated from your API, see Client project setup; it has sections for Nuxt, React Native and Node.
The examples call an orders API at http://localhost:8000/v1, such as the playground in the Fusion Stack repository. An app with Fusion Stack added to it serves it under /api/v1 instead.
The contract
| What | How |
|---|---|
| Authentication | Authorization: Bearer fs_live_… with an API key from php artisan api:key:create, or a token from another configured guard, such as Sanctum. |
| Version | Api-Version: 2026-11-30.atlas, when the API has versioning on. Without it, a request gets the key's pinned version or the API's default. |
| Documents | Content-Type: application/vnd.api+json and JSON:API bodies: { "data": { "type", "id", "attributes", "relationships" } }. |
| Queries | include, fields[type], filter[field], sort and page[size]. Anything the endpoint does not allow is a 400. |
| Pagination | Follow links.next until it is null. Do not build page URLs yourself: cursors are opaque. |
| Errors | { "errors": [{ "status", "code", "detail", "source", "meta": { "request_id" } }] }. Branch on code, never on the text. |
| Retries | Send an Idempotency-Key with POST, PATCH and DELETE, and reuse it when you retry. On a 429, wait for Retry-After seconds. |
| Caching | Send a response's ETag back in If-None-Match. A 304 means your copy is still current. |
The HTTP headers reference lists every header, and the errors reference every error code. The API reference at /docs documents each endpoint, and /docs/openapi.json is the same as an OpenAPI 3.1 document.
With curl
List paid orders with their customers, two at a time, largest first:
curl -g "localhost:8000/v1/orders?filter[status]=paid&include=customer&sort=-total_cents&page[size]=2" \
-H "Authorization: Bearer $KEY"{
"data": [
{
"id": "11",
"type": "orders",
"attributes": { "reference": "ORD-2F9ENKQD", "status": "paid", "total_cents": 49522, "currency": "GBP", "created_at": "2026-12-01T12:20:10.000000Z" },
"relationships": { "customer": { "data": { "id": "4", "type": "customers" } } }
},
…
],
"included": [{ "id": "4", "type": "customers", "attributes": { … } }],
"links": {
"first": "http://localhost:8000/v1/orders?include=customer&filter%5Bstatus%5D=paid&sort=-total_cents&page%5Bsize%5D=2",
"prev": null,
"next": "http://localhost:8000/v1/orders?include=customer&filter%5Bstatus%5D=paid&sort=-total_cents&page%5Bsize%5D=2&page%5Bafter%5D=eyJ…"
},
"meta": { "page": { "size": 2 } }
}-g stops curl reading the [ in the query string as a pattern. The related customers are in included, once each, however many orders share them.
Create an order. The Idempotency-Key makes the request safe to send again:
curl -X POST localhost:8000/v1/orders \
-H "Authorization: Bearer $KEY" \
-H "Content-Type: application/vnd.api+json" \
-H "Idempotency-Key: 0b7c6a52-7d4e-4f0a-9d55-3f1c2e8a9b10" \
-d '{"data":{"type":"orders","attributes":{"total_cents":4999,"currency":"GBP"},"relationships":{"customer":{"data":{"type":"customers","id":"1"}}}}}'The response is a 201 with the new order. Sending the same request with the same key again returns the same order with Idempotent-Replayed: true, and creates nothing.
A request that fails validation gets one error per problem, each pointing at the field at fault:
{
"errors": [
{
"status": "422",
"code": "validation_failed",
"title": "Validation failed",
"detail": "This field must be at least 0.",
"source": { "pointer": "/data/attributes/total_cents" },
"meta": { "request_id": "req_01m8rrzq8wq077fmxfwvqt5z3v" }
}
]
}A small client
Each example below does the same four things, which most clients need:
- sends the key, the version and the JSON:API content type on every request;
- turns error documents into an exception carrying the
codeandrequest_id; - waits for
Retry-Afterand tries again when rate limited; - follows
links.nextto read every page.
// Calls a Fusion Stack API with fetch, in Node 18+, Deno, Bun or a browser.
const BASE_URL = process.env.API_URL ?? 'http://localhost:8000';
const KEY = process.env.API_KEY;
export class ApiError extends Error {
constructor(status, errors) {
super(errors[0]?.detail ?? `HTTP ${status}`);
this.status = status;
this.errors = errors;
this.code = errors[0]?.code;
this.requestId = errors[0]?.meta?.request_id;
}
}
export async function api(path, { method = 'GET', body, idempotencyKey } = {}) {
for (let attempt = 1; ; attempt++) {
const response = await fetch(new URL(path, BASE_URL), {
method,
headers: {
Authorization: `Bearer ${KEY}`,
Accept: 'application/vnd.api+json',
'Api-Version': '2026-11-30.atlas',
...(body && { 'Content-Type': 'application/vnd.api+json' }),
...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),
},
body: body && JSON.stringify(body),
});
// Rate limited: wait as long as the API says, then try again.
if (response.status === 429 && attempt < 3) {
await new Promise((resolve) => setTimeout(resolve, Number(response.headers.get('Retry-After')) * 1000));
continue;
}
const document = response.status === 204 ? null : await response.json();
if (!response.ok) {
throw new ApiError(response.status, document.errors);
}
return document;
}
}
// Every order, following the next links page by page.
export async function* allOrders(query = '') {
let next = `/v1/orders?page[size]=100${query}`;
while (next) {
const page = await api(next);
yield* page.data;
next = page.links.next;
}
}<?php
namespace App\Services;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\LazyCollection;
use Illuminate\Support\Str;
use Throwable;
final class ShopApi
{
public function request(): PendingRequest
{
return Http::baseUrl(config('services.shop.url'))
->withToken(config('services.shop.key'))
->withHeaders(['Api-Version' => '2026-11-30.atlas'])
->accept('application/vnd.api+json')
// Rate limited: wait as long as the API says, then try again. Other errors throw at once.
->retry(
3,
fn (int $attempt, Throwable $e) => (int) $e->response->header('Retry-After') * 1000,
fn (Throwable $e) => $e instanceof RequestException && $e->response->status() === 429,
);
}
/** Every order, following the next links page by page. */
public function orders(string $query = ''): LazyCollection
{
return LazyCollection::make(function () use ($query) {
$next = "/v1/orders?page[size]=100{$query}";
while ($next !== null) {
$page = $this->request()->get($next)->json();
yield from $page['data'];
$next = $page['links']['next'];
}
});
}
public function createOrder(int $totalCents, string $currency, string $customerId): array
{
return $this->request()
// The same key on every retry of this order, so it is created once.
->withHeaders(['Idempotency-Key' => (string) Str::uuid()])
->withBody(json_encode(['data' => [
'type' => 'orders',
'attributes' => ['total_cents' => $totalCents, 'currency' => $currency],
'relationships' => ['customer' => ['data' => ['type' => 'customers', 'id' => $customerId]]],
]]), 'application/vnd.api+json')
->post('/v1/orders')
->json('data');
}
}"""Calls a Fusion Stack API with requests."""
import os
import time
import uuid
import requests
BASE_URL = os.environ.get("API_URL", "http://localhost:8000")
session = requests.Session()
session.headers.update({
"Authorization": f"Bearer {os.environ['API_KEY']}",
"Accept": "application/vnd.api+json",
"Api-Version": "2026-11-30.atlas",
})
class ApiError(Exception):
def __init__(self, status, errors):
super().__init__(errors[0]["detail"])
self.status = status
self.errors = errors
self.code = errors[0]["code"]
self.request_id = errors[0].get("meta", {}).get("request_id")
def api(method, path, json=None, idempotency_key=None):
headers = {"Content-Type": "application/vnd.api+json"} if json is not None else {}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
for attempt in range(3):
response = session.request(method, BASE_URL + path if path.startswith("/") else path, json=json, headers=headers)
# Rate limited: wait as long as the API says, then try again.
if response.status_code == 429 and attempt < 2:
time.sleep(int(response.headers["Retry-After"]))
continue
break
if not response.ok:
raise ApiError(response.status_code, response.json()["errors"])
return response.json() if response.content else None
def all_orders(params=""):
"""Every order, following the next links page by page."""
url = f"/v1/orders?page[size]=100{params}"
while url:
page = api("GET", url)
yield from page["data"]
url = page["links"]["next"]
if __name__ == "__main__":
for order in all_orders("&filter[status]=paid"):
print(order["id"], order["attributes"]["reference"], order["attributes"]["total_cents"])
# The same key on every retry of this order, so it is created once.
key = str(uuid.uuid4())
order = api("POST", "/v1/orders", idempotency_key=key, json={"data": {
"type": "orders",
"attributes": {"total_cents": 4999, "currency": "GBP"},
"relationships": {"customer": {"data": {"type": "customers", "id": "1"}}},
}})["data"]
print("created", order["id"])
try:
api("GET", "/v1/orders/999999")
except ApiError as error:
print(error.status, error.code, error.request_id)The JavaScript client is used like this, and the others the same way:
import { randomUUID } from 'node:crypto';
import { allOrders, api, ApiError } from './api.mjs';
for await (const order of allOrders('&filter[status]=paid')) {
console.log(order.id, order.attributes.reference, order.attributes.total_cents);
}
// The same key on every retry of this order, so it is created once.
const idempotencyKey = randomUUID();
const { data: order } = await api('/v1/orders', {
method: 'POST',
idempotencyKey,
body: {
data: {
type: 'orders',
attributes: { total_cents: 4999, currency: 'GBP' },
relationships: { customer: { data: { type: 'customers', id: '1' } } },
},
},
});
console.log('created', order.id);
try {
await api('/v1/orders/999999');
} catch (error) {
if (!(error instanceof ApiError)) throw error;
console.log(error.status, error.code, error.requestId);
}11 ORD-2F9ENKQD 49522
9 ORD-ZBF434VF 7732
7 ORD-1QVWBSWM 14806
created 17
404 not_found req_01m8rs1sen11cp5jkm27shadyvGenerate a new Idempotency-Key for each operation, not for each attempt: a retry of the same order must send the same key, or the API cannot tell it from a second order.
Handling errors
The code is stable; the detail is for people and may change. Handle the codes your client can do something about, and report the rest with their request_id, which the API's logs are searchable by.
| Code | What to do |
|---|---|
rate_limited | Wait Retry-After seconds, then retry. RateLimit-Remaining on every response shows how close you are. |
validation_failed | Show each error next to the field its source.pointer names. |
unauthenticated | The key is missing, wrong, expired or revoked. Retrying will not help. |
insufficient_scope | The key lacks meta.required_scope. Ask for a key with it. |
idempotency_in_progress | The first request with this key is still running. Retry shortly with the same key. |
idempotency_key_mismatch | The key was used for a different request. Use a new key. |
api_version_brownout | Your version is about to be retired. Retry after Retry-After, and upgrade. |
server_error, service_unavailable | Retry with backoff, with the same Idempotency-Key. |
Versions
Send Api-Version with the version your client was written for, and change it only when you upgrade, so the API never changes under you. A response in a deprecated version carries Deprecation and Sunset headers: log them, so you hear about them before the sunset. The changelog at /docs/changelog says what each version changed.
API keys created while versioning is on are pinned to the latest version, so a client that sends no Api-Version still gets a stable API. Sending the header makes the version visible in your own code.
Conditional requests
To poll a resource cheaply, keep its ETag and send it back:
curl -i localhost:8000/v1/orders/1 -H "Authorization: Bearer $KEY" -H 'If-None-Match: W/"f669a36b01671ca2decf7179d5dd8192"'HTTP/1.1 304 Not ModifiedA 304 has no body: use the copy you have. Browsers do this on their own; other clients need a few lines, or an HTTP cache such as requests-cache or Guzzle's cache middleware. See Caching.
Generated clients
The API's OpenAPI document describes every endpoint, query parameter, body and error, in the version you ask for:
curl -o openapi.json "https://api.example.com/docs/openapi.json?version=2026-11-30.atlas"TypeScript:
@fusion-stack/clientgenerates a client that knows your includes, filters and sorts, and flattens resources soorder.customer?.full_namejust works. See Client project setup, with its sections for Nuxt, React Native and Node.Other languages: any OpenAPI 3.1 generator reads the document, such as openapi-generator for Java, Go, C#, Swift and others, or openapi-python-client for Python:
shuvx openapi-python-client generate --path openapi.json --meta none --output-path shop_apiThese generators model the JSON:API documents as they are, with
data,attributesandincluded, so you readorder.attributes.total_cents. Their function names come from each operation, such asget_v1_orders.
Regenerate when you upgrade to a new API version, not on every release: a pinned version does not change.
AI agents
To let AI assistants call the API, serve chosen endpoints as tools with the MCP server rather than giving an agent an HTTP client. Each tool call still goes through the same keys, scopes, rate limits and idempotency.