7. Generate the SDK and build a Nuxt page
The API has orders, but the web app from step 2 only shows teams. In this step you generate a typed client for the API, and use it to build an orders page in the Nuxt app: a list with each order's team, a status filter, and a button that emails the invoice.
Generate the client
The API describes itself in an OpenAPI document: every endpoint, what it accepts and what it returns, built from your code. It is what http://localhost:8000/docs shows. From it, Fusion Stack generates a TypeScript client, the SDK, so the web app knows the API's shape as well as the API does.
Run this in the shop folder, not in api:
cd ..
npm run apiINFO Everything in the API reference has a description.
INFO Wrote the OpenAPI document for the API to [openapi.json].
Wrote packages/client/index.tsIt does three things: checks that every endpoint and field is described, writes api/openapi.json, and regenerates packages/client/index.ts. Open that file: it has an Order type with your descriptions as comments, and a function for each endpoint, such as ordersIndex and invoiceEmailsStore.
Run npm run api whenever you change the API, and commit the three files together. A pull request then shows a change to the API and what it means for the frontend side by side.
Build the page
Nuxt turns each file in web/app/pages into a page. Create the orders page:
<script setup lang="ts">
import { ApiError } from '@fusion-stack/client';
import { invoiceEmailsStore, ordersIndex, type Order } from '@app/client';
const statuses = ['pending', 'paid', 'shipped', 'cancelled'] as const;
type Status = (typeof statuses)[number];
// The filter lives in the URL, as ?status=paid, so a filtered list can be shared and reloaded.
const route = useRoute();
const status = computed<Status | ''>({
get: () => statuses.find((s) => s === route.query.status) ?? '',
set: (value) => navigateTo({ query: value === '' ? {} : { status: value } }),
});
// Typed against the API: include('team') and filter('status', …) are checked when you build.
const { data, error, pending } = await useApiData(ordersIndex, () => ({
query: (q) => {
const query = q.include('team').fields('teams', ['name']);
return status.value === '' ? query : query.filter('status', status.value);
},
}));
const money = (order: Order) => new Intl.NumberFormat('en-GB', { style: 'currency', currency: order.currency }).format(order.total_cents / 100);
const api = useApi();
const to = ref('accounts@example.com');
const message = ref('');
const failed = ref(false);
async function sendInvoice(order: Order) {
message.value = '';
failed.value = false;
try {
// The client sends an Idempotency-Key, and reuses it if it retries, so a retry never sends two.
await api.call(invoiceEmailsStore, {
body: { data: { type: 'invoice-emails', attributes: { to: to.value }, relationships: { order: { data: { id: order.id } } } } },
});
message.value = `Sent the invoice for order ${order.id} to ${to.value}.`;
} catch (e) {
failed.value = true;
// Your own error code from step 6, checked like any other.
message.value = e instanceof ApiError && e.code === 'order_not_paid' ? `Order ${order.id} is not paid yet.` : String(e);
}
}
</script>
<template>
<h1>Orders</h1>
<div class="bar">
<label>Status
<select v-model="status" data-test="status">
<option value="">Any</option>
<option v-for="s in statuses" :key="s" :value="s">{{ s }}</option>
</select>
</label>
<label>Send invoices to <input v-model="to" type="email" data-test="to"></label>
</div>
<p v-if="message" :class="failed ? 'error' : 'notice'" data-test="message">{{ message }}</p>
<p v-if="error" class="error">{{ error.message }} ({{ error.data?.code }})</p>
<table :class="{ pending }">
<thead><tr><th>Order</th><th>Team</th><th>Status</th><th>Total</th><th /></tr></thead>
<tbody>
<tr v-for="order in data?.data" :key="order.id" data-test="order">
<td>{{ order.id }}</td>
<td data-test="team">{{ order.team?.name }}</td>
<td>{{ order.status }}</td>
<td>{{ money(order) }}</td>
<td><button @click="sendInvoice(order)">Send invoice</button></td>
</tr>
</tbody>
</table>
</template>A few things to notice:
useApiDatafetches on the server, so the first page load arrives with the orders already in it, and fetches again in the browser whenstatuschanges.- The query is typed.
include('team')andfilter('status', …)only accept whatOrderQueryallows. Ask forfilter('colour', …)and the build fails, instead of the API refusing it in production. order.team?.name. The client resolvesincludedfor you: each order'steamis the team object itself.- Errors have codes.
order_not_paid, the code you added in step 6, gets its own message.
Add a link to it in the header, in web/app/app.vue:
<header>
<NuxtLink to="/" class="brand">My App</NuxtLink>
+ <NuxtLink to="/orders">Orders</NuxtLink>
<button v-if="token" data-test="sign-out" @click="signOut">Sign out</button>Check the types
npm run typecheckThis checks the whole web app against the generated client, and prints nothing more when all is well. Run it, or let your editor do it as you type, after each npm run api: when an API change breaks the frontend, this is where you find out.
Try it
Open http://localhost:3000/orders in your browser, signed in as in step 2. Choose paid in the status filter: the URL becomes /orders?status=paid, and two orders remain. Click Send invoice on order 1, which is pending, to see your error message, and on a paid order to send one.
The page is rendered on the server first. You can see its HTML with curl: the web app sends the token in its fusion_stack_token cookie to the API, and your API key works there too:
curl -s "localhost:3000/orders?status=paid" -b "fusion_stack_token=$KEY" | grep -o 'data-test="team">[^<]*'data-test="team">Acme Ltd
data-test="team">Globexnpm run api says an endpoint or field has no description
The client and the API reference are only as good as their descriptions, so a missing one stops it. Add the #[Describe], #[Endpoint] or describe() entry it names, and run it again.
The page shows an error, or is empty
Check that npm run dev is still running, and that you are signed in: the sign-in page is at http://localhost:3000/login. If you changed the API, run npm run api again, so the client matches it.
npm run typecheck reports errors in orders.vue
Usually the client is older than the page: run npm run api, then the typecheck again. Otherwise the message names the line, and the type the API expects there.
Next: your first breaking change.