openapi-ts-request

repository·main·Indexed 19 days ago

https://github.com/openapi-ui/openapi-ts-request

A tool to generate TypeScript/JavaScript client request functions, types, and mock services from Swagger2, OpenAPI 3.0/3.1, or Apifox definitions. It supports custom request clients, react-query/vue-query integration, JSON Schemas, and enum translation. Features include custom hooks for modifying code generation, Apifox project integration, and a CLI for generating services based on a configuration file.

Tokens
12.9K
Snippets
33
Records
42
Agent score
66%

What's inside openapi-ts-request

  1. How interactive mode works with multiple configurations

    main

    When you use a configuration file that contains an array of multiple service configurations, the CLI defaults to an interactive mode (if --interactive is enabled).

    Instead of running all tasks at once, the CLI will present a multiselect prompt (using @clack/prompts) allowing you to choose which specific services from the configuration array you want to generate. If you cancel the selection, the process terminates gracefully.

    # If your config file looks like this:
    [
      { "schemaPath": "api1.yaml", "serversPath": "./api1" },
      { "schemaPath": "api2.yaml", "serversPath": "./api2" }
    ]
    
    # Running the command will prompt:
    # "请选择要生成的 service" (Please select the service to generate)
  2. Quickly preview generated files with npx or pnpm

    main

    You can use npx or pnpm to run the CLI directly without adding it to your project dependencies to preview the output. Use the -i flag for the input schema and -o for the output directory.

    # Using npm/npx
    npx --package=openapi-ts-request -- openapi -i ./openapi.json -o ./apis --isGenReactQuery=true
    npx --package=openapi-ts-request -- openapi -i https://petstore3.swagger.io/api/v3/openapi.json -o ./apis --isGenReactQuery=true
    
    # Using pnpm
    pnpm --package=openapi-ts-request@latest dlx openapi -i ./openapi.json -o ./apis --isGenReactQuery=true
    pnpm --package=openapi-ts-request@latest dlx openapi -i https://petstore3.swagger.io/api/v3/openapi.json -o ./apis --isGenReactQuery=true
  3. Run via NPX

    main

    Use npx to run the generator without a permanent configuration file by passing arguments directly.

    # Using 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
    
    # Using 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
  4. Use the openapi CLI to generate services

    main

    The openapi CLI tool generates TypeScript or JavaScript services from an OpenAPI specification. You can run it in two ways:

    1. Directly via arguments: Provide --input (path or URL) and --output (directory) to trigger immediate generation.
    2. Via configuration files: Provide --configFilePath or --configFileName to load settings from a file. If multiple configurations are found in the file, the CLI enters an interactive mode to let you select which services to generate.

    If no input/output arguments are provided and no configuration file is found, the CLI will exit with an error.

    # Example: Generate using direct arguments
    openapi --input ./swagger.yaml --output ./src/api
    
    # Example: Generate using a specific config file
    openapi --configFilePath ./configs/api-config.json
  5. Generate request client from Swagger/OpenAPI

    main

    To generate a request client from an existing Swagger or OpenAPI schema, create an openapi-ts-request.config.ts file in your project root. Define your configuration using the GenerateServiceProps type, specifying the schemaPath. You can then run the generation via a script in your package.json.

    import type { GenerateServiceProps } from 'openapi-ts-request';
    
    export default [
      {
        schemaPath: 'https://petstore3.swagger.io/api/v3/openapi.json',
      },
    ] as GenerateServiceProps[];

    Add this to your package.json:

    "scripts": {
      "openapi": "openapi-ts"
    }

    Run the command:

    npm run openapi
  6. Generate API clients using Node.js (JS/TS)

    main

    You can programmatically trigger code generation by creating a configuration file and running it with Node.js or ts-node.

    // For TypeScript (run with ts-node)
    // openapi-ts-request.config.ts
    const { generateService } = require('openapi-ts-request');
    
    generateService({
      schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
      serversPath: './apis',
    });
    
    // For JavaScript (run with node)
    // openapi-ts-request.config.js
    const { generateService } = require('openapi-ts-request');
    
    generateService({
      schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
      serversPath: './apis',
    });
  7. Install openapi-ts-request

    main

    You can install openapi-ts-request as a development dependency using npm or pnpm to generate TypeScript/JavaScript client request functions, types, and mock services from OpenAPI/Swagger specifications.

    # npm
    npm i openapi-ts-request --save-dev
    
    # pnpm
    pnpm i openapi-ts-request -D
  8. Generate React Query configuration

    main

    Enable isGenReactQuery: true to generate React Query compatible options and hooks. For GET requests, it generates queryOptions functions. For POST, DELETE, and PATCH requests, it generates custom mutation hooks.

    import type { GenerateServiceProps } from 'openapi-ts-request';
    
    export default [
      {
        schemaPath: 'https://petstore3.swagger.io/api/v3/openapi.json',
        requestLibPath: '@/core/request/index.ts',
        isGenReactQuery: true,
      },
    ] as GenerateServiceProps[];
  9. Add API gateway prefixes using `apiPrefix`

    main

    If your API paths in the schema do not include the gateway prefix required for actual requests (e.g., /user, /manage), use the apiPrefix option to prepend a string to all generated paths.

    export default [
      {
        schemaPath: 'http://127.0.0.1:4523/export/openapi/2?version=3.0',
        requestLibPath: '@/core/request/index.ts',
        apiPrefix: '"/user"',
      },
      {
        schemaPath: 'http://127.0.0.1:4523/export/openapi/3?version=3.0',
        requestLibPath: '@/core/request/index.ts',
        apiPrefix: '"/manage"',
      },
    ] as GenerateServiceProps[];
  10. Configure Apifox integration

    main

    When using Apifox as your source, use the following configuration properties to manage project connection and export settings:

    | Property | Type | Description | Required | | --- | --- | --- | | projectId | string | Project ID | true | | apifoxToken | string | Apifox Token | true | | local | string | Language (default: zh-CN) | false | | apifoxVersion | string | Apifox version (default: 2024-03-28) | false | | selectedTags | * or string[] | Tags to include (default: *) | false | | excludedByTags | string[] | Tags to exclude (default: []) | false | | oasVersion | string | OpenAPI spec version (e.g., "2.0", "3.0", "3.1", default: '3.0') | false | | exportFormat | string | Export format ('JSON' or 'YAML', default: 'JSON') | false | | includeApifoxExtensionProperties | boolean | Include Apifox extension fields x-apifox | false | | addFoldersToTags | boolean | Include directory names in tag fields | false | | branchId | number | Branch ID | false | | moduleId | number | Module ID | false |

  11. Generate only TypeScript types

    main

    If you only need the TypeScript type definitions and do not want the generated request functions, set isOnlyGenTypeScriptType: true in your configuration.

    import type { GenerateServiceProps } from 'openapi-ts-request';
    
    export default [
      {
        schemaPath: 'http://127.0.0.1:4523/export/openapi/2?version=3.0',
        requestLibPath: '@/core/request/index.ts',
        isOnlyGenTypeScriptType: true,
      },
    ] as GenerateServiceProps[];