Skip to main content
Version: 1.x

Quick Start

To get started with OpenAPI Qraft, you first need to generate types from your OpenAPI Document, and also generate services that will use these types to interact with your API.

1. Generate OpenAPI Types & Servicesโ€‹

Assumed that you already installed @openapi-qraft/react package โœ…

Run the following command in the root directory of your project using your package manager.

npx @openapi-qraft/cli@next --plugin tanstack-query-react --plugin openapi-typescript \
--output-dir src/api https://raw.githubusercontent.com/swagger-api/swagger-petstore/master/src/main/resources/openapi.yaml
info

openapi-qraft creates service files in the src/api directory of your project:

src/
โ”œโ”€โ”€ api/
โ”‚ โ”œโ”€โ”€ schema.d.ts # โฌ…๏ธŽ Types generated by `--plugin openapi-typescript`
โ”‚ โ”‚ # โฌ‡๏ธŽ Files generated by `--plugin tanstack-query-react`
โ”‚ โ”œโ”€โ”€ create-api-client.ts # Generated function to create the API client
โ”‚ โ””โ”€โ”€ services/ # Generated services
โ”‚ โ”œโ”€โ”€ PetService.ts
โ”‚ โ”œโ”€โ”€ StoreService.ts
โ”‚ โ””โ”€โ”€ UserService.ts
  • --clean option could be useful. With the option, src/api/services directory will be cleared before the new services are generated.

2. Use the generated services in your React applicationโ€‹

Here are examples of how to use the generated services in your React application with useQuery, useMutation, and useInfiniteQuery hooks from TanStack Query.

src/App.tsx
import { createAPIClient } from './api'; // generated by OpenAPI Qraft

import { QraftContext, requestFn } from '@openapi-qraft/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useMemo } from 'react';

// The `createAPIClient(...)` function is generated by OpenAPI Qraft
// The `qraft` object could be created in a separate file and imported,
// or created multiple times in different components.
// It's just a shortcut to TanStack Query Hooks!
const qraft = createAPIClient();

function ExamplePetDetails({ petId }: { petId: number }) {
/**
* Executes the request to the API on mount:
* ###
* GET /pet/123456
**/
const {
data: pet,
isPending,
error,
} = qraft.pet.getPetById.useQuery({
path: { petId },
});

if (isPending) {
return <div>Loading...</div>;
}

if (error) {
return <div>Error: {error.message}</div>;
}

return <div>Pet Name: {pet?.name}</div>;
}

export default function App() {
const queryClient = useMemo(() => new QueryClient(), []);

return (
<QueryClientProvider client={queryClient}>
<QraftContext.Provider
value={{
baseUrl: 'https://petstore3.swagger.io/api/v3', // the base URL of the API
requestFn, // the request function to use, could be fully customized
}}
>
<ExamplePetDetails petId={123456} />
</QraftContext.Provider>
</QueryClientProvider>
);
}