JSON:API
Fusion Stack responses follow JSON:API, a standard shape for JSON APIs. Every resource is an object with an id, a type, its attributes and its relationships, and related resources a client asks for arrive once each in included. Clients then need one way to read every endpoint, and generated SDKs can type them all.
Responses use the content type application/vnd.api+json.
{
"data": {
"id": "16",
"type": "orders",
"attributes": {
"reference": "ORD-AUBHDUBY",
"status": "pending",
"total_cents": 1250,
"currency": "GBP"
},
"relationships": {
"customer": {
"data": {
"id": "1",
"type": "customers"
}
}
}
}
}Resources
Resources use Laravel's JsonApiResource in PHP, and a Resource registered with Config::resource in Rust. List the attributes and relationships to expose, and describe them for the API reference with #[Describe] (describe and describe_values in Rust):
#[Describe('status', 'Where the order is in fulfilment.', values: [
'pending' => 'Placed, awaiting payment',
'paid' => 'Paid, not yet shipped',
])]
#[Describe('customer', 'The customer who placed the order.')]
final class OrderResource extends JsonApiResource
{
public array $attributes = ['reference', 'status', 'total_cents', 'currency', 'created_at'];
public array $relationships = ['customer'];
}use fusion_stack::resources::{Kind, Resource};
let orders = Resource::new("orders", "orders")
.attribute("reference", Kind::String)
.attribute("status", Kind::String)
.attribute("total_cents", Kind::Integer)
.attribute("currency", Kind::String)
.attribute("created_at", Kind::Timestamp)
.nullable()
.belongs_to("customer", "customers", "customer_id")
.describe_values(
"status",
"Where the order is in fulfilment.",
[("pending", "Placed, awaiting payment"), ("paid", "Paid, not yet shipped")],
)
.describe("customer", "The customer who placed the order.");Queries
What a client may ask a collection endpoint for is declared in an ApiQuery class in PHP, or an ApiQuery value built in code in Rust. Anything not listed is rejected with a 400, so clients cannot load relationships you did not plan for or sort on columns without an index.
final class OrderQuery extends ApiQuery
{
protected string $model = Order::class;
protected array $includes = ['customer'];
protected array $fields = [
'orders' => ['reference', 'status', 'total_cents', 'currency', 'created_at', 'customer'],
'customers' => ['full_name', 'email', 'created_at', 'orders'],
];
protected array $filters = [
'status' => ['eq', 'in'],
'total_cents' => ['gte', 'lte', 'gt', 'lt'],
'search' => SearchOrders::class,
];
protected array $sorts = ['created_at', 'total_cents', 'reference'];
protected string $defaultSort = '-created_at';
}use fusion_stack::query::ApiQuery;
pub fn orders() -> ApiQuery {
ApiQuery::new("orders")
.includes(["customer"])
.fields("orders", ["reference", "status", "total_cents", "currency", "created_at", "customer"])
.fields("customers", ["full_name", "email", "created_at", "orders"])
.filter("status", ["eq", "in"])
.filter("total_cents", ["gte", "lte", "gt", "lt"])
.filter_with("search", ["eq"], search_orders)
.sorts(["created_at", "total_cents", "reference"])
.default_sort("-created_at")
}#[Endpoint('List orders', 'Orders, newest first.')]
public function index(OrderQuery $query): AnonymousResourceCollection
{
return OrderResource::collection($query->paginate());
}
#[Endpoint('Get an order')]
public function show(OrderQuery $query, string $order): OrderResource
{
return new OrderResource($query->find($order));
}use fusion_stack::openapi::Endpoint;
// Config::endpoint is #[Endpoint], keyed by method and URI.
Config::new()
.endpoint(
"GET /v1/orders",
Endpoint::new("List orders").description("Orders, newest first.").query(&orders()).collection(),
)
.endpoint("GET /v1/orders/{order}", Endpoint::new("Get an order").query(&orders()));
pub async fn index(request: Request) -> laravel::Result<Response> {
orders().paginate(&request).await
}
pub async fn show(request: Request) -> laravel::Result<Response> {
let id = request.current_route().and_then(|route| route.param("order")).unwrap_or_default().to_owned();
orders().find(&request, id).await
}The same class feeds the OpenAPI document, the generated TypeScript client and the MCP tools, so what you allow is documented once. In Rust, Endpoint::query adds it to the OpenAPI document and so to the client; the MCP tools (fusion-stack/mcp) are PHP only.
| Parameter | Example | What it does |
|---|---|---|
include | include=customer | Related resources to add to included. Each maps to an eager load, so there are no N+1 queries. Nesting is limited by query.max_include_depth (Config::max_include_depth in Rust), 3. |
fields | fields[orders]=reference,status | Sparse fieldsets: only these attributes and relationships of a type. |
filter | filter[status][in]=paid,shipped | filter[status]=paid means eq. Operators are eq, ne, gt, gte, lt, lte and in, as each filter allows. |
sort | sort=-total_cents,reference | A leading - sorts descending. |
page | page[size]=20&page[after]=… | See pagination. |
A request outside the whitelist gets an error that says what is allowed:
{
"errors": [
{
"status": "400",
"code": "invalid_filter",
"title": "Invalid filter",
"detail": "[nope] is not a filter. Available: status, total_cents, currency, search.",
"source": {
"parameter": "filter[nope]"
},
"meta": {
"request_id": "req_01m8r9qm3jc5exe4n06kgq764j"
}
}
]
}Custom filters
A filter that is not a column comparison is a class implementing Filter in PHP, and a filter_with closure or function in Rust:
/** `filter[search]=ada` matches the order reference or the customer's name. */
final class SearchOrders implements Filter
{
public function operators(): array
{
return ['eq'];
}
public function apply(Builder $query, string $operator, string $value): void
{
$query->where(fn (Builder $query) => $query
->where('reference', 'like', "%{$value}%")
->orWhereRelation('customer', 'full_name', 'like', "%{$value}%"));
}
}use laravel::db::{self, Builder, col};
/// `filter[search]=ada` matches the order reference or the customer's name.
fn search_orders(query: Builder, _operator: &str, value: &str) -> Builder {
let customers = db::table("customers").select(["id"]).filter(col("full_name").contains(value));
query.filter(col("orders.reference").contains(value) | col("orders.customer_id").is_in(customers))
}Limiting what a caller sees
Override scope() (call scope on the ApiQuery in Rust) to restrict the records a caller may see, such as to their account. It runs before filters, sorts and pagination, so no query parameter can reach past it:
protected function scope(Builder $query, ?ApiClient $client): void
{
// The signed-in user, from whichever guard authenticated the request.
$query->where('account_id', auth()->user()?->account_id);
}ApiQuery::new("orders")
// ...
.scope(|query, request| {
// The request's client, from your resolver or an API key.
let account = fusion_stack::auth::client(request).map(|client| client.id).unwrap_or_default();
query.filter(col("account").eq(account))
})Pagination
Collections use cursor pagination by default: page[size], then page[after] or page[before] from the links of a previous response. Cursors stay correct while records are added, and are fast on large tables. The default page size is 25 and the maximum 100 (query.page_size and query.max_page_size, or Config::page_sizes in Rust); larger sizes get a 400 rather than being quietly reduced.
An endpoint can use offset pagination instead, with page[number], and count the total when that is cheap enough:
protected string $pagination = 'offset';
protected bool $withTotal = true;use fusion_stack::query::Pagination;
ApiQuery::new("customers")
// ...
.pagination(Pagination::Offset { total: true }){
"links": {
"first": "http://localhost:8000/v1/customers?page[size]=2&page[number]=1",
"prev": null,
"next": "http://localhost:8000/v1/customers?page[size]=2&page[number]=2",
"last": "http://localhost:8000/v1/customers?page[size]=2&page[number]=3"
},
"meta": { "page": { "number": 1, "size": 2, "total": 5 } }
}Errors
Every error, on every endpoint, is a JSON:API error object with a stable, machine-readable code:
{ "errors": [{
"status": "422",
"code": "validation_failed",
"title": "Validation failed",
"detail": "This field must be a valid email address.",
"source": { "pointer": "/data/attributes/email" },
"meta": { "request_id": "req_01m8r9rdsfr8kycxk48f024tw2" }
}] }- Laravel's exceptions are mapped for you: validation, authentication, authorisation, model not found, throttling and method not allowed. In Rust, so are the framework's errors:
InvalidInputandValidatefailures, unknown routes, wrong methods andModelNotFound. - Validation errors have one error per field, with a JSON pointer to it. When versioning is on, the pointer uses the field names of the client's version.
meta.request_idmatches the response'sX-Request-Idheader and your logs, so a client can quote it in a support request.- Stack traces are shown only in the
localenvironment.
The package's codes, such as invalid_filter, insufficient_scope and idempotency_key_mismatch, are listed in the API reference. Add your own with an enum (a type implementing ErrorCode in Rust), list it in openapi.error_codes (Config::error_codes), and throw it with ApiException (return an ApiError in Rust):
enum ErrorCode: string implements \FusionStack\Laravel\Errors\ErrorCode
{
#[Description('The order has shipped or was already cancelled, so it cannot be cancelled.')]
case OrderNotCancellable = 'order_not_cancellable';
public function status(): int
{
return 409;
}
public function title(): string
{
return 'Order cannot be cancelled';
}
}use fusion_stack::errors::ErrorCode;
#[derive(Debug)]
pub struct OrderNotCancellable;
impl ErrorCode for OrderNotCancellable {
fn code(&self) -> &str { "order_not_cancellable" }
fn status(&self) -> u16 { 409 }
fn title(&self) -> &str { "Order cannot be cancelled" }
fn description(&self) -> &str {
"The order has shipped or was already cancelled, so it cannot be cancelled."
}
}
// Listed in the OpenAPI document with the package's codes.
Config::new().error_codes([Arc::new(OrderNotCancellable) as _])throw new ApiException(ErrorCode::OrderNotCancellable, "Order {$order->reference} is shipped, so it cannot be cancelled.");return Err(ApiError::new(
OrderNotCancellable,
format!("Order {} is shipped, so it cannot be cancelled.", order.reference),
)
.into_error());When your app also serves web pages, set errors.paths (Config::error_paths in Rust) to the API's paths, such as ['v1/*'], so the pages keep Laravel's error pages.