Swagger Codegen Bash 客户端生成器完整指南:从 Swagger 定义到零依赖 cURL 命令行工具

📅 发布时间:2026/9/21 16:01:36
Swagger Codegen Bash 客户端生成器完整指南:从 Swagger 定义到零依赖 cURL 命令行工具
开发工具代码生成API设计【免费下载链接】swagger-codegenswagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.项目地址https://gitcode.com/gh_mirrors/sw/swagger-codegen点击查看免费下载导读本文围绕 Swagger Codegen 内置的bash生成器代码实现见 BashClientCodegen.java完整讲解如何把一个 OpenAPI / Swagger 定义的 REST 服务自动生成一个独立的、单文件的 Bash 客户端脚本。你将掌握生成器全部 8 个自定义配置项的含义与用法、生成脚本的完整 CLI 语法参数传递、认证、--dry-run预览、Bash/Zsh 补全的安装方式以及这些行为背后的模板与源码实现原理最终能快速用 cURL 直接访问任意 Swagger 注解的 REST 服务。生成器概览一个脚本搞定 REST 服务测试bash生成器-l bash产生的不是一个完整的 SDK 工程而是一个独立的单文件 Bash 脚本客户端用于快速测试和访问 Swagger 注解的 REST 服务。生成脚本底层使用 cURL 发起真实 REST 调用因此整个客户端对外只有两个运行时依赖Bash 4.3cURL这也是它零依赖定位的来源无需安装任何语言运行时、无需编译、无需第三方库任何有 Bash 和 cURL 的环境服务器、CI、容器、macOS 终端都能直接运行。从源码看生成脚本在启动时会主动做 Bash 版本校验见 client.mustache低于 4.3 会直接报错退出if ! ( ((${BASH_VERSION:0:1} 4)) ((${BASH_VERSION:2:1} 3)) ) \ ! ((${BASH_VERSION:0:1} 5)); then echo Sorry - your Bash version is ${BASH_VERSION} echo You need at least Bash 4.3 to run this script. exit 1 fi从源码结构看BashClientCodegen的构造函数该生成器不生成任何 model 与 API 源文件modelTemplateFiles.clear()、apiTemplateFiles.clear()仅生成以下支撑文件{{scriptName}}——主客户端脚本由client.mustache渲染模板共 1069 行{{scriptName}}.bash-completion——Bash 补全脚本_{{scriptName}}——Zsh 补全脚本README.md与Dockerfile这些模板文件位于 modules/swagger-codegen/src/main/resources/bash/包括client.mustache、bash-completion.mustache、zsh-completion.mustache、README.mustache、Dockerfile.mustache、api_doc.mustache、model_doc.mustache。特性清单生成器官方特性如下全自动生成访问任意 Swagger 定义 REST 服务的客户端 Bash 脚本同时生成Bash 与 Zsh 补全脚本所有合法 cURL 选项都可以直接透传支持--dry-run选项预览每个操作将要执行的 cURL 命令提供服务整体以及每个操作完整的帮助信息除 Bash 和 cURL 外无任何外部依赖快速上手三步生成 Bash 客户端1. 获取源码并构建$ git clone https://github.com/swagger-api/swagger-codegen $ mvn packagemvn package会构建出 CLI 可执行 jarmodules/swagger-codegen-cli/target/swagger-codegen-cli.jar构建入口见 modules/swagger-codegen-cli/pom.xml。2. 准备自定义配置 JSON生成器支持通过 JSON 配置文件定制行为例如{ processMarkdown: true, curlOptions: -sS --tlsv1.2, scriptName: petstore-cli, generateBashCompletion: true, generateZshCompletion: true, hostEnvironmentVariable: PETSTORE_HOST, basicAuthEnvironmentVariable: PETSTORE_BASIC_AUTH, apiKeyAuthEnvironmentVariable: PETSTORE_API_KEY }这就是仓库测试资源中的真实样例 modules/swagger-codegen/src/test/resources/2_0/bash-config.json可直接复用。3. 生成并运行客户端$ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ -l bash \ -o generated/bash/petstore \ -c modules/swagger-codegen/src/test/resources/2_0/bash-config.json $ chmod x generated/bash/petstore/petstore-cli其中-i指定 Swagger 定义URL 或本地文件-l bash选择生成器-o指定输出目录-c指定上述配置 JSON。仓库中已生成好的完整样例见 samples/client/petstore/bash/其中包含petstore-cli主脚本、petstore-cli.bash-completion补全脚本、_petstore-cliZsh 补全文件、Dockerfile以及docs/下的 API/模型文档。生成后立即体验$ cd generated/bash/petstore $ ./petstore-cli -h Swagger Petstore command line client (API version 1.0.0) Usage petstore-cli [-h|--help] [-V|--version] [--about] [curl-options] [-ac|--accept mime-type] [-ct,--content-type mime-type] [--host url] [--dry-run] operation [-h|--help] [headers] [parameters] [body-parameters] - url - endpoint of the REST service without basepath Can also be specified in PETSTORE_HOST environment variable. - curl-options - any valid cURL options can be passed before operation - mime-type - either full mime-type or one of supported abbreviations: (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, rdf, jpg, png, gif, bmp, tiff) - headers - HTTP headers can be passed in the form HEADER:VALUE - parameters - REST operation parameters can be passed in the following forms: * KEYVALUE - path or query parameters - body-parameters - simple JSON body content (first level only) can be build using the following arguments: * KEYVALUE - body parameters which will be added to body JSON as { ..., KEY: VALUE, ... } * KEY:VALUE - body parameters which will be added to body JSON as { ..., KEY: VALUE, ... } Authentication methods - Api-key - add api_key:api-key after operation or export PETSTORE_API_KEYapi-key - OAuth2 (flow: implicit) Authorization URL: * http://petstore.swagger.io/oauth/dialog Scopes: * write:pets - modify pets in your account * read:pets - read your pets Operations (grouped by tags) [pet] addPet Add a new pet to the store deletePet Deletes a pet findPetsByStatus Finds Pets by status findPetsByTags Finds Pets by tags getPetById Find pet by ID updatePet Update an existing pet updatePetWithForm Updates a pet in the store with form data uploadFile uploads an image [store] deleteOrder Delete purchase order by ID getInventory Returns pet inventories by status getOrderById Find purchase order by ID placeOrder Place an order for a pet [user] createUser Create user createUsersWithArrayInput Creates list of users with given input array createUsersWithListInput Creates list of users with given input array deleteUser Delete user getUserByName Get user by user name loginUser Logs user into the system logoutUser Logs out current logged in user session updateUser Updated user Options -h,--help Print this help -V,--version Print API version --about Print the information about service --host url Specify the host URL (e.g. https://petstore.swagger.io) --force Force command invocation in spite of missing required parameters or wrong content type --dry-run Print out the cURL command without executing it -ac,--accept mime-type Set the Accept header in the request -ct,--content-type mime-type Set the Content-type header in the request生成器配置项全解客户端生成器bash生成器接受 8 个特定配置选项均在源码 BashClientCodegen.java 的构造函数中注册为 CLI 选项。可在 JSON 配置文件中通过-c选项传入。配置项类型默认值说明processMarkdownbooleanfalse设为true时Swagger 规范中的所有文本描述会被当作 Markdown 处理并转换为终端格式化命令curlOptionsstring无默认 cURL 选项列表会被附加到每条请求命令中scriptNamestringclient.sh目标脚本名称构建 Bash 补全脚本时必需generateBashCompletionbooleanfalse设为true时生成 Bash 补全脚本generateZshCompletionbooleanfalse设为true时生成 Zsh 补全脚本hostEnvironmentVariablestring无用于搜索默认 host 的环境变量名如PETSTORE_HOSThttp://petstore.swagger.io:8080basicAuthEnvironmentVariablestring无用于搜索默认 Basic Auth 凭据的环境变量名如PETSTORE_CREDSusername:passwordapiKeyAuthEnvironmentVariablestring无用于搜索默认 API key 的环境变量名如PETSTORE_APIKEYkjhasdGASDa5asdASD这些配置在源码中如何生效processOpts()BashClientCodegen.java负责把配置值写入additionalProperties进而以x-codegen-*前缀注入 Mustache 模板变量curlOptions→x-codegen-curl-options模板中作为curl_arguments{{x-codegen-curl-options}}的默认值见 client.mustachescriptName→x-codegen-script-name同时决定SupportingFile的输出文件名主脚本{{scriptName}}、补全{{scriptName}}.bash-completion、Zsh 补全_{{scriptName}}hostEnvironmentVariable→x-codegen-host-env模板渲染为host{{x-codegen-host-env}}即$PETSTORE_HOSTbasicAuthEnvironmentVariable→x-codegen-basicauth-env渲染为basic_auth_credential$PETSTORE_BASIC_AUTHapiKeyAuthEnvironmentVariable→x-codegen-apikey-env渲染为apikey_auth_credential$PETSTORE_API_KEY注意processOpts()中还无条件添加了 5 个支撑文件主脚本、Bash/Zsh 补全、README、Dockerfile。这意味着即使generateBashCompletion为false补全模板仍会被写出但只有开启对应开关时补全脚本内容才会被完整填充README 原文标注necessary when building Bash completion script即指scriptName是补全脚本命名的前提。另外apiKeyAuthEnvironmentVariable在源码中注册时使用的是CliOption.newBoolean(...)BashClientCodegen.java而配置示例中传入的是字符串环境变量名——从使用惯例与模板渲染来看其实际语义是环境变量名字符串这一点以模板与示例配置为准。使用生成的 Bash 脚本查询帮助与服务信息# 打印服务上可用的操作列表 $ petstore-cli --help # 打印服务描述 $ petstore-cli --about # 打印某个具体操作的详细信息 $ petstore-cli addPet --help调用 REST API 操作# 通过 stdin 传入 JSON body 调用 addPet $ echo {id:891,name:lucky,status:available} | petstore-cli --host http://petstore.swagger.io --content-type json addPet - {id:891,name:lucky,photoUrls:[],tags:[],status:available} # 上面的调用等价于直接用命令行参数构建 body $ petstore-cli --host http://petstore.swagger.io --content-type json --accept xml addPet id:891 namelucky statusavailable xml version1.0 encodingUTF-8 standaloneyes?Petid891/idnamelucky/namephotoUrls/statusavailable/statustags//Pet用 --dry-run 预览 cURL 命令# 预览 cURL 命令而不真正执行 $ petstore-cli --host http://petstore.swagger.io --content-type json --dry-run addPet id:891 namelucky statusavailable curl -sS --tlsv1.2 -H Content-type: application/json -X POST -d {name: lucky, status: available, id: 891} http://petstore.swagger.io/v2/pet注意这里curl -sS --tlsv1.2正是配置文件中curlOptions注入的结果-H Content-type: application/json来自-ct json的 MIME 缩写展开-d {name: lucky, status: available, id: 891}则展示了 body 参数的两种语法namelucky生成 JSON 字符串值id:891生成 JSON 数值。参数传递深入三种语法与底层实现生成的脚本把参数分为三类对应模板中三个关联数组见 client.mustache 与body_parameters数组KEYVALUE——路径参数path或查询参数queryKEYVALUE——body 参数加入 JSON 为字符串{ ..., KEY: VALUE, ... }KEY:VALUE——body 参数加入 JSON 为原始值{ ..., KEY: VALUE, ... }用于数值、布尔、嵌套对象等非字符串场景body 参数的实际拼接逻辑在body_parameters_to_json()client.mustache中遍历关联数组将KEY: VALUE以逗号连接成-d {...}形式——这也解释了为什么 README 标注简单 JSON body 内容仅第一层。查询与路径参数的处理集中在build_request_path()client.mustache核心行为包括参数个数校验根据模板预生成的operation_parameters_minimum_occurrences/operation_parameters_maximum_occurrences数组检查过少与过多的值--force可跳过此校验但路径参数仍强制要求。路径参数替换通过正则(.*)(\{pparam\})(.*)把模板路径中的{param}替换为实际值。集合类型序列化由operation_parameters_collection_type数组驱动支持multia1a2、csva1,2、ssva1 2、tsva1\t2。这些标记来自 BashClientCodegen.java 的fromParameter()——它把 Swagger 参数上的collectionFormat映射为对应的x-codegen-collection-*vendor 扩展并注明multi仅对 query 参数有效。URL 转义url_escape()client.mustache用sed把空格、!、、#、、?、:、(、)、Tab 等转义为百分号编码保证查询参数安全。仓库测试 samples/client/petstore/bash/tests/petstore_test.sh 覆盖了上述行为statusavailable statusgone test应生成statusavailable,gone%20test空格转义 csv 拼接tagsTAG1 tagsTAG2应生成tagsTAG1,TAG2缺参数时应输出Error: Too few values。MIME 类型缩写-ac/--accept与-ct/--content-type既可以传完整 MIME 类型如userdefined/custom也可以用内置缩写定义在模板的mime_type_abbreviations数组见 client.mustache缩写MIME 类型缩写MIME 类型texttext/plainyamlapplication/yamlhtmltext/htmljsapplication/javascriptmdtext/x-markdownbinapplication/octet-streamcsvtext/csvrdfapplication/rdfxmlcsstext/cssjpgimage/jpegrtftext/rtfpngimage/pngjsonapplication/jsongifimage/gifxmlapplication/xmlbmpimage/bmp——tiffimage/tifflookup_mime_type()client.mustache实现查找命中缩写则展开否则按完整 MIME 类型原样使用。测试addPet abbreviated content type与addPet unabbreviated content type分别验证了这两种路径。认证支持Api-key、Basic Auth 与 OAuth2生成的脚本按 Swagger 定义中的securityDefinitions自动输出认证帮助信息如 README 示例中的 Api-key 与 OAuth2 implicit 流程、授权 URL 和 scope 列表。实际运行时支持以下方式Api-keyheader在操作后追加api_key:api-key或export PETSTORE_API_KEYapi-key。模板逻辑client.mustache会先收集HEADER:VALUE形式的显式 header若其中未包含 api_key 且环境变量已设置则自动补上-H api_key: key测试findPetsByStatus api key验证-H api_key: 1234的生成findPetsByStatus empty api key验证未设置 key 时不输出该 header。Api-keyquery查询参数中的 api_key 若未显式提供可从apiKeyAuthEnvironmentVariable指定的环境变量取值见 client.mustache。Basic Auth支持-u user:pass透传或环境变量注入测试findPetsByStatus basic auth验证-u alice:secret出现在生成的 cURL 命令中。OAuth2生成器在帮助中列出授权 URL 与 scopes实际令牌可结合--host、header 或 cURL 透传方式使用。Shell 补全Bash 与 ZshBash生成的 bash-completion 脚本可以直接加载到当前 Bash 会话source output/petstore-cli.bash-completion也可以系统级安装到/etc/bash-completion.dmacOS Homebrew 为/usr/local/etc/bash-completion.dsudo cp output/petstore-cli.bash-completion /etc/bash-completion.d/petstore-cli生成脚本自带的注释还提供了用户级安装方式在~/.bash_profile中添加[ -r ~/petstore-cli.bash-completion ] source ~/petstore-cli.bash-completion。补全脚本内部同样内置了 MIME 缩写表并对 macOSDarwin做了__osx_init_completion兼容处理见 samples/client/petstore/bash/petstore-cli.bash-completion。macOS 额外配置macOS 可能需要先用 Homebrew 安装 bash-completionbrew install bash-completion并在~/.bashrc中添加if [ -f $(brew --prefix)/etc/bash_completion ]; then . $(brew --prefix)/etc/bash_completion fiZsh在 Zsh 中生成的_{{scriptName}}文件如_petstore-cli必须复制到$fpath变量所列的某个目录下之后 Zsh 会在补全时自动加载它。源码级深度解析类型映射与 Bash 原生类型BashClientCodegen构造函数中定义了 Swagger 类型到 Bash 语义类型的映射BashClientCodegen.javaint/long/short/number → integer、float/double → float、date/DateTime/UUID/ByteArray/char → string、object → map、array/List → array等。同时声明了语言原生类型集合array、map、boolean、integer、float、string、binary这些类型不会触发 import。getTypeDeclaration()L365-L377对数组生成array[ItemType]、对映射生成map[String, ValueType]的声明形式。保留字转义与安全处理Bash 保留字case、do、done、for、function、if、in、select、then、time、until、while等在reservedWords集合中列出命中时通过escapeReservedWord()加下划线前缀转义。escapeText()L482-L563统一处理文本trim、反斜杠与引号转义若processMarkdown开启还会做一系列正则替换——**Bold**/__Bold__→$(tput bold)...$(tput sgr0)*Italic*/_Italic_→$(tput dim)...$(tput sgr0)#/##/###标题 → 加粗 setaf 7白色代码块 →---分隔线。这就是processMarkdown配置项在终端格式化层面的具体实现。escapeUnsafeCharacters()把反引号替换为单引号、escapeQuotationMark()转义单引号防止代码注入。操作级扩展与 body 示例fromOperation()L589-L667支持三个 vendor 扩展x-bash-codegen-description为操作提供 Bash 专属帮助描述经escapeText处理x-code-samples规范中的 Shell 语言代码样例会被提取为x-bash-codegen-sample供模板展示body 参数当操作consumes包含application/json且模型带example时会用 Jackson 的 pretty printer 重排为x-codegen-body-example。preprocessSwagger()L674-L699则把 basePath 为/的规范规范化为空串并支持通过 info 级x-bash-codegen-description扩展注入应用描述--about输出内容来源。测试验证与可复现样例仓库为 bash 生成器提供了可复现的测试资产生成配置modules/swagger-codegen/src/test/resources/2_0/bash-config.json已生成产物samples/client/petstore/bash/含petstore-cli、补全脚本、Dockerfile、docs/文档Bats 集成测试samples/client/petstore/bash/tests/petstore_test.sh共 121 行使用 Bats 框架覆盖bash -n语法检查、缺失 host / content-type 的错误提示、缩写与完整 MIME 类型、非法操作名、Basic Auth 与 Api-key 注入、默认 cURL 参数、参数个数校验、空格转义、csv 集合拼接等关键行为已知限制与 TODOREADME 中列出了生成器当前已知的 TODO 项这也是使用前需要了解的能力边界参数补全暂不支持枚举值enum values尚未封装服务返回错误的处理基于 Swagger 规范中定义的注释--help与--about的格式化有待改进暂不支持 Bash 4.0-4.2当前要求 4.3尚未生成 manpage尚未支持 form dataform 表单参数TODO 后续将迁移到 GitHub issues说明form data与 manpage 等能力在当前仓库版本中仍未实现实际使用时应避免依赖这些特性如需表单类操作可结合--dry-run与 cURL 选项透传自行构造请求。总结bash生成器把Swagger 定义 → 可用的 REST 客户端的距离压缩到一条java -jar ... generate命令。生成的单文件脚本既适合在开发调试、CI 冒烟测试中快速调用接口也能借助--dry-run把每个操作翻译成标准 cURL 命令供其他工具复用。配合 8 个配置项curlOptions、scriptName、环境变量注入、补全开关、Markdown 终端渲染与 Bash/Zsh 补全它是一套轻量而完整的 REST 服务命令行访问方案——全部能力仅依赖 Bash 4.3 与 cURL。赞分享开发工具代码生成API设计【免费下载链接】swagger-codegenswagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.项目地址https://gitcode.com/gh_mirrors/sw/swagger-codegen点击查看免费下载相关推荐swagger-codegen 生成的 Bash REST 客户端实战指南以 Swagger Petstore Bash Client 为例swagger codegen 生成的 Bash REST 客户端实战指南以 Swagger Petstore Bash Client 为例 本指南围绕 sw开发工具代码生成API设计swagger-codegen 生成的 Bash 客户端中的 Pet 模型从数据定义到 CLI 实战swagger codegen 生成的 Bash 客户端中的 Pet 模型从数据定义到 CLI 实战 本文以 swagger codegen 生成的 Bash开发工具代码生成API设计基于 swagger-codegen 生成 Android Volley 客户端swagger-petstore-android-volley 完整使用指南基于 swagger codegen 生成 Android Volley 客户端swagger petstore android volley 完整使用指南开发工具代码生成API设计上一篇fontmin字体大小优化极限从10MB到100KB的压缩案例下一篇终极指南remotely-save错误处理机制如何优雅应对云服务故障创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考