Skip to main content
Version: 2.x

Quick Start

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

1. Generate OpenAPI Types & Servicesโ€‹

Make sure you have already installed the @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 generates 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
  • The --clean option is available if you want to clear the src/api/services directory before generating new services.

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

Below are examples demonstrating 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 { requestFn } from '@openapi-qraft/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

// Use `createAPIClient(...)` to initialize the API client as needed.
// It's a lightweight ๐Ÿชถ shortcut for working with TanStack Query ๐ŸŒด
const api = createAPIClient({
requestFn,
queryClient,
baseUrl: 'https://petstore3.swagger.io/api/v3',
});

function ExamplePetDetails({ petId }: { petId: number }) {
/**
* Executes the request to the API on mount:
* ###
* GET /pet/123456
**/
const {
data: pet,
isPending,
error,
} = api.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() {
return (
<QueryClientProvider client={queryClient}>
<ExamplePetDetails petId={123456} />
</QueryClientProvider>
);
}