# api-farmer

> API module generation tool based on Openapi3/Swagger2.

Latest version **0.1.6** (published 2026-11-12) · MIT license · 0 weekly downloads

## Install

```sh
npm install api-farmer
pnpm add api-farmer
yarn add api-farmer
bun add api-farmer
```

Provides the command `af`.

## Health

**Score 65/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; recently updated; high maintenance score.

Warnings: low downloads; pre 1.0.

## Facts

| | |
|---|---|
| Version | 0.1.6 |
| Published | 2026-11-12 |
| First published | 2025-01-14 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 12 |
| Unpacked size | 43.4 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 46 |
| Author | haoziqaq |
| Maintainers | haozijunqaq |
| Keywords | api generator, cli, json schema, openapi, swagger |

## Links

- npm: https://www.npmjs.com/package/api-farmer
- Repository: https://github.com/varletjs/api-farmer
- Homepage: https://github.com/varletjs/api-farmer#readme
- Issues: https://github.com/varletjs/api-farmer/issues
- npm.io page: https://npm.io/package/api-farmer

## Dependencies (12)

- [ejs](https://npm.io/package/ejs.md) ^3.1.10
- [yaml](https://npm.io/package/yaml.md) ^2.7.0
- [rslog](https://npm.io/package/rslog.md) ^1.2.3
- [rattail](https://npm.io/package/rattail.md) ^2.0.3
- [fs-extra](https://npm.io/package/fs-extra.md) ^11.2.0
- [prettier](https://npm.io/package/prettier.md) ^3.4.2
- [unconfig](https://npm.io/package/unconfig.md) ^7.5.0
- [commander](https://npm.io/package/commander.md) ^13.0.0
- [pluralize](https://npm.io/package/pluralize.md) ^8.0.0
- [swagger2openapi](https://npm.io/package/swagger2openapi.md) ^7.0.8
- [@types/pluralize](https://npm.io/package/@types/pluralize.md) ^0.0.33
- [openapi-typescript](https://npm.io/package/openapi-typescript.md) ^7.5.2

## Alternatives

- [@salesforce/cli](https://npm.io/package/@salesforce/cli.md) — 389.7K weekly downloads
- [@mintlify/cli](https://npm.io/package/@mintlify/cli.md) — 208.9K weekly downloads
- [@grafana/e2e-selectors](https://npm.io/package/@grafana/e2e-selectors.md) — 128.7K weekly downloads
- [mintlify](https://npm.io/package/mintlify.md) — 112.0K weekly downloads
- [@intlayer/cli](https://npm.io/package/@intlayer/cli.md) — 22.8K weekly downloads

## Recent versions

- 0.1.6 (latest) — 2026-11-12
- 0.0.26-alpha.1743349393529 (alpha) — 2025-03-30
- 0.1.5 — 2026-04-12
- 0.1.4 — 2026-04-12
- 0.1.3 — 2026-03-26
- 0.1.2 — 2026-03-23
- 0.1.1 — 2025-10-17
- 0.1.0 — 2025-08-25
- 0.0.28 — 2025-04-15
- 0.0.27 — 2025-04-06
- 0.0.26 — 2025-03-30
- 0.0.26-alpha.1743347972676 — 2025-03-30
- 0.0.26-alpha.1743347452766 — 2025-03-30
- 0.0.26-alpha.1743346634787 — 2025-03-30
- 0.0.25 — 2025-02-15
- … 28 more at https://npm.io/package/api-farmer/versions

## README

# api-farmer

### Intro

API module generation tool based on `Openapi3/Swagger2`.

### Features

- 🌐 &nbsp; Supports generating all API modules from `OpenAPI3/Swagger2 schemas`
- 📦 &nbsp; Supports generating `ts/js` modules
- 🛠️ &nbsp; Comprehensive `ts type` generation
- ✏️ &nbsp; Supports custom `ejs` templates for tailored content generation
- 🔄 &nbsp; Allows using a `transformer` to modify all variables in templates for fine-grained customization
- 💻 &nbsp; Supports both `cli` and `node.js api`
- 📋 &nbsp; Includes built-in presets for [axle](https://github.com/varletjs/axle) and [axios](https://axios-http.com/docs/intro) templates

### Quick Start

#### 1. Installation

```shell
# npm
npm i api-farmer -D
# yarn
yarn add api-farmer -D
# pnpm
pnpm i api-farmer -D
```

#### 2. Setup

```ts
// in project root path api-farmer.config.ts or api-farmer.config.js
import { defineConfig } from 'api-farmer'

export default defineConfig({
  // openapi or swagger schema path or resource url, defaults './schema.json'
  input: './schema.yaml',
  // generated codes output path, defaults './src/apis/generated'
  output: './src/apis/generated',
  // 'axle' or 'axios', defaults 'axle'.
  preset: 'axios',
})
```

#### 3. Run Command

```shell
npx af
```

> [!TIP]
> The generated content does not include the integration of the request client.

#### Some Examples

Some simple usage examples can be found [here](fixtures)

### Request import path

The preset templates import the request instance from `@/request` by default. If your request instance lives elsewhere, use `requestImportPath` to change the import path in the generated files.

```ts
// api-farmer.config.ts
import { defineConfig } from 'api-farmer'

export default defineConfig({
  requestImportPath: '@/shared/request',
})
```

The value is also passed to custom templates as the `requestImportPath` template variable.

### Custom code generation templates

Create `api-farmer.ejs` in the project root, which will replace the `preset` template.
The template format can refer to the preset template listed below:

- [Axle](templates/axle.ejs)
- [Axios](templates/axios.ejs)

And see the bottom of the document for template variable definitions.

### Transformer API

You can use the Transformer API to further define template variables, which will override the default transformation rules.

```ts
// api-farmer.config.ts
import { defineConfig } from 'api-farmer'

export default defineConfig({
  transformer: {
    moduleName({ name }) {
      // The new module name.
      return `${name}.generated`
    },
    verb() {},
    url() {},
    entity() {},
    name() {},
    fn() {},
    comment() {},
    type() {},
    typeValue() {},
    typeQuery() {},
    typeQueryValue() {},
    typeRequestBody() {},
    typeRequestBodyValue() {},
    typeResponseBody() {},
    typeResponseBodyValue() {},
  },
})
```

#### `name` Transformer

The `name` transformer is a convenience option that derives both `fn` and `type` from a single function. When set, `fn` is the return value, and `type` is automatically capitalized from `fn`. This avoids writing duplicate logic for `fn` and `type`.

```ts
export default defineConfig({
  transformer: {
    name({ verb, entity }) {
      return `api${verb}${entity}`
      // fn   -> apiGetUsers
      // type -> ApiGetUsers
    },
  },
})
```

> [!NOTE]
> If `name` is set, `fn` and `type` transformers will be ignored.

### Configuration Options

```ts
export interface Config {
  /**
   * The path to the OpenAPI/Swagger schema file.
   * @default './schema.json'
   */
  input?: string
  /**
   * The path to the output directory.
   * @default './src/apis/generated'
   */
  output?: string
  /**
   * The base path of the API endpoints.
   */
  base?: string
  /**
   * The filename of the generated openapi types file.
   * @default '_types.ts'
   */
  typesFilename?: string
  /**
   * The module path that the generated files import the request instance from.
   * @default '@/request'
   */
  requestImportPath?: string
  /**
   * Whether to generate TypeScript code.
   * @default true
   */
  ts?: boolean
  /**
   * Whether to generate only types.
   * @default false
   */
  typesOnly?: boolean
  /**
   * Whether to override the existing files, or an array of filenames to override.
   * @default true
   */
  overrides?: boolean | string[]
  /**
   * The preset ejs template to use.
   * @default 'axle'
   */
  preset?: Preset
  /**
   * Defines which return status codes will be typed
   * @default (status) => status >= 200 && status < 300
   */
  validateStatus?: (status: number) => boolean
  /**
   * The transformer api options, used to override the default transformation rules.
   */
  transformer?: Partial<Transformer>
  /**
   * Certain uncountable nouns that do not change from singular to plural
   */
  uncountableNouns?: string[]
  /**
   * Whether to clean the output directory before generating.
   * @default true
   */
  clean?: boolean
  /**
   *  The options for the openapiTS library.
   *  @see https://openapi-ts.dev/node
   */
  openapiTsOptions?: OpenAPITSOptions
  /**
   * Whether to exclude deprecated API endpoints.
   * @default false
   */
  excludeDeprecated?: boolean
}
```

### Template Variable Definitions

```ts
export interface ApiModuleTemplateData {
  /**
   * API module metadata
   */
  apiModule: ApiModule
  /**
   * The name of the generated api ts type aggregation file
   */
  typesFilename: string
  /**
   * The module path that the request instance is imported from
   */
  requestImportPath: string
  /**
   * Whether to generate ts code
   */
  ts: boolean
  /**
   * Whether to generate only types.
   */
  typesOnly?: boolean
}

export interface ApiModule {
  /**
   * The name of the API module
   */
  name: string
  /**
   * API module payloads
   */
  payloads: ApiModulePayload[]
}

export interface ApiModulePayload {
  /**
   * The comment of the API endpoint, including summary, description, URL, and method.
   */
  comment: string
  /**
   * The name of the API function/dispatcher,
   * such as apiGetUsers, apiCreatePost, apiUpdateComment, etc.
   */
  fn: string
  /**
   * The URL of the API endpoint,
   * such as /users, /posts, /comments, etc.
   */
  url: string
  /**
   * The HTTP method of the API endpoint,
   * such as get, post, put, delete, etc.
   */
  method: string
  /**
   * The HTTP verb of the API endpoint,
   * such as Get, Create, Update, Delete, etc.
   */
  verb: string
  /**
   * The entity name of the API endpoint,
   * such as User, Comment, Post, etc.
   */
  entity: string
  /**
   * The request content type of the API endpoint, such as 'application/json', 'application/x-www-form-urlencoded'.
   */
  requestContentType?: string
  /**
   * The type name of the API endpoint,
   * such as ApiGetUsers, ApiCreatePost, ApiUpdateComment, etc.
   */
  type: string
  /**
   * The value of the type of the API endpoint,
   * such as paths['/users']['get'], paths['/posts']['post'], paths['/comments']['put'], etc.
   */
  typeValue: string
  /**
   * The type name of the query parameters of the API endpoint,
   * such as ApiGetUsersQuery, ApiCreatePostQuery, ApiUpdateCommentQuery, etc.
   */
  typeQuery: string
  /**
   * The value of the type of the query parameters of the API endpoint, such as
   * ApiGetUsersQuery['parameters']['query'], ApiCreatePostQuery['parameters']['query'],
   * ApiUpdateCommentQuery['parameters']['query'], etc.
   */
  typeQueryValue: string
  /**
   * The type name of the request body of the API endpoint,
   * such as ApiGetUsersRequestBody, ApiCreatePostRequestBody, ApiUpdateCommentRequestBody, etc.
   */
  typeRequestBody: string
  /**
   * The value of the type of the request body of the API endpoint, such as
   * ApiGetUsersRequestBody['requestBody']['content']['application/json'],
   * ApiCreatePostRequestBody['requestBody']['content']['application/json'],
   * ApiUpdateCommentRequestBody['requestBody']['content']['application/json'], etc.
   */
  typeRequestBodyValue: string
  /**
   * The type name of the response body of the API endpoint,
   * such as ApiGetUsersResponseBody, ApiCreatePostResponseBody, ApiUpdateCommentResponseBody, etc.
   */
  typeResponseBody: string
  /**
   * The value of the type of the response body of the API endpoint,
   * such as ApiGetUsersResponseBody['responses']['200']['content']['application/json'],
   * ApiCreatePostResponseBody['responses']['201']['content']['application/json'],
   * ApiUpdateCommentResponseBody['responses']['200']['content']['application/json'], etc.
   */
  typeResponseBodyValue: string
}
```

---
_Source: https://npm.io/package/api-farmer · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
