如何通过JSON生成设置移除OpenAPI规范中新增的servers元素?
servers Element from OpenAPI Specs Absolutely! You can control whether the servers node is included in your generated OpenAPI JSON structure—here are the most common approaches based on the tooling you're using:
1. Using OpenAPI Generator (Most Common Tool)
OpenAPI Generator has a built-in configuration flag to skip generating the servers section entirely:
- CLI Command: Add the
--global-property skipServers=trueparameter when running the generator:openapi-generator generate -i your-source-spec.yaml -g [your-target-generator] --global-property skipServers=true - Configuration File: Create a
config.jsonfile with the setting, then reference it with the-cflag:
Run the generator with:{ "skipServers": true }openapi-generator generate -i your-source-spec.yaml -g [your-target-generator] -c config.json
2. Using Swagger Codegen
If you're using Swagger Codegen, it supports a similar flag to exclude servers:
- Use the
--skip-serversparameter in your CLI command:swagger-codegen generate -i your-source-spec.json -g [your-target-generator] --skip-servers
3. Custom Generation Logic (If You're Building the Spec Yourself)
If you're writing custom code to assemble the OpenAPI JSON:
- Simply omit the
serverskey entirely when constructing the spec object. For example in JavaScript:const finalSpec = { openapi: "3.0.1", info: { title: "Dummy API", version: "v1" }, paths: {/* Your path definitions */} // No servers property added = no servers node in output }; - If you're starting from a spec that already includes
servers, explicitly delete the key before outputting:delete existingSpec.servers;
4. Post-Processing with a Script
If your generator doesn't have a built-in flag, you can clean up the generated spec after creation using a tool like jq (for JSON manipulation):
jq 'del(.servers)' generated-spec.json > cleaned-spec.json
All these methods will give you the exact spec structure you want: {"openapi": "3.0.1", "info": {"title": "Dummy API", "version": "v1"}, "paths": {...}} without the servers node.
内容的提问来源于stack exchange,提问作者Christobal25

