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 } }
}
);
This example demonstrates how to use multiple API clients with React Context. With the context: option
in CLI, you can generate an API client that retrieves queryClient, requestFn, and baseUrl from
React Context at render time.
Creating the API client outside of the component with the context: option makes hooks static,
allowing React Compiler to optimize them. If you create the client inside useMemo, hooks become
dynamic and cannot be optimized by React Compiler.
import { createAPIClient as createAPIClientV1, APIClientContextV1 } from './api-v1'; // generated with context:APIClientContextV1
import { createAPIClient as createAPIClientV2, APIClientContextV2 } from './api-v2'; // generated with context:APIClientContextV2
import { requestFn } from '@openapi-qraft/react';
import { useEffect, useState, type ReactNode } from "react";
import { QueryClient } from '@tanstack/react-query'
// ⬇︎ Create API clients OUTSIDE of the component - hooks are static and React Compiler compatible
const apiV1 = createAPIClientV1(); // Uses APIClientContextV1 for options
const apiV2 = createAPIClientV2(); // Uses APIClientContextV2 for options
export default function MultipleAPIClientsApp({ children }: { children: ReactNode }) {
const [queryClient1] = useState(() => new QueryClient());
const [queryClient2] = useState(() => new QueryClient());
useEffect(() => {
queryClient1.mount();
queryClient2.mount();
return () => {
queryClient1.unmount();
queryClient2.unmount();
};
}, [queryClient1, queryClient2]);
return (
<APIClientContextV1.Provider value={{ requestFn, queryClient: queryClient1, baseUrl: 'https://api.example.com/v1' }}>
<APIClientContextV2.Provider value={{ requestFn, queryClient: queryClient2, baseUrl: 'https://api.example.com/v2' }}>
{children}
</APIClientContextV2.Provider>
</APIClientContextV1.Provider>
);
}
function YourComponent() {
// ⬇︎ Use hooks directly - they read options from Context
const { data: v1Data } = apiV1.pets.getPets.useQuery();
const { data: v2Data } = apiV2.pets.getPets.useQuery();
return <div>...</div>;
}
For more details on configuring and using the Context-based API client, see the Context-based API Client documentation.