createAPIClient(...)
Qraft CLI generates a helper function createAPIClient(...), which creates a Qraft API client with
the necessary requestFn, baseUrl and queryClient for React Hooks.
- Full Power 🔋
- Vanilla
fetch🫛 - Only
QueryClient🔧 - No requests 🛜
To use Qraft with a complete set of methods and React hooks, you need to provide queryClient,
requestFn, and baseUrl. This setup allows you to use the API client for both React and Node.js.
import { createAPIClient } from './api'
const api = createAPIClient({
queryClient,
requestFn,
baseUrl,
})
Arguments
options: QraftClientOptions- Required options to be used by the Qraft API clientoptions.queryClient- RequiredQueryClientinstance to be used by Qraft Hooks.options.requestFn- RequiredrequestFnfunction to be used by Qraft Hooks.options.baseUrl- Required base URL for therequestFnfunction.
Returns
- Qraft API client with the necessary React Hooks for operations. It contains all the methods to interact with the API grouped in services.
In rare cases when you don't want to use QueryClient, you can create an API client with pure-fetch methods.
These can be used for utility purposes when you don't need retry or caching functionality.
import { createAPIClient } from './api'
const api = createAPIClient({
requestFn,
baseUrl,
})
Arguments
options: QraftClientOptions- Required options to be used by the Qraft API clientoptions.requestFn- RequiredrequestFnfunction to be used by Qraft requests.options.baseUrl- Required base URL for therequestFnfunction.
Returns
- Qraft API client without
QueryClient.
If you need to type-safe QueryClient methods like setQueryData(), getQueryState(), or invalidateQueries(),
you can create an API client with only QueryClient provided.
import { createAPIClient } from './api'
const api = createAPIClient({ queryClient })
Arguments
options: QraftClientOptions- Required options to be used by the Qraft API clientoptions.queryClient- RequiredQueryClientinstance to be used by Qraft Hooks.
Returns
- Qraft API client without request methods and React Hooks.
If you only need to type QueryKey or MutationKey, you can create an API client without options.
In this case, be aware that only methods that create typed QueryKey or MutationKey will be available.
import { createAPIClient } from './api'
const api = createAPIClient()
Returns
- Qraft API client with
QueryKeyandMutationKeycomposition methods.
Examples
- Full Power 🔋
- Vanilla
fetch🫛 - Multiple API versions and React
Context
import { requestFn } from '@openapi-qraft/react';
import { createAPIClient } from './api'; // generated by OpenAPI Qraft CLI
import { QueryClient, dehydrate } from '@tanstack/react-query';
const queryClient = new QueryClient();
// ⬇︎ Create a Qraft API client
const api = createAPIClient({
requestFn,
queryClient,
baseUrl: 'https://api.sandbox.monite.com/v1',
});
// ⬇︎ Fetch the `getPetById` query with the `queryClient`
const pet = await api.pet.getPetById.fetchQuery(
{ parameters: { path: { petId: 1 } } }
);
console.log(pet.name);
dehydrate(queryClient); // Dehydrate the `queryClient` to be used for SSR
// ⬇︎ Qraft API client usage in React
function PetDetailsComponent() {
const { data: pet } = api.pet.getPetById.useQuery({ path: { petId: 1 } });
return <div>{pet?.name}</div>;
}
import { requestFn } from '@openapi-qraft/react';
import { createAPIClient } from './api'; // generated by OpenAPI Qraft CLI
const api = createAPIClient({
requestFn,
baseUrl: 'https://petstore3.swagger.io/api/v3',
});
/**
* Executes the request:
* ###
* GET /posts?limit=10
**/
const posts = await api.posts.getPosts(
{
parameters: { query: { limit: 10 } }
}
);
In this example, we create multiple API clients that manage two different API versions, each with its own QueryClient.
This approach mounts and unmounts QueryClient instances during the lifecycle of the application.
This setup is particularly useful when you need to work with different API versions simultaneously, or when you're in the process of migrating from one API version to another.
import { createAPIClient as createAPIClientV1Basic } from './api-v1'; // generated by OpenAPI Qraft CLI (1️⃣)
import { createAPIClient as createAPIClientV2Basic } from './api-v2'; // generated by OpenAPI Qraft CLI (2️⃣)
import { requestFn, type CreateAPIBasicClientOptions, type CreateAPIQueryClientOptions } from '@openapi-qraft/react';
import { createContext, useContext, useMemo, useEffect, type ReactNode} from "react";
import { QueryClient } from '@tanstack/react-query'
// Hypothetical legacy API Client
function createAPIClientV1(options: CreateAPIQueryClientOptions) {
return createAPIClientV1Basic(options);
}
// New version API Client
function createAPIClientV2(options: CreateAPIQueryClientOptions) {
return createAPIClientV2Basic(options);
}
const MultipleAPIClientsContext = createContext<{
apiV1: ReturnType<typeof createAPIClientV1>; // 1️⃣
apiV2: ReturnType<typeof createAPIClientV2>; // 2️⃣
}>(null!);
export default function MultipleAPIClientsApp({ children }: { children: ReactNode }) {
const queryClient1 = useMemo(() => new QueryClient(), []);
const queryClient2 = useMemo(() => new QueryClient(), []);
// Hypothetical legacy API Client without Query Client feature
const apiV1 = useMemo(() => createAPIClientV1({
requestFn,
queryClient: queryClient1,
baseUrl: 'https://api.sandbox.monite.com/v1',
}), [queryClient1]);
// New version API Client with the modern features
const apiV2 = useMemo(() => createAPIClientV2({
requestFn,
queryClient: queryClient2,
baseUrl: 'https://api.sandbox.monite.com/v2',
}), [queryClient2]);
useEffect(() => {
queryClient1.mount();
queryClient2.mount();
return () => {
queryClient1.unmount();
queryClient2.unmount();
};
}, [queryClient1, queryClient2]);
return (
<MultipleAPIClientsContext.Provider value={{ apiV1, apiV2 }}>
{children}
</MultipleAPIClientsContext.Provider>
);
}
function YourComponents() {
const { apiV1, apiV2 } = useContext(MultipleAPIClientsContext);
// Use `apiV1` and `apiV2` as needed
// ...
}