### Install Dependencies and Run Dev Server Source: https://openapi-ts.dev/README Run these commands to install project dependencies and start the local development server for the docs site. Ensure you have Node.js and pnpm installed. ```bash pnpm i pnpm run dev ``` -------------------------------- ### API Client Setup Source: https://openapi-ts.dev/openapi-react-query/use-suspense-query Example of how to set up the openapi-fetch client and create the React Query client using an OpenAPI schema. ```APIDOC ## API Client Setup This section shows how to initialize the `openapi-fetch` client and integrate it with `openapi-react-query`. ### Description Set up a fetch client with your OpenAPI schema and base URL, then create a client instance for use with React Query hooks. ### Method `createFetchClient`, `createClient` ### Endpoint N/A ### Parameters #### `createFetchClient` Arguments * `paths` (object) - Required - The generated TypeScript types from your OpenAPI schema (e.g., from `openapi-typescript`). * `baseUrl` (string) - Required - The base URL for your API. #### `createClient` Arguments * `fetchClient` (object) - Required - The fetch client instance created by `createFetchClient`. ### Request Example ```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); ``` ### Response N/A (This is a setup configuration.) ``` -------------------------------- ### Basic GET and PUT Request Examples Source: https://openapi-ts.dev/openapi-fetch Demonstrates making GET and PUT requests with `openapi-fetch`, including passing path parameters and request bodies. The `data` and `error` properties are automatically typed. ```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(), }, }); ``` -------------------------------- ### Infinite Query Example with useInfiniteQuery Source: https://openapi-ts.dev/openapi-react-query/use-infinite-query Demonstrates how to use useInfiniteQuery to fetch and display a list of posts with infinite scrolling. It includes fetching next pages and handling loading states. Requires setup with $api client. ```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}`}> ); }; ``` -------------------------------- ### Example Usage of useInfiniteQuery Source: https://openapi-ts.dev/openapi-react-query/use-infinite-query This example demonstrates how to use the `useInfiniteQuery` hook to fetch a list of posts and implement a 'Load More' functionality. ```APIDOC ## Example Usage of useInfiniteQuery ### Description This example shows how to fetch a list of posts using `useInfiniteQuery` and display them, along with a button to load more posts. ### Code Example ```typescript 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 && ( )}
); }; ``` ### Related Files `src/api.ts`: ```typescript 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); ``` ``` -------------------------------- ### Install Dependencies Source: https://openapi-ts.dev/openapi-react-query Install openapi-react-query, openapi-fetch, openapi-typescript, and typescript. Ensure typescript is installed as a dev dependency. ```bash npm i openapi-react-query openapi-fetch npm i -D openapi-typescript typescript ``` -------------------------------- ### Install openapi-typescript and TypeScript Source: https://openapi-ts.dev/introduction Install the necessary packages for development. Ensure Node.js 20.x or higher is installed. ```bash npm i -D openapi-typescript typescript ``` -------------------------------- ### useQuery Example with queryOptions Source: https://openapi-ts.dev/openapi-react-query/query-options This example demonstrates how to use the queryOptions method with React Query's useQuery hook to fetch user data. ```APIDOC ## GET /users/{user_id} ### Description Fetches a user by their ID. ### Method GET ### Endpoint /users/{user_id} ### Parameters #### Path Parameters - **user_id** (number) - Required - The ID of the user to fetch. ### Request Example ```json { "params": { "path": { "user_id": 5 } } } ``` ### Response #### Success Response (200) - **firstname** (string) - The first name of the user. #### Response Example ```json { "firstname": "John" } ``` ``` -------------------------------- ### API Client Setup Source: https://openapi-ts.dev/openapi-react-query/use-query This snippet shows how to set up the `openapi-fetch` client and the `openapi-react-query` client using your generated OpenAPI schema. ```APIDOC ```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); ``` ``` -------------------------------- ### Install openapi-typescript Source: https://openapi-ts.dev/node Install the necessary packages for using the openapi-typescript Node.js API. ```bash npm i --save-dev openapi-typescript typescript ``` -------------------------------- ### Install openapi-fetch and openapi-typescript Source: https://openapi-ts.dev/openapi-fetch Install the necessary packages using npm. `openapi-fetch` is the client library, and `openapi-typescript` is used to generate TypeScript types from your OpenAPI schema. ```bash npm i openapi-fetch npm i -D openapi-typescript typescript ``` -------------------------------- ### Basic GET and POST Requests Source: https://openapi-ts.dev/openapi-fetch Demonstrates how to make GET and POST requests using the client, including the structure of the params and body objects. ```APIDOC ## GET and POST Requests ### Description This section details how to perform GET and POST requests using the client. For GET requests, parameters are grouped within a `params` object, categorized by type (`path` or `query`). For POST requests, a `body` object is required to provide all necessary request body data. ### Request Parameters - **params** (object) - Required for GET requests. Groups parameters by type (`path`, `query`). - **path** (object) - Path parameters. - **query** (object) - Query parameters. - **body** (object) - Required for POST requests. Contains all necessary request body data. ### Response Structure All methods return an object with the following properties: - **data** (`object` | `undefined`): `2xx` response if OK; otherwise `undefined`. - **error** (`object` | `undefined`): `5xx`, `4xx`, or `default` response if not OK; otherwise `undefined`. - **response** (`Response`): The original Response object, containing `status`, `headers`, etc. ### Request Example (GET) ```typescript const { data, error, response } = await client.GET("/url"); ``` ### Request Example (POST) ```typescript // Assuming a POST request to /users with a body const { data, error, response } = await client.POST("/users", { body: { name: "John Doe", email: "john.doe@example.com" } }); ``` ### Response Example ```json { "data": { ... }, // 2xx response data "error": undefined, // or an error object for non-2xx responses "response": { ... } // original Response object } ``` ``` -------------------------------- ### Example Usage Source: https://openapi-ts.dev/openapi-react-query/use-mutation This example demonstrates how to use the `useMutation` hook to update a user's first name. It shows the integration with a button click event. ```APIDOC ## Example Usage ### Description This example demonstrates how to use the `useMutation` hook to update a user's first name. It shows the integration with a button click event. ### Code ```tsx import { $api } from "./api"; export const App = () => { const { mutate } = $api.useMutation("patch", "/users"); return ( ); }; ``` ### Setup Ensure you have `openapi-fetch` and `@tanstack/react-query` installed and configured. The `$api` client should be initialized with your OpenAPI schema and base URL. ```typescript 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); ``` ``` -------------------------------- ### useQueries Example with queryOptions Source: https://openapi-ts.dev/openapi-react-query/query-options This example shows how to fetch multiple users by their IDs using React Query's useQueries hook and the queryOptions method. ```APIDOC ## GET /users/{user_id} ### Description Fetches a user by their ID. ### Method GET ### Endpoint /users/{user_id} ### Parameters #### Path Parameters - **user_id** (number) - Required - The ID of the user to fetch. ### Request Example ```json { "params": { "path": { "user_id": 1 } } } ``` ### Response #### Success Response (200) - **firstname** (string) - The first name of the user. #### Response Example ```json { "firstname": "Jane" } ``` ``` -------------------------------- ### Use queryOptions with useQuery Source: https://openapi-ts.dev/openapi-react-query/query-options This example demonstrates how to use `queryOptions` with the `useQuery` hook from `@tanstack/react-query` to fetch user data. Ensure your API client is set up correctly. ```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"; // generated by openapi-typescript const fetchClient = createFetchClient({ baseUrl: "https://myapi.dev/v1/", }); export const $api = createClient(fetchClient); ``` -------------------------------- ### Use queryOptions with useQueries Source: https://openapi-ts.dev/openapi-react-query/query-options This example shows how to fetch multiple users by their IDs using `queryOptions` within the `useQueries` hook. It maps over an array of user IDs to generate individual query options. ```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"; // generated by openapi-typescript const fetchClient = createFetchClient({ baseUrl: "https://myapi.dev/v1/", }); export const $api = createClient(fetchClient); ``` -------------------------------- ### Use useSuspenseQuery to fetch user data Source: https://openapi-ts.dev/openapi-react-query/use-suspense-query This example demonstrates fetching user data using useSuspenseQuery with specific parameters. Ensure the ErrorBoundary is set up to handle potential errors during data fetching. ```typescript 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}`}> ); }; ``` -------------------------------- ### Make a GET Request Source: https://openapi-ts.dev/openapi-fetch Use the client's `GET` method to fetch data. The `data` and `error` properties are type-checked based on your OpenAPI schema. Path parameters are provided within the `params.path` object. ```typescript 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" }, }, }); ``` -------------------------------- ### Make a GET Request Source: https://openapi-ts.dev/openapi-fetch Use the GET() method to make a request. It requires a params object for query or path parameters. A type error is thrown if required parameters are missing or of the wrong type. ```typescript const { data, error, response } = await client.GET("/url"); ``` -------------------------------- ### Express with openapi-ts-router for Type-Safe Routes Source: https://openapi-ts.dev/examples This example demonstrates using `openapi-ts-router` with Express to achieve type-safe API routes and runtime validation. It showcases validation of path parameters and request bodies using Zod, similar to the Hono example. ```typescript import { Router } from 'express'; import { createExpressOpenApiRouter } from 'openapi-ts-router'; import * as z from 'zod'; import { zValidator } from 'validation-adapters/zod'; import { paths } from './gen/v1'; // OpenAPI-generated types import { PetSchema } from './schemas'; // Custom reusable schema for validation export const router: Router = Router(); export const openApiRouter = createExpressOpenApiRouter(router); // GET /pet/{petId} openApiRouter.get('/pet/{petId}', { pathValidator: zValidator( z.object({ petId: z.number() // Validate that petId is a number }) ), handler: (req, res) => { const { petId } = req.params; // Access validated params res.send({ name: 'Falko', photoUrls: [] }); } }); // POST /pet openApiRouter.post('/pet', { bodyValidator: zValidator(PetSchema), // Validate request body using PetSchema handler: (req, res) => { const { name, photoUrls } = req.body; // Access validated body data res.send({ name, photoUrls }); } }); // TypeScript will error if route/method doesn't exist in OpenAPI spec // or if response doesn't match defined schema ``` -------------------------------- ### Request Options Source: https://openapi-ts.dev/openapi-fetch/api Options that apply to all request methods (e.g., GET, POST). ```APIDOC ## Fetch options The following options apply to all request methods (`.GET()`, `.POST()`, etc.) ```ts client.GET("/my-url", options); ``` ### Parameters | Name | Type | Description | |---|---|---| | `params` | ParamsObject | path and query params for the endpoint | | `body` | `{ [name]:value }` | requestBody data for the endpoint | | `querySerializer` | QuerySerializer | (optional) Provide a querySerializer | | `bodySerializer` | BodySerializer | (optional) Provide a bodySerializer | | `pathSerializer` | PathSerializer | (optional) Provide a pathSerializer | | `parseAs` | `"json"` | `"text"` | `"arrayBuffer"` | `"blob"` | `"stream"` | (optional) Parse the response using a built-in instance method (default: `"json"`). `"stream"` skips parsing altogether and returns the raw stream. | | `baseUrl` | `string` | Prefix the fetch URL with this option (e.g. `"https://myapi.dev/v1/"`) | | `fetch` | `fetch` | Fetch instance used for requests (default: fetch from `createClient`) | | `middleware` | `Middleware[]` | See docs | | (Fetch options) | | Any valid fetch option (`headers`, `mode`, `cache`, `signal`, …) (docs) | ``` -------------------------------- ### Using useMutation in a React Component Source: https://openapi-ts.dev/openapi-react-query/use-mutation This example demonstrates how to use the useMutation hook within a React component to trigger an API update. Ensure the $api client is properly configured. ```tsx import { $api } from "./api"; export const App = () => { const { mutate } = $api.useMutation("patch", "/users"); return ( ); }; ``` -------------------------------- ### Mocking API Responses with Type Checking Source: https://openapi-ts.dev/examples This example shows how to define mock API responses for different endpoints and HTTP methods. It leverages generated types from `openapi-typescript` to ensure the mock data shape is correct for each path, method, and status code. ```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(); }); }); ``` -------------------------------- ### Hono API Route with OpenAPI Types Source: https://openapi-ts.dev/examples Example of defining a Hono API route using types generated by openapi-typescript. It demonstrates fetching data and returning a JSON response, with error handling for potential issues. ```typescript import { Hono } from "hono"; import { components, paths } from "./my-openapi-3-schema"; // generated by openapi-typescript const app = new Hono(); /** /users */ app.get("/users", async (ctx) => { try { const users = db.get("SELECT * from users"); return ctx.json< paths["/users"]["responses"][200]["content"]["application/json"] >(users); } catch (err) { return ctx.json({ status: 500, message: err ?? "An error occurred", }); } }); export default app; ``` -------------------------------- ### Hono with openapi-ts-router for Type-Safe Routes Source: https://openapi-ts.dev/examples This snippet shows how to use `openapi-ts-router` with Hono to provide full type-safety and runtime validation for API routes. It includes examples for validating path parameters and request bodies using Zod. ```typescript import { Hono } from 'hono'; import { createHonoOpenApiRouter } from 'openapi-ts-router'; import { zValidator } from 'validation-adapters/zod'; import * as z from 'zod'; import { paths } from './gen/v1'; // OpenAPI-generated types import { PetSchema } from './schemas'; // Custom reusable schema for validation export const router = new Hono(); export const openApiRouter = createHonoOpenApiRouter(router); // GET /pet/{petId} openApiRouter.get('/pet/{petId}', { pathValidator: zValidator( z.object({ petId: z.number() // Validate that petId is a number }) ), handler: (c) => { const { petId } = c.req.valid('param'); // Access validated params return c.json({ name: 'Falko', photoUrls: [] }); } }); // POST /pet openApiRouter.post('/pet', { bodyValidator: zValidator(PetSchema), // Validate request body using PetSchema handler: (c) => { const { name, photoUrls } = c.req.valid('json'); // Access validated body data return c.json({ name, photoUrls }); } }); // TypeScript will error if route/method doesn't exist in OpenAPI spec // or if response doesn't match defined schema ``` -------------------------------- ### Client Creation Source: https://openapi-ts.dev/openapi-fetch/api Initialize a client with default settings for all subsequent fetch calls. ```APIDOC ## createClient **createClient** accepts the following options, which set the default settings for all subsequent fetch calls. ```ts createClient(options); ``` ### Parameters | Name | Type | Description | |---|---|---| | `baseUrl` | `string` | Prefix all fetch URLs with this option (e.g. `"https://myapi.dev/v1/"`) | | `fetch` | `fetch` | Fetch instance used for requests (default: `globalThis.fetch`) | | `querySerializer` | QuerySerializer | (optional) Provide a querySerializer | | `bodySerializer` | BodySerializer | (optional) Provide a bodySerializer | | `pathSerializer` | PathSerializer | (optional) Provide a pathSerializer | | (Fetch options) | | Any valid fetch option (`headers`, `mode`, `cache`, `signal` …) (docs) | ``` -------------------------------- ### Initialize openapi-fetch Client Source: https://openapi-ts.dev/openapi-fetch Import `createClient` and initialize it with your OpenAPI schema type and base URL. This sets up the client for making type-safe API requests. ```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/" }); ``` -------------------------------- ### Initialize openapi-fetch Client Source: https://openapi-ts.dev/openapi-react-query/use-infinite-query Sets up the fetch client for openapi-ts using a base URL and type definitions generated by openapi-typescript. This client is then used to create the $api instance. ```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); ``` -------------------------------- ### Invalid $defs Definition on Primitive Type Source: https://openapi-ts.dev/advanced This example shows an invalid use of $defs defined on a primitive type, which will not transform correctly into TypeScript. ```yaml components: schemas: DefType: type: string # ❌ this won’t keep its $defs $defs: myDefType: type: string MyType: properties: myType: $ref: "#/components/schemas/DefType/$defs/myDefType" ``` -------------------------------- ### Valid $defs Definition on Object Type Source: https://openapi-ts.dev/advanced This example demonstrates a valid use of $defs defined on an object type, which correctly transforms into TypeScript. ```yaml components: schemas: DefType: type: object # ✅ `type: "object"` is OK to define $defs on $defs: myDefType: type: string MyType: type: object properties: myType: $ref: "#/components/schemas/DefType/$defs/myDefType" ``` -------------------------------- ### Path-Based Client Source: https://openapi-ts.dev/openapi-fetch Explains how to create a client that allows accessing endpoints as properties, offering an alternative way to structure API calls. ```APIDOC ## Path-Based Client ### Description This method allows you to create a client where API endpoints are accessed as properties of the client object. This can lead to a more organized and readable code structure, especially for complex APIs. ### Usage To use this feature, you first need to create a path-based client using `createPathBasedClient`. You'll need to import your generated OpenAPI schema types. ### Code Example ```typescript import { createPathBasedClient } from "openapi-fetch"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript const client = createPathBasedClient({ baseUrl: "https://myapi.dev/v1", }); // Accessing an endpoint as a property client["/blogposts/{post_id}"].GET({ params: { post_id: "my-post" }, query: { version: 2 }, }); ``` ### Considerations - **Performance Implications**: Using a path-based client might have performance implications. - **Middlewares**: Attaching middlewares directly is not supported with this approach. Consider `wrapAsPathBasedClient` for more advanced scenarios. ``` -------------------------------- ### Custom Path Serializer Function Source: https://openapi-ts.dev/openapi-fetch/api Define a custom `pathSerializer` function when creating the client to handle non-standard path parameter serialization formats. This example replaces `{key}` with `[value]`. ```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 } }, }); // URL: `/users/[5]` ``` -------------------------------- ### Create a Path-Based Client Source: https://openapi-ts.dev/openapi-fetch Create a client that allows selecting the path as a property. This requires importing createPathBasedClient and providing a generated OpenAPI schema. Note potential performance implications and limitations with middleware. ```typescript import { createPathBasedClient } from "openapi-fetch"; import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript const client = createPathBasedClient({ baseUrl: "https://myapi.dev/v1", }); client["/blogposts/{post_id}"].GET({ params: { post_id: "my-post" }, query: { version: 2 }, }); ``` -------------------------------- ### Create OpenAPI Fetch Client Source: https://openapi-ts.dev/openapi-fetch/api Initialize the OpenAPI Fetch client with default options for all subsequent requests. Options include baseUrl, fetch instance, and various serializers. ```typescript createClient(options); ``` -------------------------------- ### Configure HTTP Headers and Basic Auth in Redocly Source: https://openapi-ts.dev/cli Set up authentication for non-public schemas within your `redocly.yaml` file. This includes configuring custom headers and basic authentication using environment variables. ```yaml resolve: http: headers: - matches: https://api.example.com/v2/** name: X-API-KEY envVariable: SECRET_KEY - matches: https://example.com/*/test.yaml name: Authorization envVariable: SECRET_AUTH ``` -------------------------------- ### useQuery Arguments Source: https://openapi-ts.dev/openapi-react-query/use-query Detailed explanation of the arguments accepted by the `$api.useQuery` method. ```APIDOC ## useQuery ### Description Allows you to use the original `useQuery` hook from React Query, integrated with your OpenAPI schema. ### Method `$api.useQuery(method, path, options, queryOptions, queryClient)` ### Endpoint N/A (Hook) ### Parameters #### Arguments - **method** (string) - Required - The HTTP method (e.g., 'GET', 'POST'). Used as part of the query key. - **path** (string) - Required - The API endpoint path (e.g., '/users/{user_id}'). Must exist in your schema. Used as part of the query key. - **options** (object) - Optional - Fetch options, including `params` (path, query, etc.). Required if the schema defines parameters for the endpoint. The `params` are used as part of the query key. - **queryOptions** (object) - Optional - Additional options for React Query's `useQuery`. - **queryClient** (object) - Optional - An instance of React Query's `QueryClient`. ``` -------------------------------- ### Apply Fetch Options to Client Requests Source: https://openapi-ts.dev/openapi-fetch/api Use client methods like .GET() to make requests with specific options. These options can override client defaults and include parameters, request body, and response parsing preferences. ```typescript client.GET("/my-url", options); ``` -------------------------------- ### Specify Redocly Configuration File Source: https://openapi-ts.dev/cli If your `redocly.yaml` file is not in the project root, you can specify its location using the `--redocly` flag. This allows for flexible configuration management. ```bash npx openapi-typescript --redocly ./path/to/redocly.yaml ``` -------------------------------- ### Basic Usage with React Query Source: https://openapi-ts.dev/openapi-react-query Create a fetch client using openapi-fetch and a react-query client using openapi-react-query. Use the $api.useQuery hook to fetch data, providing the HTTP method, URL, and parameters. Handle loading, error, and data states. ```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); 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}
; }; ``` -------------------------------- ### Define Mock Responses with Type Safety Source: https://openapi-ts.dev/examples Use the `mockResponses` function to define mock data for your API endpoints. This function ensures that your mock responses are type-checked against your OpenAPI schema, preventing inconsistencies and errors in your tests. No specific setup is required beyond having your OpenAPI schema defined. ```typescript export function mockResponses(responses: { [Path in keyof Partial]: { [Method in keyof Partial]: MockedResponse< PathResponses >; }; }); ``` -------------------------------- ### useInfiniteQuery Method Signature Source: https://openapi-ts.dev/openapi-react-query/use-infinite-query Illustrates the general signature for calling the useInfiniteQuery method, detailing the required and optional arguments. ```tsx const query = $api.useInfiniteQuery( method, path, options, infiniteQueryOptions, queryClient ); ``` -------------------------------- ### Create Path-Based Client Convenience Method Source: https://openapi-ts.dev/openapi-fetch/api Use createPathBasedClient as a shortcut to combine createClient and wrapAsPathBasedClient for exclusive use of the path-based call style. This method does not support attaching middlewares. ```typescript const client = createPathBasedClient(clientOptions); client["/my-url"].GET(fetchOptions); ``` -------------------------------- ### Create Path-Based Client with Proxy Source: https://openapi-ts.dev/openapi-fetch/api Wrap a created client to enable path-indexed calls using a Proxy. This can improve type inference but incurs a runtime cost. The fetch options are the same as for the base client. ```typescript const client = createClient(clientOptions); const pathBasedClient = wrapAsPathBasedClient(client); pathBasedClient["/my-url"].GET(fetchOptions); ``` -------------------------------- ### Support Matrix Source: https://openapi-ts.dev/openapi-fetch Details the platform and version support for the OpenAPI Fetch client. ```APIDOC ## Support Matrix ### Description This section outlines the compatibility of the OpenAPI Fetch client with different platforms and development environments. ### Platform Support - **Browsers**: Widely available in all major browsers (see fetch API support). - **Node.js**: Requires version 18.0.0 or higher. - **TypeScript**: Requires version 4.7 or higher (version 5.0 or higher is recommended). ``` -------------------------------- ### Mocking Requests with Vitest Source: https://openapi-ts.dev/openapi-fetch/testing Use `vi.fn()` to mock the fetch implementation when testing requests. This allows you to inspect the request URL and body. ```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); }); ``` -------------------------------- ### useQuery Hook Usage Source: https://openapi-ts.dev/openapi-react-query/use-query The `useQuery` hook allows you to fetch data from your API. It takes the HTTP method, the path, and optional fetch options. The query key is automatically generated from the method, path, and parameters. ```APIDOC ## GET /users/{user_id} ### Description Fetches user data based on the provided user ID. ### Method GET ### Endpoint /users/{user_id} ### Parameters #### Path Parameters - **user_id** (number) - Required - The ID of the user to retrieve. ### Request Example ```json { "params": { "path": { "user_id": 5 } } } ``` ### Response #### Success Response (200) - **firstname** (string) - The first name of the user. #### Response Example ```json { "firstname": "John" } ``` ``` -------------------------------- ### Run openapi-typescript CLI without arguments Source: https://openapi-ts.dev/migration-guide When a `redocly.config.yml` file is declared, you can run the CLI command with no arguments to generate multiple schemas. ```sh npx openapi-typescript ``` -------------------------------- ### Using useQuery in a React Component Source: https://openapi-ts.dev/openapi-react-query/use-query Demonstrates how to use the $api.useQuery hook within a React component to fetch user data. It handles loading and error states, and displays the user's first name upon successful retrieval. Ensure your OpenAPI schema defines the '/users/{user_id}' path and the 'firstname' property. ```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}
; }; ``` -------------------------------- ### Implement Basic Authentication Middleware Source: https://openapi-ts.dev/openapi-fetch/middleware-auth This middleware fetches and adds an `Authorization` header to requests. It stores the access token in module state, suitable for client applications but not server applications. Ensure `someAuthFunc()` is defined to handle token retrieval and errors. ```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 }) { // fetch token, if it doesn’t exist if (!accessToken) { const authRes = await someAuthFunc(); if (authRes.accessToken) { accessToken = authRes.accessToken; } else { // handle auth error } } // (optional) add logic here to refresh token when it expires // add Authorization header to every request 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"); ``` -------------------------------- ### useQuery Hook Signature Source: https://openapi-ts.dev/openapi-react-query/use-query The useQuery hook accepts the HTTP method, path, fetch options, original useQuery options, and an optional query client. The method, path, and options parameters are used to construct the query key. ```tsx const query = $api.useQuery(method, path, options, queryOptions, queryClient); ``` -------------------------------- ### Configure Multiple Schemas with redocly.yaml Source: https://openapi-ts.dev/cli Define multiple OpenAPI schemas and their output TypeScript files in a `redocly.yaml` configuration file. This allows for managing complex projects with several schemas. ```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 # CLI flags are also supported, either in kebab-case or camelCase format ``` -------------------------------- ### Basic Node.js API Usage Source: https://openapi-ts.dev/node Load a schema from a local file using a URL and convert the resulting TypeScript AST to a string. Optionally, write the generated types to a file. ```typescript import fs from "node:fs"; import openapiTS, { astToString } from "openapi-typescript"; const ast = await openapiTS(new URL("./my-schema.yaml", import.meta.url)); const contents = astToString(ast); // (optional) write to file fs.writeFileSync("./my-schema.ts", contents); ``` -------------------------------- ### Data Fetching with openapi-axios Source: https://openapi-ts.dev/examples This library offers three status handling strategies: 'axios' (default), 'fetch', and 'all' (safe). Choose based on your preferred error handling and exception behavior. ```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"); if (error) { // status >= 400 } } catch (err) { if (api.isAxiosError(err)) { // request failed (e.g. network error) } throw err; // axios.interceptors error } // Example 3. Usage with "safe" status handling strategy (validStatus: 'all') // (No try/catch required) const safeApi = new OpenApiAxios(axios, { validStatus: "all" }); // never throws errors const { status, data, error, response } = await api.get("/users"); if (error) { if (typeof status === "number") { // status >= 400 } else if (api.isAxiosError(error)) { // request failed (e.g. network error) } throw error; // axios.interceptors error } ``` -------------------------------- ### Basic Data Fetching with openapi-fetch Source: https://openapi-ts.dev/examples Use this wrapper for simple and safe data fetching. It automatically types responses and errors based on your 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, // 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", }, }); ``` -------------------------------- ### Dynamic Path Lookup with `--path-params-as-types` Source: https://openapi-ts.dev/cli When `--path-params-as-types` is enabled, you can use dynamic lookups with URLs. This allows for automatic matching of path parameters. ```typescript import type { paths } from "./my-openapi-3-schema"; const url = `/user/${id}`; type UserResponses = paths[url]["responses"]; // automatically matches `paths['/user/{user_id}']` ``` -------------------------------- ### Configure Redocly with Node.js API Source: https://openapi-ts.dev/node Integrate Redocly configurations with the openapi-typescript Node.js API. This can be done by creating an in-memory config or loading 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 }); ``` -------------------------------- ### Path-Based Client Source: https://openapi-ts.dev/openapi-fetch/api Wraps a client to enable path-indexed calls using a Proxy. ```APIDOC ## wrapAsPathBasedClient **wrapAsPathBasedClient** wraps the result of `createClient()` to return a Proxy-based client that allows path-indexed calls: ```ts const client = createClient(clientOptions); const pathBasedClient = wrapAsPathBasedClient(client); pathBasedClient["/my-url"].GET(fetchOptions); ``` The `fetchOptions` are the same than for the base client. A path based client can lead to better type inference but comes at a runtime cost due to the use of a Proxy. **createPathBasedClient** is a convenience method combining `createClient` and `wrapAsPathBasedClient` if you only want to use the path based call style: ```ts const client = createPathBasedClient(clientOptions); client["/my-url"].GET(fetchOptions); ``` Note that it does not allow you to attach middlewares. If you need middlewares, you need to use the full form: ```ts const client = createClient(clientOptions); client.use(...); const pathBasedClient = wrapAsPathBasedClient(client); client.use(...); // the client reference is shared, so the middlewares will propagate. pathBasedClient["/my-url"].GET(fetchOptions); ``` ```