{"id":15159,"library":"openapi-typescript-fetch","title":"Typed Fetch Client for OpenAPI Schemas","description":"openapi-typescript-fetch provides a robust and type-safe `fetch` client tailored for use with TypeScript definitions generated by `openapi-typescript`. It simplifies API interactions by offering strong typing for request parameters, response bodies, and error structures, directly derived from OpenAPI 3.x and Swagger 2.0 schemas. The current stable version is 2.2.1, with releases occurring incrementally as bug fixes and minor features are introduced. The project differentiates itself by deeply integrating with `openapi-typescript`'s generated types, allowing developers to configure a global fetcher instance, define per-path operations, and handle complex API error responses using discriminated unions, enhancing developer experience and reducing runtime errors. It supports middleware for request/response interception and offers utility types for introspection of operation arguments and return values. This library focuses on providing a secure and reliable way to interact with RESTful APIs in TypeScript environments, primarily for Node.js (>=12) and modern browsers.","status":"active","version":"2.2.1","language":"javascript","source_language":"en","source_url":"https://github.com/ajaishankar/openapi-typescript-fetch","tags":["javascript","fetch","client","swagger","typescript","ts","openapi","openapi 3","node"],"install":[{"cmd":"npm install openapi-typescript-fetch","lang":"bash","label":"npm"},{"cmd":"yarn add openapi-typescript-fetch","lang":"bash","label":"yarn"},{"cmd":"pnpm add openapi-typescript-fetch","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for generating the TypeScript type definitions (paths, operations) from an OpenAPI schema, which openapi-typescript-fetch then consumes to provide type safety.","package":"openapi-typescript","optional":false}],"imports":[{"note":"Since v2.0.0, the package primarily targets ES Modules (ESM). CommonJS `require` syntax is not directly supported.","wrong":"const { Fetcher } = require('openapi-typescript-fetch')","symbol":"Fetcher","correct":"import { Fetcher } from 'openapi-typescript-fetch'"},{"note":"The `Middleware` type is essential for creating custom request/response interceptors.","symbol":"Middleware","correct":"import { Middleware } from 'openapi-typescript-fetch'"},{"note":"Utility types like `OpArgType`, `OpReturnType`, `OpErrorType` are used for inferring types from operations generated by `openapi-typescript`, often in conjunction with `paths` or `operations` types.","symbol":"OpArgType","correct":"import { OpArgType } from 'openapi-typescript-fetch'"}],"quickstart":{"code":"import { Fetcher } from 'openapi-typescript-fetch';\nimport type { paths } from './petstore'; // Assume this is generated by 'npx openapi-typescript'\n\n// Configure the fetcher with a base URL and optional global settings\nconst fetcher = Fetcher.for<paths>();\nfetcher.configure({\n  baseUrl: 'https://petstore.swagger.io/v2',\n  init: {\n    headers: {\n      'Accept': 'application/json'\n    }\n  },\n  use: [async (url, init, next) => {\n    console.log(`[REQUEST] ${init.method || 'GET'} ${url}`);\n    const response = await next(url, init);\n    console.log(`[RESPONSE] ${url} - Status: ${response.status}`);\n    return response;\n  }]\n});\n\n// Define specific API operations\nconst findPetsByStatus = fetcher.path('/pet/findByStatus').method('get').create();\nconst addPet = fetcher.path('/pet').method('post').create();\n\nasync function runExample() {\n  try {\n    // Execute the findPetsByStatus operation with typed parameters\n    const { status, data: pets } = await findPetsByStatus({\n      status: ['available', 'pending'],\n      // No body for GET request, but type-safe parameters are enforced\n    });\n    console.log(`Found ${pets.length} pets. First pet ID: ${pets[0]?.id}`);\n\n    // Example of a POST request\n    const newPet = {\n      id: 987654321,\n      name: 'Max',\n      status: 'available',\n      category: { id: 1, name: 'Dog' },\n      photoUrls: ['http://example.com/max.jpg']\n    };\n    const addPetResult = await addPet(newPet);\n    console.log(`Added pet with ID: ${addPetResult.data.id}`);\n\n  } catch (e) {\n    // Handle typed errors\n    if (e instanceof addPet.Error) {\n      const error = e.getActualType();\n      console.error(`API Error for addPet (Status: ${error.status}):`, error.data);\n    } else {\n      console.error('An unexpected error occurred:', e);\n    }\n  }\n}\n\nrunExample();","lang":"typescript","description":"This quickstart demonstrates how to configure a typed fetch client, define specific API operations, execute them with type-safe parameters, and handle potential errors using the library's discriminated union error types."},"warnings":[{"fix":"Ensure your project is configured for ES Modules. If using CommonJS, consider transpiling your code to ESM or using an older version if ESM migration is not feasible. Update `tsconfig.json` and build tools accordingly.","message":"Version 2.0.0 introduced significant changes targeting ES Modules (ESM) environments. It dropped explicit TypeScript transpilation for `async/await` and was bundled with `esbuild` for ESM compatibility. Projects should ensure their build setup (e.g., Vite) is configured for ESM.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always run `npx openapi-typescript <schema-url-or-path> --output <output-file>.ts` before using `openapi-typescript-fetch`. Ensure the `output-file` matches the import path in your client code.","message":"Properly generating `petstore.ts` (or equivalent) using `openapi-typescript` is crucial. The types generated are the foundation for the type safety provided by `openapi-typescript-fetch`. Outdated or incorrectly generated types will lead to `any` types or incorrect type inference.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Implement error handling as shown in the documentation: `if (e instanceof myOperation.Error) { const error = e.getActualType(); /* handle error.status and error.data */ }`. This ensures type safety for different HTTP error codes and their associated bodies.","message":"Error handling relies on `e instanceof operation.Error` and `e.getActualType()` to leverage OpenAPI's defined error responses as discriminated unions. Generic `catch (e: any)` blocks will lose this type safety.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Understand the merging behavior. Global `init` options provide defaults, but operation-specific `init` will take precedence for conflicting properties. Use middlewares for more complex, conditional header modifications or other `init` changes.","message":"The `baseUrl` and `init` configurations set globally on the `fetcher` instance are merged with any `init` object provided directly to an operation. Be mindful of potential overwrites if not intended.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure your project is configured for ES Modules. Use `type: \"module\"` in `package.json`, ensure your `tsconfig.json` has `\"module\": \"esnext\"` or similar, and use `import` statements. If running Node.js, ensure `node --loader ts-node/esm` or similar for TypeScript projects.","cause":"This usually indicates an attempt to import an ESM-only package using CommonJS `require()` or in an environment not configured for ESM, particularly after the v2.0.0 release.","error":"Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'openapi-typescript-fetch' imported from ..."},{"fix":"Verify that `openapi-typescript` has successfully generated your `petstore.ts` (or similar) file. Check the import path `import type { paths } from './petstore';` to ensure it correctly points to the generated types file. Regenerate the types if the OpenAPI schema has changed.","cause":"This error often appears when the `paths` type from `openapi-typescript` is incorrectly imported or not up-to-date, causing the `Fetcher.for<paths>()` to infer `never` or an empty type.","error":"Property 'someProperty' does not exist on type 'never'."},{"fix":"Review your OpenAPI schema for the specific endpoint and method. Cross-reference with the `OpArgType` for that operation to ensure all required parameters are present and correctly typed. This is the core benefit of the library: type safety.","cause":"You are passing an argument to an operation that does not match the expected type defined by your OpenAPI schema and `openapi-typescript` generated types.","error":"Argument of type '{ status: string[]; invalidProp: string; }' is not assignable to parameter of type 'OpArgType<...>'"}],"ecosystem":"npm"}