openapi2aspida

repository·main·Indexed 41 days ago

https://github.com/aspida/openapi2aspida

A tool that converts OpenAPI 3.0 and Swagger 2.0 definitions (YAML or JSON) into type-safe aspida API clients. It provides a CLI and a default export function to generate route files and types, ensuring full type safety for request bodies and response types when used with aspida-compatible clients like @aspida/axios.

Tokens
1.9K
Snippets
7
Records
7
Agent score
52%

What's inside openapi2aspida

  1. Get started with openapi2aspida

    main

    Convert OpenAPI 3.0 or Swagger 2.0 definitions (YAML or JSON) into aspida type-safe API clients.

    To use it, you can run the CLI via npx pointing to a remote URL or a local file, then install the necessary dependencies to run the generated client (such as @aspida/axios and axios).

    $ mkdir petstore-api
    $ cd petstore-api
    $ npx openapi2aspida -i https://petstore.swagger.io/v2/swagger.json
    
    $ npm init -y
    $ npm install @aspida/axios axios typescript ts-node @types/node
  2. Build from a config file

    main

    Instead of passing CLI flags every time, you can create an aspida.config.js file in your project root to manage generation settings. Note that the input key in this config refers to the source OpenAPI file, which acts as the output for the generated files.

    module.exports = {
      input: 'api', // This is the directory where aspida files will be output
      outputEachDir: true, // Generate $api.ts in each endpoint directory
      openapi: { inputFile: 'https://petstore.swagger.io/v2/swagger.json' },
    };

    Then run:

    $ npx openapi2aspida
  3. Use the generated aspida client

    main

    Once openapi2aspida has generated the api/$api.ts file, you can use it by passing an aspida-compatible client (like @aspida/axios) to the generated api function. This provides full type safety for request bodies and response types.

    import axiosClient from '@aspida/axios';
    import api from './api/$api';
    import type { Pet } from './api/@types';
    
    (async () => {
      const client = api(axiosClient());
      const petId = 100;
      const body: Pet = {
        id: petId,
        name: 'hoge',
        photoUrls: [],
        status: 'available',
      };
    
      // POST request with typed body
      await client.pet.$post({ body });
    
      // GET request with path parameter
      const pet = await client.pet._petId(petId).$get();
      console.log(pet);
    })();
  4. Configure openapi2aspida via aspida.config.js

    main

    The openapi2aspida plugin is configured using an array of configuration objects exported from aspida.config.js. Each object in the array defines a specific generation task.

    Key configuration properties include:

    • input: The base directory where the generated files will be placed.
    • outputEachDir: A boolean flag. When true, it indicates that files should be output to subdirectories within the input directory.
    • openapi: An object containing OpenAPI-specific settings:
      • inputFile: The path to the OpenAPI/Swagger specification file (supports .yaml, .yml, and .json).
      • yaml: A boolean flag to explicitly specify if the input is YAML (set to false when using .json files).
    module.exports = [
      {
        input: 'samples/swagger',
        outputEachDir: true,
        openapi: {
          inputFile: 'samples/swagger.yaml'
        },
      },
      {
        input: 'samples/openapi',
        outputEachDir: true,
        openapi: {
          inputFile: 'samples/openapi.json',
          yaml: false
        },
      }
    ];
  5. CLI options for openapi2aspida

    main

    Use the following flags to control the generation process via the command line:

    • -i, --input: Path to the OpenAPI spec file (URL or local path).
    • -o, --outputdir: Change the directory where the generated files are placed.
    • -c, --config: Path to an aspida configuration file.
    • --version: Display the current version of openapi2aspida.
    npx openapi2aspida -i=openApi/sample.yaml -o=lib/api/sample
  6. Execute openapi2aspida via the default export function

    main

    The default export of openapi2aspida is a function used to generate aspida route files and types from OpenAPI/Swagger specifications. You can call this function without arguments to use the default configuration, or pass a PartialConfig object to override settings.

    When executed, the function:

    1. Resolves the configuration.
    2. Ensures the output directory exists and is empty.
    3. Builds the necessary templates and types.
    4. Writes the generated route files to the specified output directory.

    Note: If the destination path is not an empty directory, the process will log a fatal error and stop.

    import openapi2aspida from 'openapi2aspida';
    
    // Example: Running with custom configuration
    await openapi2aspida({
      input: 'path/to/openapi.yaml',
      output: 'src/api',
      // ... other PartialConfig options
    });
  7. Use the openapi2aspida CLI

    main

    The openapi2aspida CLI allows you to generate aspida API clients from OpenAPI/Swagger specifications. You can provide configuration via a config file or by specifying input and output paths directly through CLI flags.

    CLI Flags

    FlagAliasTypeDescription
    --input-istringThe path to the OpenAPI/Swagger input file. If not provided, the CLI looks for openapi.inputFile in the configuration file.
    --outputdir-ostringThe directory where the generated files will be placed. If not provided, the CLI looks for openapi.outputDir in the configuration file.
    --config-cstringThe path to a configuration file. If multiple configurations are detected, the CLI will build all of them.
    --version-vstringDisplays the current version of openapi2aspida and exits.

    Usage Patterns

    1. Using a configuration file (Recommended) If you have a configuration file defined, you can run the CLI simply by pointing to it:

    openapi2aspida --config path/to/config.json

    2. Overriding input/output via CLI You can use a config file for general settings but override specific paths via flags:

    openapi2aspida --config path/to/config.json --input ./spec.yaml --outputdir ./src/api

    3. Running without a config file If you are not using a config file, you must provide the input file path:

    openapi2aspida --input ./spec.yaml --outputdir ./src/api
    # Example: Using a config file with overrides
    openapi2aspida --config path/to/config.json --input ./spec.yaml --outputdir ./src/api