Recently, I tried several libraries for generating SDKs based on OpenAPI metadata, such as autorest, the official swagger-codegen-cli, and @hey-api/openapi-ts, which I ultimately chose. Below, I document the process and the reasons for my choice.

SDK Auto-Generation

Why is automatic generation necessary? Generally speaking, the backend will write corresponding swagger documentation for its APIs, construct the relevant metadata, and then feed it to swagger ui to generate a frontend webpage that is usable and testable. In fact, based on this metadata, one can generate SDKs for various languages. This is made possible by the standardization of APIs, with OpenAPI being the primary driver of this standardization process. Can the SDK generation process also include relevant basic validation? If so, basic frontend validation functionality could be introduced into the SDK at no extra cost, significantly reducing common 400 errors, especially those related to data format. Of course, this is an ideal scenario. In reality, most current SDK or code generation tools do not automatically generate parameter validation. I personally feel this is due to a lack of standardization in this area, and the fact that there are too many choices for validation libraries, meaning teams do not necessarily share the same standards. For these reasons, when automatically generating an SDK or code, for the backend building the APIs, it only requires designing the relevant types for the input and return results. If one is more thorough, adding corresponding documentation comments and refining the examples is beneficial. At this point, most mainstream frameworks can generate the corresponding OpenAPI metadata. Based on this metadata, the generation of the relevant SDK or code can be completed. This is not only useful for the frontend but also for backend cross-service calls. However, most inter-service calls are not http but likely use grpc or similar protocols. Furthermore, during the API development process, one only needs to focus on the functional details of the API. The input/output specifications rarely change, and even if they do, the cost of regenerating is likely very low, especially when integrated into a related build pipeline, which makes things even more convenient. For the frontend, there is no need to write service requests one by one; in many cases, even common request classes may not need to be written. This is one aspect, but more importantly, it enables type reuse. The DTOs in the generated SDK or code often correspond exactly to the frontend's artifact types. Used properly, this can indeed save the frontend a lot of time and improve overall efficiency. As an aside, this way of interacting between frontend and backend places slightly higher demands on the backend's API construction. Especially for some backend programmers, they may not clearly define what input leads to what output, they do not validate types, they fail to provide necessary prompts, and they do not return necessary information. I will discuss this in more detail another time.

@hey-api/openapi-ts

Why not use autorest? This package is quite good, but it can be difficult to configure. It can generate code directly from metadata, and the generated output is essentially one step away from being ready for publication. If publishing an npm package, the CI/CD pipeline typically only needs to run npm publish with the appropriate token to complete the release. The code generated by this package can be difficult to use, partly because its design is heavily oriented toward the azure cloud environment.

The code generated by swagger-codegen-cli is relatively concise, but it can have issues when invoked, especially in frontend applications. Some dependencies may be missing, resulting in undefined values. It relies on the Node.js url package, which the author may not have intended for browser environments, or the package may simply be outdated due to a lack of recent updates.

@hey-api/openapi-ts is the successor to openapi-typescript-codegen. The latter was used by the author in a .net web api project to generate a corresponding SDK for frontend consumption, with excellent expected results. The user experience of @hey-api/openapi-ts is largely similar. Below are the relevant configuration and usage steps.

Usage Process

The environment is nestjs, the frontend is vue, and the CI environment is github action

  • openapi metadata retrieval

In practice, this starts a service in the pipeline and then requests the relevant metadata. Currently, there is no good build method. Theoretically, it can be built directly without starting a service. During the build process, there is an important plugin configuration.

  • nest-cli.json
