jarvisbox

OpenAPI to React Query types in browser

Generate a paths interface from your OpenAPI spec and wire it to TanStack Query via openapi-fetch — fully typed useQuery and useMutation hooks with zero boilerplate.

The combination of openapi-typescript types + openapi-fetch + TanStack Query is rapidly becoming the standard pattern for type-safe API integration in React applications. The workflow: generate a paths interface from your OpenAPI spec, create a typed client with createClient<paths>(), then use @openapi-qraft/react or a thin wrapper to get fully typed useQuery and useMutation hooks where parameter types, request body types, and response types are all inferred automatically.

The bottleneck is generating the paths interface — normally requiring npx openapi-typescript spec.yaml -o types.d.ts. The OpenAPI to TypeScript browser generator eliminates that step: paste your spec and download types.d.ts in seconds, ready to drop into your React project.

Using the generated types with TanStack Query

// 1. Import the generated types
import type { paths } from "./types";

// 2. Create a typed client
import createClient from "openapi-fetch";
const client = createClient<paths>({ baseUrl: "/api" });

// 3. Wrap with TanStack Query
import { useQuery } from "@tanstack/react-query";

function useUser(id: number) {
  return useQuery({
    queryKey: ["/users/{id}", { path: { id } }],
    queryFn: async () => {
      const { data, error } = await client.GET("/users/{id}", {
        params: { path: { id } },
      });
      if (error) throw error;
      return data;
    },
  });
}
// data is typed as components["schemas"]["User"] automatically

How to generate types for React Query

  1. Paste your OpenAPI spec (JSON or YAML) into OpenAPI to TypeScript Types and click Generate TypeScript. Download types.d.ts.
  2. Install openapi-fetch and @tanstack/react-query in your project. Import your paths type and create a typed client as shown above.
  3. Wrap each API call in a useQuery or useMutation hook. TypeScript will infer the correct parameter shapes and response types from the generated paths interface.

Related tools

回報這個工具的問題