### Setup and run development server Source: https://github.com/openapi-ts/openapi-typescript/blob/main/packages/openapi-fetch/examples/nextjs/README.md Install dependencies and start the local development server. ```sh pnpm i pnpm run dev ``` -------------------------------- ### Initialize and Run Development Server Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/README.md Installs project dependencies and starts the Vitepress development server. Requires Node.js and pnpm to be installed on the host machine. ```bash pnpm i pnpm run dev ``` -------------------------------- ### Install openapi-fetch and openapi-typescript Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/index.md Instructions for installing the openapi-fetch and openapi-typescript libraries using npm. ```bash npm i openapi-fetch npm i -D openapi-typescript typescript ``` -------------------------------- ### Install openapi-react-query and Dependencies Source: https://github.com/openapi-ts/openapi-typescript/blob/main/packages/openapi-react-query/README.md Installs the necessary packages for openapi-react-query, including openapi-fetch for making requests and openapi-typescript for generating types. TypeScript and the schema generator are installed as development dependencies. ```bash npm i openapi-react-query openapi-fetch npm i -D openapi-typescript typescript ``` -------------------------------- ### Fetch Data with openapi-typescript-fetch Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/examples.md Illustrates data fetching using the openapi-typescript-fetch library. This example shows how to create a fetcher instance, make GET and PUT requests, and handle responses and errors using try-catch blocks. ```typescript import { Fetcher } from 'openapi-typescript-fetch'; import type { paths } from './my-openapi-3-schema'; // generated by openapi-typescript const fetcher = Fetcher.for(); // GET request const getBlogPost = fetcher.path('/blogposts/{post_id}').method('get').create(); try { const { status, data } = await getBlogPost({ pathParams: { post_id: '123' } }); console.log(data); } catch (error) { console.error('Error:', error); } // PUT request const updateBlogPost = fetcher.path('/blogposts').method('put').create(); try { await updateBlogPost({ body: { title: 'My New Post' } }); } catch (error) { console.error('Error:', error); } ``` -------------------------------- ### Install dependencies and generate types Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/index.md Commands to install the necessary packages and generate TypeScript types from an OpenAPI schema file. ```bash npm i openapi-react-query openapi-fetch npm i -D openapi-typescript typescript npx openapi-typescript ./path/to/api/v1.yaml -o ./src/lib/api/v1.d.ts ``` -------------------------------- ### React Infinite Data Fetching with useInfiniteQuery Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/use-infinite-query.md Demonstrates how to use the `useInfiniteQuery` hook from `openapi-typescript` to fetch paginated lists of posts. It includes rendering the data, a 'Load More' button, and handling loading states. This example assumes a React environment and the setup of `$api` from `openapi-fetch` and `openapi-react-query`. ```tsx import { $api } from "./api"; const PostList = () => { const { data, fetchNextPage, hasNextPage, isFetching } = $api.useInfiniteQuery( "get", "/posts", { params: { query: { limit: 10, }, }, }, { getNextPageParam: (lastPage) => lastPage.nextPage, initialPageParam: 0, } ); return (
{data?.pages.map((page, i) => (
{page.items.map((post) => (
{post.title}
))}
))} {hasNextPage && ( )}
); }; export const App = () => { return ( `Error: ${error.message}`}> ); }; ``` -------------------------------- ### Initialize Client and Perform HTTP Requests Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/index.md Demonstrates how to initialize an openapi-fetch client with a base URL and perform GET and PUT requests using type-safe parameters derived from an OpenAPI schema. ```typescript import createClient from "openapi-fetch"; import type { paths } from "./my-openapi-3-schema"; const client = createClient({ baseUrl: "https://myapi.dev/v1/" }); const { data, error } = await client.GET("/blogposts/{post_id}", { params: { path: { post_id: "my-post" }, query: { version: 2 }, }, }); const { data: putData, error: putError } = await client.PUT("/blogposts", { body: { title: "New Post", body: "

New post body

", publish_date: new Date("2023-03-01T12:00:00Z").getTime(), }, }); ``` -------------------------------- ### Fetch Data with openapi-axios Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/examples.md Demonstrates using openapi-axios for data fetching with Axios. It shows two strategies for handling response status: 'axios' (throws on 4xx/5xx) and 'fetch' (throws on network errors). Includes examples for GET requests and error checking. ```typescript import { OpenApiAxios } from "@web-bee-ru/openapi-axios"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript import Axios from "axios"; const axios = Axios.create({ baseURL: "https://myapi.dev/v1", adapter: "fetch", // strongly recommended (available since axios@1.7.0) }); // Example 1. Usage with "axios" (default) status handling strategy (validStatus: 'axios') const api = new OpenApiAxios(axios, { validStatus: "axios" }); // throws like axios (e.g. status 400+, network errors, interceptor errors) // const api = new OpenApiAxios(axios) // same result try { const { status, data, response } = await api.get("/users"); } catch (err) { if (api.isAxiosError(err)) { if (typeof err.status === "number") { // status >= 400 } // request failed (e.g. network error) } throw err; // axios.interceptors error } // Example 2. Usage with "fetch" status handling strategy (validStatus: 'fetch') const fetchApi = new OpenApiAxios(axios, { validStatus: "fetch" }); // throws like browser's fetch() (e.g. network errors, interceptor errors) try { const { status, data, error, response } = await api.get("/users"); ``` -------------------------------- ### Fetch Data with feature-fetch Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/examples.md Shows how to use the feature-fetch library for OpenAPI data fetching. This example demonstrates creating a fetch client, making GET and PUT requests, and handling responses using both if-else and try-catch with specific error types like NetworkError and RequestError. ```typescript import { createOpenApiFetchClient } from 'feature-fetch'; import type { paths } from './my-openapi-3-schema'; // generated by openapi-typescript // Create the OpenAPI fetch client const fetchClient = createOpenApiFetchClient({ prefixUrl: 'https://myapi.dev/v1' }); // Send a GET request const response = await fetchClient.get('/blogposts/{post_id}', { pathParams: { post_id: '123', }, }); // Handle the response (Approach 1: Standard if-else) if (response.isOk()) { const data = response.value.data; console.log(data); // Handle successful response } else { const error = response.error; if (error instanceof NetworkError) { console.error('Network error:', error.message); } else if (error instanceof RequestError) { console.error('Request error:', error.message, 'Status:', error.status); } else { console.error('Service error:', error.message); } } // Send a PUT request const putResponse = await fetchClient.put('/blogposts', { body: { title: 'My New Post', }, }); // Handle the response (Approach 2: Try-catch) try { const putData = putResponse.unwrap().data; console.log(putData); // Handle the successful response } catch (error) { // Handle the error if (error instanceof NetworkError) { console.error('Network error:', error.message); } else if (error instanceof RequestError) { console.error('Request error:', error.message, 'Status:', error.status); } else { console.error('Service error:', error.message); } } ``` -------------------------------- ### Example API Test with Mocked Responses Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/examples.md This TypeScript test suite demonstrates how to use the `mockResponses` helper function to typecheck API mocks against an OpenAPI schema using `vitest` and `vitest-fetch-mock`. It defines mock data for different endpoints and HTTP methods, then makes `fetch` calls to verify that the mocks are correctly set up and that the responses conform to the expected structure. The example includes tests for GET, DELETE, and PUT requests with various status codes. ```typescript import { mockResponses } from "../test/utils"; describe("My API test", () => { it("mocks correctly", async () => { mockResponses({ "/users/{user_id}": { // ✅ Correct 200 response get: { status: 200, body: { id: "user-id", name: "User Name" } }, // ✅ Correct 403 response delete: { status: 403, body: { code: "403", message: "Unauthorized" } }, }, "/users": { // ✅ Correct 201 response put: { 201: { status: "success" } }, }, }); // test 1: GET /users/{user_id}: 200 await fetch("/users/user-123"); // test 2: DELETE /users/{user_id}: 403 await fetch("/users/user-123", { method: "DELETE" }); // test 3: PUT /users: 200 await fetch("/users", { method: "PUT", body: JSON.stringify({ id: "new-user", name: "New User" }), }); // test cleanup fetchMock.resetMocks(); }); }); ``` -------------------------------- ### Install openapi-typescript and TypeScript Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/node.md Installs the necessary packages for using openapi-typescript and TypeScript in your Node.js project. ```bash npm i --save-dev openapi-typescript typescript ``` -------------------------------- ### API Client Setup with openapi-fetch and openapi-react-query Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/use-infinite-query.md Sets up a typed API client using `openapi-fetch` and `openapi-react-query`. It defines the base URL and imports the generated schema types from `openapi-typescript`. This client, `$api`, is then used for making typed API requests. ```ts import createFetchClient from "openapi-fetch"; import createClient from "openapi-react-query"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript const fetchClient = createFetchClient({ baseUrl: "https://myapi.dev/v1/", }); export const $api = createClient(fetchClient); ``` -------------------------------- ### Create and Use Type-Safe Fetch Client with openapi-fetch Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/index.md Demonstrates how to create a type-safe fetch client using openapi-fetch and an OpenAPI schema generated by openapi-typescript. It shows how to make GET and PUT requests, and highlights the automatic type checking for request parameters, bodies, and responses. ```typescript import createClient from "openapi-fetch"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript const client = createClient({ baseUrl: "https://myapi.dev/v1/" }); const { data, // only present if 2XX response error, // only present if 4XX or 5XX response } = await client.GET("/blogposts/{post_id}", { params: { path: { post_id: "123" }, }, }); await client.PUT("/blogposts", { body: { title: "My New Post", }, }); ``` -------------------------------- ### Install openapi-typescript dependencies Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/introduction.md Install the necessary packages via npm to begin generating types from your OpenAPI schema. ```bash npm i -D openapi-typescript typescript ``` -------------------------------- ### Fetch Options Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/api.md This section details the available options that can be passed to any request method (GET, POST, etc.) to customize fetch behavior. ```APIDOC ## Fetch Options The following options apply to all request methods (`.GET()`, `.POST()`, etc.) ```ts client.GET("/my-url", options); ``` ### Parameters - **params** (ParamsObject) - Description: [path](https://swagger.io/specification/#parameter-locations) and [query](https://swagger.io/specification/#parameter-locations) params for the endpoint - **body** ({ [name]:value }) - Description: [requestBody](https://spec.openapis.org/oas/latest.html#request-body-object) data for the endpoint - **querySerializer** (QuerySerializer) - Description: (optional) Provide a [querySerializer](#queryserializer) - **bodySerializer** (BodySerializer) - Description: (optional) Provide a [bodySerializer](#bodyserializer) - **pathSerializer** (PathSerializer) - Description: (optional) Provide a [pathSerializer](#pathserializer) - **parseAs** ("json" | "text" | "arrayBuffer" | "blob" | "stream") - Description: (optional) Parse the response using [a built-in instance method](https://developer.mozilla.org/en-US/docs/Web/API/Response#instance_methods) (default: "json"). "stream" skips parsing altogether and returns the raw stream. - **baseUrl** (string) - Description: Prefix the fetch URL with this option (e.g. "https://myapi.dev/v1/") - **fetch** (fetch) - Description: Fetch instance used for requests (default: fetch from `createClient`) - **middleware** (Middleware[]) - Description: [See docs](/openapi-fetch/middleware-auth) - **(Fetch options)** - Description: Any valid fetch option (`headers`, `mode`, `cache`, `signal`, …) ([docs](https://developer.mozilla.org/en-US/docs/Web/API/fetch#options)) ### Request Example ```json { "params": { "userId": "123" }, "body": { "name": "example" }, "headers": { "Authorization": "Bearer YOUR_TOKEN" } } ``` ### Response - **(Response Data)** - Description: Depends on the endpoint and `parseAs` option. ### Response Example ```json { "message": "Success" } ``` ``` -------------------------------- ### Execute API Request with Fetch Options Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/api.md Demonstrates how to invoke a GET request using the openapi-typescript client. This snippet shows the basic structure for passing a URL and an options object to configure the request. ```typescript client.GET("/my-url", options); ``` -------------------------------- ### Basic API Request with openapi-fetch (TypeScript) Source: https://github.com/openapi-ts/openapi-typescript/blob/main/packages/openapi-fetch/README.md This snippet shows how to initialize an openapi-fetch client with a specific OpenAPI schema and make GET and PUT requests. It demonstrates passing parameters for path and query, and providing a request body. The code leverages TypeScript for type safety, inferring types from the OpenAPI schema. ```TypeScript import createClient from "openapi-fetch"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript const client = createClient({ baseUrl: "https://myapi.dev/v1/" }); const { data, error } = await client.GET("/blogposts/{post_id}", { params: { path: { post_id: "my-post" }, query: { version: 2 }, }, }); const { data, error } = await client.PUT("/blogposts", { body: { title: "New Post", body: "

New post body

", publish_date: new Date("2023-03-01T12:00:00Z").getTime(), }, }); ``` -------------------------------- ### Transform OpenAPI binary format to Blob type Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/node.md This example shows how to map binary schema formats to Blob types, which is useful for multipart/form-data file upload handling. ```typescript import openapiTS from "openapi-typescript"; import ts from "typescript"; const BLOB = ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("Blob")); const NULL = ts.factory.createLiteralTypeNode(ts.factory.createNull()); const ast = await openapiTS(mySchema, { transform(schemaObject, metadata) { if (schemaObject.format === "binary") { return schemaObject.nullable ? ts.factory.createUnionTypeNode([BLOB, NULL]) : BLOB; } }, }); ``` -------------------------------- ### React App Integration with useQuery Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/use-query.md Demonstrates how to use the `useQuery` hook from `openapi-react-query` within a React component to fetch user data. It shows handling loading and error states, and accessing typed response data. This example assumes an API client `$api` is already configured. ```tsx import { $api } from "./api"; export const App = () => { const { data, error, isLoading } = $api.useQuery("get", "/users/{user_id}", { params: { path: { user_id: 5 }, }, }); if (!data || isLoading) return "Loading..."; if (error) return `An error occured: ${error.message}`; return
{data.firstname}
; }; ``` -------------------------------- ### Use Suspense Query with React Components Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/use-suspense-query.md Demonstrates how to use the `useSuspenseQuery` hook within a React component to fetch data. It includes setting up an `ErrorBoundary` for handling potential errors during data fetching and displaying the fetched data. This example assumes an API client `$api` has been configured. ```tsx import { ErrorBoundary } from "react-error-boundary"; import { $api } from "./api"; const MyComponent = () => { const { data } = $api.useSuspenseQuery("get", "/users/{user_id}", { params: { path: { user_id: 5 }, }, }); return
{data.firstname}
; }; export const App = () => { return ( `Error: ${error.message}`}> ); }; ``` -------------------------------- ### Mocking API Responses with Mock Service Worker Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/testing.md Provides an example of using Mock Service Worker (MSW) to mock API responses for testing openapi-fetch. This method is recommended for a more integrated testing approach, allowing you to simulate various API responses and test your client's handling of them. It requires `msw`, `openapi-fetch`, and a test runner like Vitest. ```typescript import { http, HttpResponse } from "msw"; import { setupServer } from "msw/node"; import createClient from "openapi-fetch"; import { afterEach, beforeAll, afterAll, expect, test } from "vitest"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript const server = setupServer(); beforeAll(() => { // NOTE: server.listen must be called before `createClient` is used to ensure // the msw can inject its version of `fetch` to intercept the requests. server.listen({ onUnhandledRequest: (request) => { throw new Error( `No request handler found for ${request.method} ${request.url}` ); }, }); }); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); test("my API call", async () => { const rawData = { test: { data: "foo" } }; const BASE_URL = "https://my-site.com"; server.use( http.get(`${BASE_URL}/api/v1/foo`, () => HttpResponse.json(rawData, { status: 200 }) ) ); const client = createClient({ baseUrl: BASE_URL, }); const { data, error } = await client.GET("/api/v1/foo"); expect(data).toEqual(rawData); expect(error).toBeUndefined(); }); ``` -------------------------------- ### Initialize Fetch Client and React Query API Client Source: https://github.com/openapi-ts/openapi-typescript/blob/main/packages/openapi-react-query/README.md Sets up the API client by first creating a fetch client with a base URL and schema type, then initializing the openapi-react-query client with this fetch client. This client will be used for making type-safe API calls. ```tsx import createFetchClient from "openapi-fetch"; import createClient from "openapi-react-query"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript const fetchClient = createFetchClient({ baseUrl: "https://myapi.dev/v1/", }); const $api = createClient(fetchClient); ``` -------------------------------- ### Initialize and use openapi-react-query Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/index.md Demonstrates how to create a fetch client, initialize the React Query client, and perform a type-safe query within a React component. ```tsx import createFetchClient from "openapi-fetch"; import createClient from "openapi-react-query"; import type { paths } from "./my-openapi-3-schema"; const fetchClient = createFetchClient({ baseUrl: "https://myapi.dev/v1/", }); const $api = createClient(fetchClient); const MyComponent = () => { const { data, error, isLoading } = $api.useQuery( "get", "/blogposts/{post_id}", { params: { path: { post_id: 5 }, }, }, ); if (isLoading || !data) return "Loading..."; if (error) return `An error occured: ${error.message}`; return
{data.title}
; }; ``` -------------------------------- ### Wrapping and Creating Path-Based Clients Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/api.md Demonstrates how to use wrapAsPathBasedClient to enable path-indexed API calls and how to use createPathBasedClient as a shorthand. It also highlights how to share middleware between a base client and a path-based wrapper. ```typescript const client = createClient(clientOptions); const pathBasedClient = wrapAsPathBasedClient(client); pathBasedClient["/my-url"].GET(fetchOptions); const pathClient = createPathBasedClient(clientOptions); pathClient["/my-url"].GET(fetchOptions); const clientWithMiddleware = createClient(clientOptions); clientWithMiddleware.use(myMiddleware); const wrapped = wrapAsPathBasedClient(clientWithMiddleware); wrapped["/my-url"].GET(fetchOptions); ``` -------------------------------- ### Create API Client with openapi-typescript Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/api.md Demonstrates how to create an API client using the `createClient` function from openapi-typescript. This function accepts an options object to configure default settings for all subsequent API calls. Options include `baseUrl`, `fetch` instance, `querySerializer`, `bodySerializer`, `pathSerializer`, and any standard fetch options. ```typescript createClient(options); ``` -------------------------------- ### Basic Middleware Implementation Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/middleware-auth.md Demonstrates how to create and register a basic middleware that modifies request headers, changes response status, and wraps fetch errors. ```APIDOC ## Basic Middleware Implementation ### Description This example shows how to define a middleware with `onRequest`, `onResponse`, and `onError` callbacks. The `onRequest` callback adds a custom header, `onResponse` modifies the response status, and `onError` wraps any fetch errors. ### Method N/A (This is a configuration example) ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Request Example ```ts import createClient, { Middleware } from "openapi-fetch"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript const myMiddleware: Middleware = { async onRequest({ request, options }) { // set "foo" header request.headers.set("foo", "bar"); return request; }, async onResponse({ request, response, options }) { const { body, ...resOptions } = response; // change status of response return new Response(body, { ...resOptions, status: 200 }); }, async onError({ error }) { // wrap errors thrown by fetch return new Error("Oops, fetch failed", { cause: error }); }, }; const client = createClient({ baseUrl: "https://myapi.dev/v1/" }); // register middleware client.use(myMiddleware); ``` ### Response N/A (This is a configuration example) ### Response Example N/A ``` -------------------------------- ### GET /pet/{petId} Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/examples.md Retrieves pet information by ID with path parameter validation. ```APIDOC ## GET /pet/{petId} ### Description Fetches a pet's details based on the provided pet ID. Validates that the petId is a number at runtime. ### Method GET ### Endpoint /pet/{petId} ### Parameters #### Path Parameters - **petId** (number) - Required - The unique identifier of the pet. ### Request Example GET /pet/123 ### Response #### Success Response (200) - **name** (string) - The name of the pet. - **photoUrls** (array) - List of URLs for pet photos. #### Response Example { "name": "Falko", "photoUrls": [] } ``` -------------------------------- ### Implement and Register Middleware Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/middleware-auth.md Demonstrates how to create a middleware object with onRequest, onResponse, and onError handlers and register it with the openapi-fetch client. ```typescript import createClient, { Middleware } from "openapi-fetch"; import type { paths } from "./my-openapi-3-schema"; const myMiddleware: Middleware = { async onRequest({ request, options }) { request.headers.set("foo", "bar"); return request; }, async onResponse({ request, response, options }) { const { body, ...resOptions } = response; return new Response(body, { ...resOptions, status: 200 }); }, async onError({ error }) { return new Error("Oops, fetch failed", { cause: error }); }, }; const client = createClient({ baseUrl: "https://myapi.dev/v1/" }); client.use(myMiddleware); ``` -------------------------------- ### Custom Path Serializer Implementation Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/api.md Provides an example of a custom pathSerializer that modifies how path parameters are injected into the URL string. ```typescript const client = createClient({ pathSerializer(pathname, pathParams) { let result = pathname; for (const [key, value] of Object.entries(pathParams)) { result = result.replace(`{${key}}`, `[${value}]`); } return result; }, }); const { data, error } = await client.GET("/users/{id}", { params: { path: { id: 5 } }, }); ``` -------------------------------- ### useQuery Method Signature Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/use-query.md Illustrates the signature of the `useQuery` method, detailing its arguments: `method`, `path`, `options`, `queryOptions`, and `queryClient`. It explains the purpose and requirements of each parameter, including how they contribute to query keys and fetch options. ```tsx const query = $api.useQuery(method, path, options, queryOptions, queryClient); ``` -------------------------------- ### Throwing Errors in Middleware Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/middleware-auth.md Demonstrates how middleware can throw custom errors, for example, when a response is not OK, which can be caught by error handling libraries. ```APIDOC ## Throwing Errors in Middleware ### Description This example shows how to throw an error within the `onResponse` callback if the response status indicates an error (e.g., not `response.ok`). This allows for centralized error handling, especially when integrating with libraries like TanStack Query. ### Method N/A (This is a configuration example) ### Endpoint N/A ### Parameters N/A ### Request Body N/A ### Request Example ```ts onResponse({ response }) { if (!response.ok) { // Will produce error messages like "https://example.org/api/v1/example: 404 Not Found". throw new Error(`${response.url}: ${response.status} ${response.statusText}`) } } ``` ### Response N/A (This is a configuration example) ### Response Example N/A ``` -------------------------------- ### useQuery Hook Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/use-query.md The useQuery hook allows you to perform type-safe GET requests using your OpenAPI schema, leveraging TanStack Query's caching and state management. ```APIDOC ## useQuery Hook ### Description The `useQuery` hook is a wrapper around TanStack Query's `useQuery` that provides full type safety based on your OpenAPI schema. It automatically generates query keys based on the method, path, and parameters. ### Method GET (typically) ### Endpoint Dynamic based on schema path ### Parameters #### Arguments - **method** (string) - Required - The HTTP method (e.g., 'get'). - **path** (string) - Required - The API endpoint path defined in your schema. - **options** (object) - Optional - Fetch parameters including path, query, header, or body params. - **queryOptions** (object) - Optional - Original TanStack Query configuration options. - **queryClient** (object) - Optional - Custom query client instance. ### Request Example ```tsx const { data, error, isLoading } = $api.useQuery("get", "/users/{user_id}", { params: { path: { user_id: 5 }, }, }); ``` ### Response #### Success Response (200) - **data** (object) - The typed response body from the API. - **error** (object) - The typed error object if the request fails. - **isLoading** (boolean) - Loading state indicator. ``` -------------------------------- ### Using Path-Based Client Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/index.md Demonstrates an alternative client pattern where paths are accessed as properties, which can be useful for specific architectural preferences. ```typescript import { createPathBasedClient } from "openapi-fetch"; import type { paths } from "./my-openapi-3-schema"; const client = createPathBasedClient({ baseUrl: "https://myapi.dev/v1", }); client["/blogposts/{post_id}"].GET({ params: { post_id: "my-post" }, query: { version: 2 }, }); ``` -------------------------------- ### React Mutation with openapi-typescript Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/use-mutation.md Demonstrates how to use the `useMutation` hook from `openapi-typescript` to perform a PATCH request to update user data. It shows the integration with React components and the setup of the API client using `openapi-fetch` and `openapi-react-query`. ```tsx import { $api } from "./api"; export const App = () => { const { mutate } = $api.useMutation("patch", "/users"); return ( ); }; ``` ```ts import createFetchClient from "openapi-fetch"; import createClient from "openapi-react-query"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript const fetchClient = createFetchClient({ baseUrl: "https://myapi.dev/v1/", }); export const $api = createClient(fetchClient); ``` -------------------------------- ### Configure Multiple OpenAPI Schemas with redocly.yaml CLI Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/cli.md Defines configurations for transforming multiple OpenAPI schemas using a redocly.yaml file. This allows for specifying input schemas, output file paths, and custom options for each schema. When this file is present, the CLI can be run without explicit input/output arguments. ```yaml apis: core@v2: root: ./openapi/openapi.yaml x-openapi-ts: output: ./openapi/openapi.ts external@v1: root: ./openapi/external.yaml x-openapi-ts: output: ./openapi/external.ts additional-properties: true ``` -------------------------------- ### Mocking Fetch Requests with Vitest/Jest Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/testing.md Demonstrates how to mock the `fetch` function using `vi.fn()` (Vitest) or `jest.fn()` (Jest) to test API requests made by openapi-fetch. This allows you to inspect the request details like URL and body without making actual network calls. Dependencies include `openapi-fetch` and a test runner like Vitest. ```typescript import createClient from "openapi-fetch"; import { expect, test, vi } from "vitest"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript test("my request", async () => { const mockFetch = vi.fn(); const client = createClient({ baseUrl: "https://my-site.com/api/v1/", fetch: mockFetch, }); const reqBody = { name: "test" }; await client.PUT("/tag", { body: reqBody }); const req = mockFetch.mock.calls[0][0]; expect(req.url).toBe("/tag"); expect(await req.json()).toEqual(reqBody); }); ``` -------------------------------- ### Use openapi-react-query to Fetch Data in a React Component Source: https://github.com/openapi-ts/openapi-typescript/blob/main/packages/openapi-react-query/README.md Demonstrates how to use the generated API client within a React component to fetch data. It utilizes the `useQuery` hook from openapi-react-query to make a GET request, handling loading, error, and data states. ```tsx const MyComponent = () => { const { data, error, isPending } = $api.useQuery( "get", "/blogposts/{post_id}", { params: { path: { post_id: 5 }, }, } ); if (isPending || !data) return "Loading..."; if (error) return `An error occurred: ${error.message}`; return
{data.title}
; }; ``` -------------------------------- ### SvelteKit Client-Side Fetching with openapi-fetch Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/zh/openapi-fetch/examples.md Shows how to use openapi-fetch within SvelteKit's load functions for client-side data fetching. It leverages SvelteKit's custom fetch and automatic type inference. ```typescript import { createFetcher } from "@openapi-fetch/core"; import type { paths } from "./types"; // generated OpenAPI type // createFetcher is a generic function that takes the OpenAPI paths object export const fetcher = createFetcher(); // Example usage in a SvelteKit load function: // src/routes/+page.ts import type { PageLoad } from "./$types"; export const load: PageLoad = async ({ fetch }) => { const res = await fetcher("/users", { // SvelteKit's custom fetch fetch: fetch as typeof fetch, }); return { users: res.data, }; }; // src/routes/+page.svelte

Users

{#each data.users as user}

{user.name}

{/each} ``` -------------------------------- ### Implementing dynamic queries with useQueries Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/query-options.md Shows how to map an array of IDs to multiple query options using the useQueries hook. This is useful for fetching multiple resources in parallel while maintaining type safety. ```tsx import { useQueries } from '@tanstack/react-query'; import { $api } from "./api"; export const useUsersById = (userIds: number[]) => ( useQueries({ queries: userIds.map((userId) => ( $api.queryOptions("get", "/users/{user_id}", { params: { path: { user_id: userId }, }, }) )) }) ); ``` ```ts import createFetchClient from "openapi-fetch"; import createClient from "openapi-react-query"; import type { paths } from "./my-openapi-3-schema"; const fetchClient = createFetchClient({ baseUrl: "https://myapi.dev/v1/", }); export const $api = createClient(fetchClient); ``` -------------------------------- ### useSuspenseQuery Method Signature Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/use-suspense-query.md Illustrates the general signature for the `useSuspenseQuery` method. It outlines the required and optional arguments: method, path, options (for parameters), queryOptions, and queryClient. Each argument's purpose and how it contributes to the query key is explained. ```typescript const query = $api.useSuspenseQuery(method, path, options, queryOptions, queryClient); ``` -------------------------------- ### Implementing and Registering Middleware Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/api.md This snippet demonstrates how to define a middleware object with onRequest, onResponse, and onError callbacks and register it with an openapi-fetch client instance. ```typescript import createClient from "openapi-fetch"; import type { paths } from "./my-openapi-3-schema"; const myMiddleware: Middleware = { async onRequest({ request, options }) { request.headers.set("foo", "bar"); return request; }, async onResponse({ request, response, options }) { const { body, ...resOptions } = res; return new Response(body, { ...resOptions, status: 200 }); }, async onError({ error }) { return new Error("Oops, fetch failed", { cause: error }); }, }; const client = createClient({ baseUrl: "https://myapi.dev/v1/" }); client.use(myMiddleware); ``` -------------------------------- ### Constructing type-safe query options for useQuery Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-react-query/query-options.md Demonstrates how to use queryOptions within a React component to fetch data via useQuery. It requires a pre-configured API client and returns a fully typed query object. ```tsx import { useQuery } from '@tanstack/react-query'; import { $api } from "./api"; export const App = () => { const { data, error, isLoading } = useQuery( $api.queryOptions("get", "/users/{user_id}", { params: { path: { user_id: 5 }, }, }), ); if (!data || isLoading) return "Loading..."; if (error) return `An error occured: ${error.message}`; return
{data.firstname}
; }; ``` ```ts import createFetchClient from "openapi-fetch"; import createClient from "openapi-react-query"; import type { paths } from "./my-openapi-3-schema"; const fetchClient = createFetchClient({ baseUrl: "https://myapi.dev/v1/", }); export const $api = createClient(fetchClient); ``` -------------------------------- ### Run openapi-typescript CLI with Redocly config Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/migration-guide.md Executes the openapi-typescript CLI using the configuration defined in redocly.config.yml, which replaces previous globbing patterns. ```shell npx openapi-typescript ``` -------------------------------- ### Implementing Basic Authentication Middleware Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/openapi-fetch/middleware-auth.md Shows how to inject an Authorization header into every outgoing request using middleware, including logic to fetch and store an access token. ```typescript import createClient, { type Middleware } from "openapi-fetch"; import type { paths } from "./my-openapi-3-schema"; let accessToken: string | undefined = undefined; const authMiddleware: Middleware = { async onRequest({ request }) { if (!accessToken) { const authRes = await someAuthFunc(); if (authRes.accessToken) { accessToken = authRes.accessToken; } } request.headers.set("Authorization", `Bearer ${accessToken}`); return request; }, }; const client = createClient({ baseUrl: "https://myapi.dev/v1/" }); client.use(authMiddleware); const authRequest = await client.GET("/some/auth/url"); ``` -------------------------------- ### Configure Redocly with openapi-typescript Node.js API Source: https://github.com/openapi-ts/openapi-typescript/blob/main/docs/node.md Shows how to integrate Redocly configuration with the openapi-typescript Node.js API. It presents two methods for providing the Redocly configuration: creating an in-memory config object or loading it from a file. ```typescript import { createConfig, loadConfig } from "@redocly/openapi-core"; import openapiTS from "openapi-typescript"; // option 1: create in-memory config const redocly = await createConfig( { apis: { "core@v2": { … }, "external@v1": { … }, }, }, { extends: ["recommended"] }, ); // option 2: load from redocly.yaml file const redocly = await loadConfig({ configPath: "redocly.yaml" }); const ast = await openapiTS(mySchema, { redocly }); ```