STC (Swagger Transform Code) is a tool for converting OpenApi/Swagger/Apifox into code.
🚧 Encapsulate the "shared" directory.
- 🐹 Support for Swagger 2/3(OpenApi) and Apifox.
- 📄 Support for JSON and YAML spec formats.
- 💡 Support plug-in development.
- 🤖 Support MCP Tools, generate an MCP-compatible tool catalog from OpenAPI.
- 🐣 Built-in transformation languages:
- TypeScript, almost equivalent to handwriting. Depends on
axios,wx.request,fetch.
xhr/ajax、ofetchplanned- JavaScript, from TypeScript to it.
- Dart, dependency on
dio. - Swift, type-safe async APIs backed by
Alamofire.
- TypeScript, almost equivalent to handwriting. Depends on
download by system:
- stc: Intel-based Mac
- stc-m: M-series Mac
- stc-linux:Linux
- stc-win.exe: Windows
1.Install the @lonu/stc npm package.
pnpm add @lonu/stc -D2.Open the project's package.json file and add the following command to scripts:
{
"scripts": {
"api": "stc --url=http://127.0.0.1:4523/export/openapi/2?version=3.1"
}
}~ character as the user's home directory.
stc --url=https://petstore3.swagger.io/api/v3/openapi.json --outDir=outAssume a project directory is:
.
├── src
│ └── apis # Copy the shared directory here.
│ └── shared
│ └── xxx.ts # Other files.
-
Find the directory of
outDir, copy the entireshareddirectory to the directory of theaxiosmodule you encapsulated. -
Open the
shared > axios > index.tsfile, copy therequestmethod, and add it to theaxiosmodule you encapsulated. If it is not encapsulated, copy theindex.tsfile as a new file to avoid the problem of modification being overwritten. -
Taking
Vueas an example, add the following code to themain.tsfile:
import { createApiClient } from './apis/shared/fetchRuntime';
createApiClient({
baseURL: 'https://api.xxx.com'
// onError(msg) {
// // 处理错误信息
// }
})STC's generated methods return Promise<T>, so they can be used directly as a
query function. Replace getPetById and its import path with a method from your
own generated API.
Install the adapter for your framework:
pnpm add @tanstack/vue-query # Vue
pnpm add @tanstack/react-query # ReactInitialize the generated API client once:
import { createApiClient } from './apis/shared/fetchRuntime';
createApiClient({ baseURL: 'https://api.xxx.com' });Vue uses VueQueryPlugin and a composable:
// main.ts
import { createApp } from 'vue';
import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query';
import App from './App.vue';
const app = createApp(App);
app.use(VueQueryPlugin, { queryClient: new QueryClient() });
app.mount('#app');
// usePet.ts
import { useQuery } from '@tanstack/vue-query';
import type { Ref } from 'vue';
import { getPetById } from '../apis/pet';
export const usePet = (petId: Ref<number>) => useQuery({
queryKey: ['pet', petId],
queryFn: () => getPetById(petId.value),
});React uses QueryClientProvider and a custom hook:
// main.tsx
import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';
const queryClient = new QueryClient();
createRoot(document.getElementById('root')!).render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>,
);
// usePet.ts
import { useQuery } from '@tanstack/react-query';
import { getPetById } from '../apis/pet';
export const usePet = (petId: number) => useQuery({
queryKey: ['pet', petId],
queryFn: () => getPetById(petId),
});-
Find the directory of
outDir, copy the entire directory ofsharedto the directory of thewechatmodule you encapsulated. -
Open the
shared > wechat > index.tsfile, copy therequestmethod, and add it to thewx.requestcode file you encapsulated. If it is not encapsulated, copy theindex.tsfile as a new file to avoid the problem of modification being overwritten. -
Add the following code to the
app.tsfile:
import { createApiClient } from './apis/shared/fetchRuntime';
// import Notify from './miniprogram_npm/@vant/weapp/notify/notify';
App<IAppOption>({
onLaunch() {
createApiClient({
baseURL: 'https://api.xxx.com,
onError(msg) {
// Notify({ type: 'danger', message: msg, selector: '#v-notify'})
}
})
}
});Add Alamofire to the app target, keep the generated shared/APIClientBase.swift
and shared/alamofire/APIClient.swift files in the same target as the generated
API files, then configure the client once during app startup:
import Alamofire
APIClient.shared.configure(
APICreateConfig(
baseURL: "https://api.example.com",
defaultHeaders: ["Accept": "application/json"],
onError: { message in
print(message)
},
onLogin: {
// Handle an HTTP 401 response.
}
)
)Generated methods use async throws, preserve path/query/header/body parameters,
and use APIFile for multipart uploads.
STC does not generate authentication code. For the axios client, inject a token into every request via onRequestInterceptor:
import { createApiClient } from './apis/shared/fetchRuntime';
createApiClient({
baseURL: 'https://api.xxx.com',
onRequestInterceptor(config) {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
},
onLogin() {
// Triggered when the response status is 401, e.g. redirect to the login page
}
})For the
fetchorconfigargument of each generated method instead, e.g.getPetById(petId, { headers: { Authorization: 'Bearer xxx' } }).
| Option | Alias | Type | Default | Description |
|---|---|---|---|---|
| url | string | Swagger/OpenApi/Apifox document address, or local path (JSON or YAML). | ||
| outDir | o | string | ./stc_out | Output Directory. |
| client | string | axios | http request client. When lang is ts/js, the possible values are: axios, wechat, fetch. |
|
| mcp | boolean | false | Generate an MCP tool catalog (mcp-tools.json). |
|
| lang | l | string | ts | Language, used for output file suffix. |
| tag | number | Specify the tag from the interface url. By default, the first tag is read for the file name. | ||
| filter | f | string[] | Filter interfaces. Interfaces that meet the filter conditions will be generated. Example: --filter "/pet*", generate an interface for /pet, and support multiple --filter. For more usage information, please refer to micromatch |
|
| conjunction | c | string | By | The method's connector, the default value is By. |
| actionIndex | number | -1 | The method name index, the default value is -1. |
|
| shared | boolean | true | Whether to generate the shared directory. [default: true]. | |
| clean | boolean | true | Whether to clean the output directory before generating. [default: true]. | |
| globalHeader | gh | string[] | Global header key configuration, multiple can be set. When a single API has the same key, it will not appear as a parameter. | |
| version | v | boolean | Output version information. | |
| help | h | boolean | Output help information. |
Use --mcp to generate mcp-tools.json. The file contains the standard MCP tool fields (name, description, inputSchema) and an x-stc-http extension with the original HTTP method and path, so an MCP server can expose the tools and connect them to a generic HTTP executor.
stc --url=./openapi.yaml --mcp --outDir=./generatedThe generated JSON is intentionally limited to tool discovery. Authentication, base URL selection, and HTTP execution remain in the MCP server/runtime that consumes the catalog.
For convenience, STC can not only develop plugins in Deno, but also provides @lonu/stc npm library, which can develop plugins in Node environment.
Create a myPlugin.ts file:
// 引用模块
import { start } from 'jsr:@lonu/stc@^2.17.1'
// Defining plugins
const myPlugin: IPlugin = {
name: 'stc:MyPlugin',
lang: 'ts',
setup(context: IPluginContext) {
// type map
return {
}
},
onTransform(def, action) {
// definition
const defContent: string = parserDefinition(
def
)
// action
const actionContent: Map<string, string> = parserAction(
action
)
return {
definition: {
filename: '_types.ts',
content: defContent,
},
action: actionContent // Here actionContent is of type Map<string, string>, key is the file name, value is the converted code.
}
},
onEnd() {
console.log('end')
}
}
// use plugin
start({
// ...other options
plugins: [myPlugin]
})-
Create a
myPlugin.tsfile. -
Add the
@lonu/stcreference and use thestartmethod:
import { start } from '@lonu/stc'- Implement the code that converts
definitionandactioninto the target language in the plugin'sonTransformhook function.
export const myPlugin: IPlugin = {
name: 'stc:MyPlugin',
lang: 'ts',
setup(context: IPluginContext) {
// type map
return {
}
},
onTransform(def, action) {
// definition
const defContent: string = parserDefinition(
def
)
// action
const actionContent: Map<string, string> = parserAction(
action
)
return {
definition: defContent,
action: actionContent
}
},
onEnd() {
console.log('end')
}
}4.In the start method, add plugins:
start({
// ...other options
plugins: [myPlugin]
})



