The recommended way to create an API instance is by passing the current Request object. This will automatically point the API to your current instance and extract the token from the headers (either from cookies or Authorization header):
import { Api } from "bknd/client";// replace this with the actual requestlet request: Request;const api = new Api({ request });
If the authentication details are contained in the current request, but you're hosting your bknd instance somewhere else, you can specify a host option:
import { Api } from "bknd/client";// replace this with the actual requestlet request: Request;const api = new Api({ host: "https://<your-endpoint>", request,});
In case the place where you're using the API is the same as your bknd instance (e.g. when using it embedded in a React framework), you can specify a fetcher option to point to your bknd app. This way, requests won't travel over the network and instead processed locally:
import type { App } from "bknd";import { Api } from "bknd/client";// replace this with your actual `App` instancelet app: App;const api = new Api({ fetcher: app.server.request as typeof fetch, // specify `host` and `token` or `request`});
To retrieve a list of records from an entity, use the readMany method:
const { data } = await api.data.readMany("posts");
You can also add additional query instructions:
const { data } = await api.data.readMany("posts", { limit: 10, offset: 0, select: ["id", "title", "views"], with: { // join last 2 comments comments: { with: { // along with the comments' user users: {}, }, limit: 2, sort: "-id", }, // also get the first 2 images, but only the path images: { select: ["path"], limit: 2, }, }, where: { // same as '{ title: { $eg: "Hello, World!" } }' title: "Hello, World!", // only with views greater than 100 views: { $gt: 100, }, }, // sort by views descending (without "-" would be ascending) sort: "-views",});
The with property automatically adds the related entries to the response.
Access the Auth specific API methods at api.auth. If there is successful authentication, the
API will automatically save the token and use it for subsequent requests.