"compilerOptions": {
    "plugins": [
      {
        "name": "@nestjs/swagger",
        "options": {
          // 这里使用是主要的类型 dto(视图) entity(领域实体) schema(存储实体)
          "dtoFileNameSuffix": [".dto.ts", ".entity.ts", ".schema.ts"],
          "classValidatorShim": true,
          "introspectComments": true
        }
      }
    ],
  • package.json
pnpm add @hey-api/openapi-ts -D
"gen:openapi-ts": "npx @hey-api/openapi-ts -i /tmp/openapi/swagger-spec.json -o /tmp/openapi/sdk -c @hey-api/client-fetch",
  • Related pipeline (added relevant comments to help readers quickly scan through)
name: Generate and Push SDK

# 只有打 tag 才触发
on:
  push:
    # branches:
    #   - openapi
    tags:
      - 'v*'

jobs:
  build-and-publish:
    runs-on: ubuntu-latest

    # 该仓库代码 Checkout
    steps:
    - name: Checkout code
      uses: actions/checkout@v2

    # node 20 环境
    - name: Use Node.js
      uses: actions/setup-node@v2
      with:
        node-version: '20'
        registry-url: 'https://registry.npmjs.org'

    # 依赖安装及启动服务(为了获取服务的 openapi 元数据)
    - name: Install dependencies and start server
      run: |
        npm i
        cp config.example.yml config.yml
        npm run start &
        sleep 10
    
    # 获取元数据并保存到指定位置
    - name: Download swagger.json
      run: |
        mkdir -p /tmp/openapi
        curl http://localhost:3000/api-json > /tmp/openapi/swagger-spec.json
    
    # 调用脚本生成 sdk 代码
    - name: Generate SDK
      run: |
        npm run gen:openapi-ts

    # 这里不使用 npm 包的方式发布, 而是使用子仓库, 带着 token Checkout 目标仓库
    - name: Checkout target repository
      uses: actions/checkout@v2
      with:
        repository: 'wedreamer/lims-server-openapi'
        token: ${{ secrets.LIMS_SERVER_OPENAPI_GITHUB_TOKEN }}

    # 删除上次代码, 这个仓库的所有代码, 除了本地的 .git, 完全使用生成的 sdk 代码
    - name: Copy SDK to target repository
      run: |
        find . -not -name .git -not -path './.git/*' -delete
        cp -r /tmp/openapi/sdk/* ./

    # push 到子仓库
    - name: Push SDK to target repository
      run: |
        git config --global user.email "[email protected]"
        git config --global user.name "shubuzuo"
        cd .
        git add .
        git commit -m "Update SDK"
        git push
      env:
        GIT_TOKEN: ${{ secrets.LIMS_SERVER_OPENAPI_GITHUB_TOKEN }}
  • Frontend vue
# 因为生成包时选择了基于该包的方式, 所以需要该包进行配置, 建议使用这个包, 生成时 -c @hey-api/client-fetch
pnpm add @hey-api/client-fetch

Wrap client.ts in a class

import { createClient } from '@hey-api/client-fetch'

const getToken = () => `Bearer ${localStorage.getItem('token') ?? ''}`

const openapi = createClient({
  baseUrl: 'http://localhost:3000',
  headers: {
    Authorization: getToken()
  }
})

openapi.interceptors.request.use((request, options) => {
  // 登录之后 token 拦截器中附带
  request.headers.set('Authorization', getToken())
  return request
})

openapi.interceptors.response.eject((res, req, options) => {
  // 集中错误处理
  // TODO: options 中允许设置不进行错误处理, 直接给到程序逻辑进行处理
  return res
})

export default openapi
  • Used in store
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { authGetProfile, authLogin, type loginDto, type loginResDto, type User } from '@/openapi'
import openapi from '@/client'

export const useUserStore = defineStore('user', () => {
  const current = ref<User | null>(null)

  const getCurrent = async () => {
    const { data: me, error } = await authGetProfile({ client: openapi })
    if (!error) {
      current.value = me!
    }
  }

  const login = async (dto: loginDto): Promise<loginResDto | null> => {
    const { data, error } = await authLogin({ client: openapi, body: dto })
    if (!error) {
      const { access_token: accessToken = '' } = data as loginResDto
      localStorage.setItem('token', accessToken)
      await getCurrent()
      return data!
    }
    return null
  }

  const logout = () => {
    current.value = null
    localStorage.setItem('token', '')
    // TODO: req to cancel token
  }

  return { current, getCurrent, login, logout }
})

The basic user experience is quite elegant