### Install openapi-ts-request CLI Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md Installs the openapi-ts-request CLI globally on your system. This command is typically run once to make the `openapi` command available in your terminal. ```bash npm i openapi-ts-request -g ``` -------------------------------- ### Detect Project Type and Recommend Configuration Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md This snippet demonstrates how to detect the project type based on installed packages and suggest relevant configuration options for OpenAPI TypeScript Request. It checks for React, Vue, Taro, Uni-app, or Node.js environments to recommend appropriate settings like `isGenReactQuery` or `requestLibPath`. ```typescript if (has("react") && has("@tanstack/react-query")) { recommend: { isGenReactQuery: true, reactQueryMode: "react" } } else if (has("vue") && has("@tanstack/vue-query")) { recommend: { isGenReactQuery: true, reactQueryMode: "vue" } } else if (has("@tarojs/taro") || has("@dcloudio/uni-app")) { recommend: { requestLibPath: "@/request" } } else if (isNodeProject) { recommend: { requestLibPath: "node-fetch" } } ``` -------------------------------- ### Install openapi-ts-request Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md Install the openapi-ts-request package as a development dependency using npm or pnpm. ```bash # npm npm i openapi-ts-request --save-dev # pnpm pnpm i openapi-ts-request -D ``` -------------------------------- ### CLI Usage for openapi-ts-request Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Demonstrates how to use the openapi-ts-request CLI tool with different package managers (npx, pnpm, npm) for generating API clients. It shows the command structure for specifying input OpenAPI specification and output directories. ```bash # NPX usage npx --package=openapi-ts-request -- openapi -i ./openapi.json -o ./apis # PNPM usage pnpm --package=openapi-ts-request@latest dlx openapi -i ./openapi.json -o ./apis # Global installation npm i -g openapi-ts-request openapi --input https://api.example.com/openapi.json --output ./src/apis ``` -------------------------------- ### Generate React + TypeScript API Client Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Configuration for generating a React client with TypeScript, including options for React Query, type labels, JSON schemas, camel case conversion, and specifying the request library (e.g., axios). ```typescript { schemaPath: "https://api.example.com/openapi.json", serversPath: "./src/apis", isGenReactQuery: true, reactQueryMode: "react", isDisplayTypeLabel: true, isGenJsonSchemas: true, isCamelCase: true, requestLibPath: "axios", nullable: false, enableLogging: false } ``` -------------------------------- ### Generate APIs using NPX (npm) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md Use `npx` to run the `openapi-ts-request` CLI tool directly without global installation. This is useful for one-off generations or CI/CD pipelines. Specify input OpenAPI JSON file and output directory. ```bash # npm npx --package=openapi-ts-request -- openapi -i ./openapi.json -o ./apis npx --package=openapi-ts-request -- openapi -i https://petstore3.swagger.io/api/v3/openapi.json -o ./apis ``` -------------------------------- ### Example Generated API Function (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md An example of a generated API function for updating a pet. It uses axios for requests and is automatically typed based on the OpenAPI schema. ```typescript // src/apis/pet.ts /* eslint-disable */ // @ts-ignore import request from 'axios'; import * as API from './types'; /** Update an existing pet PUT /pet */ export async function updatePet({ body, options, }: { body: API.Pet; options?: { [key: string]: unknown }; }) { return request(`/pet`, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, data: body, ...(options || {}), }); } // ... more interfaces ``` -------------------------------- ### Apifox Integration for API Client Generation Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Configuration for integrating with Apifox, a platform for API design and documentation. This includes project ID, token, language settings, selected tags, OpenAPI version, and export format. ```typescript { apifoxConfig: { projectId: "your-project-id", apifoxToken: "your-apifox-token", local: "zh-CN", selectedTags: ["user", "order"], oasVersion: "3.0", exportFormat: "JSON" }, serversPath: "./src/apis", isGenReactQuery: true, isDisplayTypeLabel: true, isSupportParseEnumDesc: true } ``` -------------------------------- ### Generate API Client with Mock Data Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Configuration for generating API clients with integrated mock data support. This scenario enables mock data generation using a specified folder and mockjs, while also allowing for JavaScript generation and logging. ```typescript { schemaPath: "https://petstore.swagger.io/v2/swagger.json", serversPath: "./src/apis", mockFolder: "./mocks", isGenJavaScript: true, isDisplayTypeLabel: false, isGenReactQuery: false, enableLogging: true } ``` -------------------------------- ### Generate API Client with Custom Request Client Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Configuration for integrating a custom request client. This allows specifying the path to the custom library, the import statement, the type for request options, and defining a dynamic API prefix based on namespace. ```typescript { schemaPath: "https://api.example.com/openapi.json", serversPath: "./src/apis", requestLibPath: "@/utils/httpClient", requestImportStatement: "import { httpClient as request } from '@/utils/httpClient';", requestOptionsType: "CustomRequestOptions", apiPrefix: (params) => `api/${params.namespace.toLowerCase()}`, isGenReactQuery: true } ``` -------------------------------- ### Generate UniApp/Taro Mini Program API Client Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Configuration tailored for UniApp or Taro mini-program development, including specifying the request library path, API prefix, and request options type. It also supports JavaScript generation. ```typescript { schemaPath: "https://api.example.com/swagger.json", serversPath: "./src/apis", requestLibPath: "@/request", isGenJavaScript: false, isCamelCase: true, apiPrefix: "'api'", requestOptionsType: "{ [key: string]: any }" } ``` -------------------------------- ### Generate Node.js Backend API Client Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Configuration for generating API clients for Node.js backends, specifying the request library (e.g., node-fetch), import statement, and request options type. It allows for JavaScript generation. ```typescript { schemaPath: "./api-spec.json", serversPath: "./src/clients", requestLibPath: "node-fetch", isGenJavaScript: true, isOnlyGenTypeScriptType: false, requestImportStatement: "const request = require('node-fetch');", requestOptionsType: "RequestInit" } ``` -------------------------------- ### Custom Function Naming with OpenAPI TS Request Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Allows defining custom logic for naming generated functions based on API data. This example shows RESTful conventions, operationId fallback, and domain-specific naming strategies. It processes API method and path to create function names. ```typescript hook: { customFunctionName: (data: APIDataType) => { const method = data.method; const resource = data.path.split('/').filter(Boolean).pop(); return `${method}${upperFirst(resource)}`; // Result: GET /users/{id} → getUsersId } } ``` ```typescript hook: { customFunctionName: (data: APIDataType) => { if (data.operationId) { return camelCase(data.operationId.replace(/[^a-zA-Z0-9]/g, '_')); } return `${data.method}${upperFirst(camelCase(data.path))}`; } } ``` ```typescript hook: { customFunctionName: (data: APIDataType) => { const segments = data.path.split('/').filter(Boolean); const version = segments.find((s) => s.match(/^v\d+$/)); // v1, v2, etc. const resource = segments[segments.length - 1]; const action = data.method; return version ? `${action}${upperFirst(resource)}${upperFirst(version)}` : `${action}${upperFirst(resource)}`; } } ``` -------------------------------- ### Generate Type-Only TypeScript Definitions Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Configuration for generating only TypeScript type definitions, skipping request functions. This includes options for JSON schema generation, custom namespaces, camel case conversion, and display type labels. ```typescript { schemaPath: "./openapi.json", serversPath: "./src/types", isOnlyGenTypeScriptType: true, isDisplayTypeLabel: true, isGenJsonSchemas: true, namespace: "APITypes", isCamelCase: true } ``` -------------------------------- ### Generate API Client for Large API with Filtering Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Configuration for managing large APIs, focusing on performance optimization through tag filtering. It supports incremental code updates, logging, and generating React Query hooks with type labels. ```typescript { schemaPath: "https://large-api.example.com/openapi.json", serversPath: "./src/apis", priorityRule: "include", includeTags: ["user", "order", "product"], filterCaseInsensitive: true, isGenReactQuery: true, isDisplayTypeLabel: true, full: false, // Incremental updates for large APIs enableLogging: true } ``` -------------------------------- ### Custom Type Generation Logic with OpenAPI TS Request Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Provides a hook to override default type generation logic for specific schema types or formats. Examples include converting numbers to strings for precision and date-time strings to Date objects, or handling custom formats like 'decimal' and custom enums. ```typescript hook: { customType: ({ schemaObject, namespace, originGetType }) => { if (schemaObject.type === 'number' && !schemaObject.format) { return 'string'; // Use string for large numbers } // Convert date-time to Date objects if (schemaObject.type === 'string' && schemaObject.format === 'date-time') { return 'Date'; } return originGetType(schemaObject, namespace); } } ``` ```typescript hook: { customType: ({ schemaObject, namespace, originGetType, schemas }) => { // Custom decimal type if (schemaObject.type === 'string' && schemaObject.format === 'decimal') { return 'Decimal'; } // Custom enum handling if (schemaObject.enum && schemaObject['x-enum-labels']) { return `${namespace}.${upperFirst(schemaObject.title || 'CustomEnum')}`; } return originGetType(schemaObject, namespace, schemas); } } ``` -------------------------------- ### Generate Vue + TypeScript API Client Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Configuration for generating a Vue client with TypeScript, focusing on type labels, camel case conversion, and specifying the request library (e.g., axios). React Query mode is set to 'vue'. ```typescript { schemaPath: "./openapi.yaml", serversPath: "./src/api", isGenReactQuery: true, reactQueryMode: "vue", isDisplayTypeLabel: true, isCamelCase: true, requestLibPath: "axios" } ``` -------------------------------- ### Performance Optimization: Development Speed Settings (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Speeds up development by configuring generation options. Options include generating JavaScript instead of TypeScript for faster iteration, skipping heavy features like type labels and schema generation, and enabling mock data generation for offline development. ```typescript { // Generate JavaScript for faster iteration isGenJavaScript: true, // Skip heavy features during development isDisplayTypeLabel: false, isGenJsonSchemas: false, // Enable mocks for offline development mockFolder: "./mocks" } ``` -------------------------------- ### Generate International API Client (Chinese API) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Configuration for handling international projects with Chinese APIs. This includes translating Chinese tags to English, displaying type labels, parsing enum descriptions, using camel case, and case-insensitive filtering. ```typescript { schemaPath: "./openapi.json", serversPath: "./src/apis", isTranslateToEnglishTag: true, isDisplayTypeLabel: true, isSupportParseEnumDesc: true, isCamelCase: true, filterCaseInsensitive: true } ``` -------------------------------- ### Custom File Organization: Version-Based (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Organizes generated API files based on versioning and resource names. It identifies version segments (e.g., 'v1') and the last path segment as the resource, creating paths like 'v1/resource'. Falls back to just the resource name if no version is found. No external dependencies. ```typescript hook: { customFileNames: (operationObject, apiPath, apiMethod) => { const segments = apiPath.split('/').filter(Boolean); const version = segments.find((s) => s.match(/^v\d+$/)); const resource = segments[segments.length - 1]; return version ? [`${version}/${resource}`] : [resource]; }; } ``` -------------------------------- ### Custom File Organization: Group by Feature (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Organizes generated API files by grouping operations based on the first segment of their API path, treating it as a feature. This helps in structuring the codebase around application features. Requires no external dependencies. ```typescript hook: { customFileNames: (operationObject, apiPath, apiMethod) => { const pathSegments = apiPath.split('/').filter(Boolean); const feature = pathSegments[0]; // First path segment return [feature]; }; } ``` -------------------------------- ### Generate API Clients via CLI with openapi-ts-request (Bash) Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt The `openapi-ts-request` CLI allows code generation directly from the command line without requiring configuration files. It supports installing globally or using `npx`/`pnpm dlx` for on-demand execution. Options include specifying input schema (`-i`), output directory (`-o`), request library path (`--requestLibPath`), and various generation flags like `--isGenReactQuery` and `--includeTags`. ```bash # Install globally npm i openapi-ts-request -g # Generate from local file openapi -i ./openapi.json -o ./apis # Generate from remote URL with custom request library openapi -i https://petstore3.swagger.io/api/v3/openapi.json \ -o ./src/api \ --requestLibPath "@/request" \ --isGenReactQuery true \ --reactQueryMode react # Use npx without installation (npm) npx --package=openapi-ts-request -- openapi \ -i https://api.example.com/openapi.json \ -o ./apis \ --includeTags user,pet \ --excludePaths "/internal/*" \ --isCamelCase true # Use pnpm dlx pnpm --package=openapi-ts-request@latest dlx openapi \ -i ./spec.yaml \ -o ./src/services \ --mockFolder ./mocks \ --isDisplayTypeLabel true ``` -------------------------------- ### Custom File Organization: Method-Based Splitting (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Organizes generated API files by combining tags with HTTP methods. Each tag is converted to camelCase, and then appended with the lowercase HTTP method (e.g., 'user.get'). This allows for fine-grained splitting of API functions. Requires a `camelCase` utility function. ```typescript hook: { customFileNames: (operationObject, apiPath, apiMethod) => { const tags = operationObject.tags || ['default']; const method = apiMethod.toLowerCase(); return tags.map((tag) => `${camelCase(tag)}.${method}`); }; } ``` -------------------------------- ### Custom Type Naming with OpenAPI TS Request Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Enables custom naming for generated types, differentiating between request and response types. It uses the operationId or path to generate a base name and adds suffixes like 'Request' or 'Response'. ```typescript hook: { customTypeName: (data: APIDataType) => { const baseName = upperFirst(camelCase(data.operationId || data.path)); if (data.requestBody) return `${baseName}Request`; if (data.responses) return `${baseName}Response`; return baseName; } } ``` -------------------------------- ### Custom Function Name Generation (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md An example of a custom function name generation hook for openapi-ts-request. It demonstrates how to resolve function names based on operationId or generate a default name using the path and a prefix, adhering to old version naming conventions. ```typescript import type { APIDataType } from 'openapi-ts-request/dist/generator/type'; import { genDefaultFunctionName, resolveFunctionName, stripDot, } from 'openapi-ts-request/dist/generator/util'; export default { hook: { customFunctionName(data: APIDataType, prefix: string) { if (data.operationId) return resolveFunctionName(stripDot(data.operationId), data.method); return data.method + genDefaultFunctionName(data.path, prefix); }, }, }; ``` -------------------------------- ### OpenAPI Data Transformation: Add Custom Extensions (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Iterates through all paths and operations in the OpenAPI data and adds a custom extension 'x-rate-limit' with a default value of '100/hour' if it doesn't exist. This allows for annotating API endpoints with metadata. No external dependencies. ```typescript hook: { afterOpenApiDataInited: (openAPIData) => { // Add rate limiting info Object.values(openAPIData.paths || {}).forEach((pathItem) => { Object.values(pathItem).forEach((operation) => { if (operation.operationId) { operation['x-rate-limit'] = operation['x-rate-limit'] || '100/hour'; } }); }); return openAPIData; }; } ``` -------------------------------- ### Custom Options Default Values: Authentication Headers (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Adds an 'Authorization: Bearer' header to requests if the operation requires authentication (has a 'security' property). Returns an empty object otherwise. Assumes a global token is available. No external dependencies. ```typescript hook: { customOptionsDefaultValue: (operationObject) => { const requiresAuth = operationObject.security?.length > 0; return requiresAuth ? { headers: { Authorization: 'Bearer ${token}', }, } : {}; }; } ``` -------------------------------- ### Custom Class Name Transformations with OpenAPI TS Request Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Enables custom logic for transforming tag names into class names. This includes translating Chinese tags to English and ensuring class names end with 'Controller'. It cleans and formats the tag names for consistent class naming. ```typescript hook: { customClassName: (tagName: string) => { const chineseToEnglish = { 用户管理: 'UserManagement', 订单管理: 'OrderManagement', 商品管理: 'ProductManagement', }; return chineseToEnglish[tagName] || upperFirst(camelCase(tagName)); } } ``` ```typescript hook: { customClassName: (tagName: string) => { const cleanName = upperFirst( camelCase(tagName.replace(/[^a-zA-Z0-9]/g, '')) ); return cleanName.endsWith('Controller') ? cleanName : `${cleanName}Controller`; } } ``` -------------------------------- ### Performance Optimization: Filter API Endpoints by Tags (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Optimizes generation for large APIs by filtering endpoints based on specified tags. Supports including ('includeTags') or excluding ('excludeTags') tags, with an option for case-insensitive filtering. Useful for reducing generation time and output size. ```typescript { // Filter by specific tags only priorityRule: "include", includeTags: ["user", "order", "product"], // Or exclude administrative endpoints priorityRule: "exclude", excludeTags: ["admin", "internal"], // Enable case-insensitive filtering filterCaseInsensitive: true } ``` -------------------------------- ### Custom Options Default Values: Timeout and Retries (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Sets default request options like timeout and retry logic based on the operation. It increases the timeout and retries for file upload requests ('multipart/form-data') and sets a default status validator. No external dependencies. ```typescript hook: { customOptionsDefaultValue: (operationObject) => { const isFileUpload = operationObject.requestBody?.content?.['multipart/form-data']; return { timeout: isFileUpload ? 30000 : 10000, retries: isFileUpload ? 1 : 3, validateStatus: (status: number) => status < 400, }; }; } ``` -------------------------------- ### Custom Templates: Service Controller Template (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Defines a custom template for generating service controller files. It includes importing a request library and defining asynchronous functions for each API endpoint, including parameters, path, method, and request body. Requires context object with `requestLibPath` and `TypescriptFileType.serviceController` enum. ```typescript hook: { customTemplates: { [TypescriptFileType.serviceController]: (apis, context) => { return ` // Auto-generated API client import request from '${context.requestLibPath}'; import type * as API from './types'; ${apis.map(api => ` /** ${api.summary || api.path} */ export const ${api.functionName} = async (${api.params}) => { return request<${api.responseType}>(`${api.path}`, { method: '${api.method.toUpperCase()}', ${api.data ? `data: ${api.data}, ` : ''} ...options }); }; `).join(' ')} `; } } } ``` -------------------------------- ### OpenAPI Data Transformation: Filter Deprecated Endpoints (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/agents.md Removes all operations marked as deprecated from the OpenAPI data. It iterates through paths and methods, deleting entries where the 'deprecated' flag is true. This cleans up the generated API client by excluding outdated endpoints. No external dependencies. ```typescript hook: { afterOpenApiDataInited: (openAPIData) => { Object.keys(openAPIData.paths || {}).forEach((path) => { Object.keys(openAPIData.paths[path]).forEach((method) => { const operation = openAPIData.paths[path][method]; if (operation.deprecated) { delete openAPIData.paths[path][method]; } }); }); return openAPIData; }; } ``` -------------------------------- ### Display openapi CLI help information Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md Displays detailed help information for the `openapi` CLI command. This includes a list of all available options and their descriptions, allowing users to understand and utilize the tool's full capabilities. ```bash $ openapi --help Usage: openapi [options] Options: -V, --version output the version number -i, --input OpenAPI specification, can be a path, url -o, --output output directory -cfn, --configFileName config file name -cfp, --configFilePath config file path --requestLibPath custom request lib path, for example: "@/request", "node-fetch" (default: "axios") -f, --full full replacement (default: true) --enableLogging open the log (default: false) --priorityRule priority rule, include/exclude/both (default: "include") --filterCaseInsensitive whether to perform a case-insensitive match with includeTags, includePaths, excludeTags, excludePaths filters (default: false) --includeTags <(string|RegExp)[]> generate code from include tags --includePaths <(string|RegExp)[]> generate code from include paths --excludeTags <(string|RegExp)[]> generate code from exclude tags --excludePaths <(string|RegExp)[]> generate code from exclude paths --requestOptionsType custom request method options parameter type (default: "{ [key: string]: unknown }") --requestImportStatement custom request import statement, for example: "const request = require('@/request')" --apiPrefix custom the prefix of the api path, for example: "api"(variable), "'api'"(string) --isGenReactQuery generate react-query (default: false) --reactQueryMode react-query mode, react/vue (default: "react") --isGenJavaScript generate JavaScript (default: false) --isDisplayTypeLabel generate label matching type field (default: false) --isGenJsonSchemas generate JSON Schemas (default: false) --mockFolder mock file path, for example: './mocks' --authorization docs authorization --nullable null instead of optional (default: false) --isTranslateToEnglishTag translate chinese tag name to english tag name (default: false) --isOnlyGenTypeScriptType only generate typescript type (default: false) --isCamelCase camelCase naming of controller files and request client (default: true) --isSupportParseEnumDesc parse enum description to generate enum label (default: false) -h, --help display help for command ``` -------------------------------- ### Generate APIs using NPX (pnpm) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md Use `pnpm dlx` to execute the `openapi-ts-request` CLI tool. This method downloads the package temporarily for execution, similar to `npx`. ```bash # pnpm pnpm --package=openapi-ts-request@latest dlx openapi -i ./openapi.json -o ./apis pnpm --package=openapi-ts-request@latest dlx openapi -i https://petstore3.swagger.io/api/v3/openapi.json -o ./apis ``` -------------------------------- ### Run openapi-ts-request CLI to generate API code Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md Executes the `openapi-ts-request` CLI tool to generate API client code. It takes an OpenAPI specification file as input and outputs the generated code to a specified directory. This is the primary command for using the tool. ```bash openapi -i ./spec.json -o ./apis ``` -------------------------------- ### Generate APIs using npm script Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md Add an 'openapi' script to your `package.json` to run the generation process. The generated files will be located in the specified `serversPath`. ```bash { "scripts": { "openapi": "openapi-ts" } } ``` -------------------------------- ### Configure openapi-ts-request with defineConfig (TypeScript) Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt The `defineConfig` helper provides type-safe configuration for setting up `openapi-ts-request` in cosmiconfig-based projects. It supports defining configurations for single or multiple OpenAPI sources, specifying schema paths, output directories, request libraries, and various generation options. The configuration can be exported from a file like `openapi-ts-request.config.ts`. ```typescript // openapi-ts-request.config.ts import { defineConfig } from 'openapi-ts-request'; // Single service configuration export default defineConfig({ schemaPath: 'http://petstore.swagger.io/v2/swagger.json', serversPath: './src/apis', requestLibPath: 'axios', isGenReactQuery: false, isCamelCase: true, }); // Multiple service configuration export default defineConfig([ { schemaPath: 'http://app.swagger.io/v2/swagger.json', serversPath: './src/apis/app', describe: 'Application API', includeTags: ['auth', 'users'], }, { schemaPath: 'http://payment.swagger.io/v2/swagger.json', serversPath: './src/apis/payment', describe: 'Payment Gateway API', authorization: 'Bearer token123', }, ]); // Run with: npm run openapi (package.json script: "openapi": "openapi-ts") ``` -------------------------------- ### Configure openapi-ts-request with CosmiConfig (TypeScript) Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md Configure openapi-ts-request using a TypeScript configuration file named `openapi-ts-request.config.ts` in the project root. It supports single or array configurations for schema paths and output server paths. ```typescript import { defineConfig } from 'openapi-ts-request'; export default defineConfig({ schemaPath: 'http://petstore.swagger.io/v2/swagger.json', serversPath: './src/apis', }); ``` ```typescript import { defineConfig } from 'openapi-ts-request'; export default defineConfig([ { schemaPath: 'http://app.swagger.io/v2/swagger.json', serversPath: './src/apis/app', }, { schemaPath: 'http://auth.swagger.io/v2/swagger.json', serversPath: './src/apis/auth', }, ]); ``` -------------------------------- ### Generating Mock Services with MockJS in TypeScript Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt This snippet shows how to configure openapi-ts-request to generate mock services using MockJS. By specifying the `mockFolder` option, the tool will create mock files based on your API specifications, providing realistic fake data for development and testing purposes. These mocks can be used with server frameworks like @umijs/server. ```typescript import { defineConfig } from 'openapi-ts-request'; export default defineConfig({ schemaPath: 'https://api.example.com/openapi.json', serversPath: './src/api', mockFolder: './mocks', }); // Generated mock file structure: // mocks/ // ├── user.ts // └── pet.ts // Example generated mock (mocks/user.ts): // import mockjs from 'mockjs'; // // export default { // 'GET /api/user/:id': (req: any, res: any) => { // res.json(mockjs.mock({ // id: '@id', // name: '@name', // email: '@email', // 'age|18-60': 1, // avatar: '@image("200x200")', // createdAt: '@datetime', // })); // }, // 'POST /api/user': (req: any, res: any) => { // res.json(mockjs.mock({ // success: true, // message: 'User created', // data: { id: '@id' }, // })); // }, // }; // Use with @umijs/server or similar mock server ``` -------------------------------- ### Apifox Integration for API Documentation Synchronization in TypeScript Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt This configuration demonstrates integrating openapi-ts-request directly with the Apifox platform. It utilizes a project ID and Apifox token to fetch OpenAPI specifications and synchronize API documentation seamlessly. This allows for generating code directly from Apifox without needing a separate schema file. ```typescript import { defineConfig } from 'openapi-ts-request'; export default defineConfig({ serversPath: './src/api', apifoxConfig: { projectId: '1234567890', apifoxToken: 'your-apifox-token-here', locale: 'en-US', // or 'zh-CN' oasVersion: '3.0', exportFormat: 'JSON', selectedTags: ['v1', 'public'], // or '*' for all excludedByTags: ['deprecated', 'internal'], includeApifoxExtensionProperties: true, addFoldersToTags: true, }, isGenReactQuery: true, mockFolder: './mocks', }); // This configuration fetches the OpenAPI spec directly from Apifox // and generates code without needing a schemaPath // Run with: npm run openapi ``` -------------------------------- ### Configure openapi-ts-request with JavaScript Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md Configure the service generation using a JavaScript file (`openapi-ts-request.config.js`). This method is suitable for JavaScript projects or specific build configurations. ```javascript const { generateService } = require('openapi-ts-request'); generateService({ schemaPath: 'http://petstore.swagger.io/v2/swagger.json', serversPath: './apis', }); ``` -------------------------------- ### Customizing API Client Generation with Hooks in TypeScript Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt This snippet demonstrates how to use the 'hook' system in openapi-ts-request to customize various aspects of API client generation, such as function names, type names, file naming conventions, and default request options. It allows for deep modification of the generated code based on OpenAPI specifications. ```typescript import { defineConfig } from 'openapi-ts-request'; import type { APIDataType } from 'openapi-ts-request/dist/generator/type'; import type { OperationObject, SchemaObject } from 'openapi-ts-request'; export default defineConfig({ schemaPath: 'https://api.example.com/openapi.json', serversPath: './src/api', hook: { // Modify OpenAPI data after initialization afterOpenApiDataInited: (openAPIData) => { // Add custom server URL openAPIData.servers = [{ url: 'https://prod.example.com' }]; return openAPIData; }, // Custom function naming customFunctionName: (data: APIDataType) => { const operationId = data.operationId; if (operationId) { return operationId.replace(/Using(GET|POST|PUT|DELETE)/, ''); } return `${data.method}_${data.path.replace(/\//g, '_')}`; }, // Custom type naming customTypeName: (data: APIDataType) => { return `${data.namespace}.${data.typeName}DTO`; }, // Custom class/controller naming customClassName: (tagName: string) => { return `${tagName}Service`; }, // Transform number types to string for precision customType: ({ schemaObject, namespace, originGetType, schemas }) => { if ( (schemaObject as SchemaObject).type === 'number' && !(schemaObject as SchemaObject).format ) { return 'string'; // Return custom type for BigDecimal } return originGetType(schemaObject as SchemaObject, namespace, schemas); }, // Generate multiple files per operation customFileNames: (operationObject: OperationObject, apiPath: string) => { const tags = operationObject.tags || []; return tags.length > 0 ? tags : ['default']; }, // Add default options to requests customOptionsDefaultValue: (operation: OperationObject) => { if (operation.security) { return { withCredentials: true }; } return undefined; }, }, }); ``` -------------------------------- ### Configure Custom HTTP Client for UniApp Requests Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt Integrate a custom HTTP client, such as UniApp's request, by specifying the library path, import statement, and request options type in the configuration. This allows the generated API functions to use your preferred network request methods. ```typescript import { defineConfig } from 'openapi-ts-request'; export default defineConfig({ schemaPath: 'https://api.example.com/openapi.json', serversPath: './src/api', requestLibPath: '@/utils/uniRequest', requestImportStatement: "import request from '@/utils/uniRequest';", requestOptionsType: 'UniApp.RequestOptions', apiPrefix: "'https://api.example.com'", }); ``` -------------------------------- ### Generate API Service Client with openapi-ts-request (TypeScript) Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt The `generateService` function creates API clients from OpenAPI specifications. It supports basic usage with remote schemas and advanced configurations including path filtering, tag inclusion/exclusion, and options for generating React Query hooks, mock servers, and type definitions. Requires the 'openapi-ts-request' package. ```typescript import { generateService } from 'openapi-ts-request'; // Basic usage with remote OpenAPI spec await generateService({ schemaPath: 'http://petstore.swagger.io/v2/swagger.json', serversPath: './src/apis', requestLibPath: 'axios', }); // Advanced configuration with filtering and customization await generateService({ schemaPath: 'https://api.example.com/v3/openapi.json', serversPath: './src/api', requestLibPath: '@/utils/request', priorityRule: 'both', includeTags: ['user', 'pet', /product.*/], excludePaths: ['/internal/*'], isGenReactQuery: true, reactQueryMode: 'react', isDisplayTypeLabel: true, mockFolder: './mocks', nullable: false, isCamelCase: true, hook: { customFunctionName: (data) => `${data.method}${data.path.replace(/\//g, '_')}`, customClassName: (tagName) => `${tagName}Controller`, }, }); // Generated output structure: // src/apis/ // ├── index.ts // Re-exports all controllers // ├── types.ts // TypeScript interfaces // ├── pet.ts // Pet API controller // └── user.ts // User API controller ``` -------------------------------- ### Filter API Generation by Tags and Paths (TypeScript) Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt Filters the API generation process by specifying which tags and paths to include or exclude. This configuration allows for precise control over the generated client code, supporting both inclusion and exclusion modes with string or regular expression matching. ```typescript import { defineConfig } from 'openapi-ts-request'; export default defineConfig({ schemaPath: 'https://api.example.com/openapi.json', serversPath: './src/api', // Include mode: only generate specified tags priorityRule: 'include', includeTags: ['user', 'authentication', /product.*/], includePaths: ['/api/v1/users/*', '/api/v1/auth/*'], // Exclude mode: generate everything except specified // priorityRule: 'exclude', // excludeTags: ['internal', 'deprecated'], // excludePaths: ['/api/internal/*', '/api/admin/*'], // Both mode: include specified but exclude others // priorityRule: 'both', // includeTags: ['user', 'product'], // excludeTags: ['deprecated'], // includePaths: ['/api/v1/*'], // excludePaths: ['/api/v1/internal/*'], // Case-insensitive filtering filterCaseInsensitive: true, }); // Only user, authentication, and product-related APIs will be generated // Paths matching /api/v1/users/* or /api/v1/auth/* will be included ``` -------------------------------- ### Generate React Query or Vue Query Hooks Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt Enable the generation of ready-to-use hooks for React Query or Vue Query by setting the `isGenReactQuery` and `reactQueryMode` options. This feature automates query key management and type inference for efficient data fetching and state management. ```typescript import { defineConfig } from 'openapi-ts-request'; export default defineConfig({ schemaPath: 'https://api.example.com/openapi.json', serversPath: './src/api', isGenReactQuery: true, reactQueryMode: 'react', // or 'vue' }); ``` -------------------------------- ### Resolve Schema References with patchSchema Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt Use the `patchSchema` function to resolve `$ref` and `allOf` references within JSON schemas. This utility creates fully expanded schema objects, which is useful for handling complex or fragmented schema definitions. ```typescript import { patchSchema } from 'openapi-ts-request'; import type { ComponentsObject, ISchemaObject } from 'openapi-ts-request'; // Example: Resolve schema with $ref and allOf const schemas: ComponentsObject['schemas'] = { BaseUser: { type: 'object', properties: { id: { type: 'string' }, createdAt: { type: 'string', format: 'date-time' }, }, required: ['id'], }, AdminUser: { allOf: [ { $ref: '#/components/schemas/BaseUser' }, { type: 'object', properties: { role: { type: 'string', enum: ['admin'] }, permissions: { type: 'array', items: { type: 'string' } }, }, required: ['role'], }, ], }, }; const adminUserSchema: ISchemaObject = { $ref: '#/components/schemas/AdminUser' }; const resolvedSchema = patchSchema(adminUserSchema, schemas); // Result: // { // type: 'object', // properties: { // id: { type: 'string' }, // createdAt: { type: 'string', format: 'date-time' }, // role: { type: 'string', enum: ['admin'] }, // permissions: { type: 'array', items: { type: 'string' } } // }, // required: ['id', 'role'], // 'x-id': 'AdminUser' // } ``` -------------------------------- ### Patch JSON Schema with References Source: https://github.com/openapi-ui/openapi-ts-request/blob/main/README-en_US.md This function patches a JSON schema by resolving references like '$ref' and '$allOf' within the provided components schemas. It's useful for generating complete schemas from OpenAPI definitions. ```typescript export declare function patchSchema( schema: ISchemaObject, schemas: ComponentsObject['schemas'] ): T; ``` -------------------------------- ### Generate JSON Schemas for Runtime Validation (TypeScript) Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt Enables the generation of JSON Schema files from the OpenAPI specification for runtime validation using libraries like ajv or zod. The generated schemas are placed in a specified directory and can be used for validating API request and response data. ```typescript import { defineConfig } from 'openapi-ts-request'; export default defineConfig({ schemaPath: 'https://api.example.com/openapi.json', serversPath: './src/api', isGenJsonSchemas: true, }); // Generated JSON Schema files: // src/api/schemas/ // ├── User.json // ├── Pet.json // └── Order.json // Example usage with ajv: import Ajv from 'ajv'; import UserSchema from '@/api/schemas/User.json'; const ajv = new Ajv(); const validate = ajv.compile(UserSchema); const userData = { id: '123', name: 'John Doe', email: 'john@example.com', }; if (validate(userData)) { console.log('Valid user data'); } else { console.error('Validation errors:', validate.errors); } // Runtime schema resolution with patchSchema: import { patchSchema } from 'openapi-ts-request'; import schemas from '@/api/schemas/index.json'; const userSchema = patchSchema( { $ref: '#/components/schemas/User' }, schemas ); ``` -------------------------------- ### Generate Type Field Labels and Enums (TypeScript) Source: https://context7.com/openapi-ui/openapi-ts-request/llms.txt Configures openapi-ts-request to generate type field labels and enum translations for internationalization and UI display. It takes an OpenAPI schema path and outputs generated types, including enums, label mappings, and options arrays suitable for UI components. ```typescript import { defineConfig } from 'openapi-ts-request'; export default defineConfig({ schemaPath: 'https://api.example.com/openapi.json', serversPath: './src/api', isDisplayTypeLabel: true, isSupportParseEnumDesc: true, }); // Generated types with labels: // src/api/types.ts export enum UserRole { User = 0, Agent = 1, Admin = 2, } export const UserRoleLabel = { [UserRole.User]: 'Normal User', [UserRole.Agent]: 'Agent', [UserRole.Admin]: 'Administrator', }; export const UserRoleOptions = [ { value: UserRole.User, label: 'Normal User' }, { value: UserRole.Agent, label: 'Agent' }, { value: UserRole.Admin, label: 'Administrator' }, ]; // Usage in UI components: import { UserRole, UserRoleLabel, UserRoleOptions } from '@/api/types'; function UserForm() { return ( ); } console.log(UserRoleLabel[UserRole.Admin]); // "Administrator" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.