Skip to main content
Version: 2.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 { 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>
);
}