Swagger Codegen (Code Generation)
Swagger is a set of open-source tools built around the OpenAPI specification (formerly known as the Swagger specification) for designing, building, documenting, and consuming RESTful web services.
Swagger mainly includes:
- Swagger Editor: A browser-based editor for writing OpenAPI specifications
- Swagger UI: A visual API documentation interface that allows developers to explore APIs interactively
- Swagger Codegen: Automatically generate client code and server stubs from the OpenAPI specification
The OpenAPI specification is a language-agnostic definition format used to describe RESTful APIs.
OpenAPI allows humans and computers to discover and understand the capabilities of a service without accessing source code or additional documentation.
Swagger Codegen (Code Generation)
Environment Preparation
Before you begin, make sure the following are installed in your system:
- Java 8+
- Maven (for Java projects)
- Git (for obtaining source code)
Install Swagger Codegen:
# 方法1: 使用homebrew (macOS)
brew install swagger-codegen
# Method 2: Download JAR file from GitHub
wget https://repo1.maven.org/maven2/io/swagger/codegen/v3/swagger-codegen-cli/3.0.36/swagger-codegen-cli-3.0.36.jar -O swagger-codegen-cli.jar
java -jar swagger-codegen-cli.jar help
Generate client SDKs
Java Client Generation
Generate a Java client using the Petstore API as an example:
# Using command-line tools
swagger-codegen generate -i https://petstore.swagger.io/v2/swagger.json -l java -o ./java-client
# or use JAR file
java -jar swagger-codegen-cli.jar generate \
-i https://petstore.swagger.io/v2/swagger.json \
-l java \
-o ./java-client
Generated client SDK structure:
java-client/
├── pom.xml # Maven项目文件
├── README.md # 说明文档
├── src/
│ ├── main/
│ │ ├── java/ # 生成的Java代码
│ │ └── resources/ # 配置文件
│ └── test/ # 测试代码
└── .gitignore
Using the generated Java client:
Example
import
io.swagger.client.*
;
import
io.swagger.client.auth.*
;
import
io.swagger.client.model.*
;
import
io.swagger.client.api.PetApi
;
public
class
Example
{
public
static
void
main
(
String
[
]
args
)
{
ApiClient defaultClient
=
Configuration.
getDefaultApiClient
(
)
;
// Configure API key authorization
ApiKeyAuth apiKey
=
(
ApiKeyAuth
)
defaultClient.
getAuthentication
(
"api_key"
)
;
apiKey.
setApiKey
(
"YOUR API KEY"
)
;
PetApi apiInstance
=
new
PetApi
(
)
;
try
{
Pet result
=
apiInstance.
getPetById
(
789L
)
;
System
.
out
.
println
(
result
)
;
}
catch
(
ApiException e
)
{
System
.
err
.
println
(
"Exception when calling PetApi#getPetById"
)
;
e.
printStackTrace
(
)
;
}
}
}
Python Client Generation
Generate Python client:
swagger-codegen generate -i https://petstore.swagger.io/v2/swagger.json -l python -o ./python-client
Python client usage example:
Example
import
swagger_client
from
swagger_client.
rest
import
ApiException
Create API client instance
api_instance
=
swagger_client.
PetApi
(
)
api_client
=
api_instance.
api_client
Set API key
api_client.
configuration
.
api_key
[
'api_key'
]
=
'YOUR_API_KEY'
try
:
Get pet by specified ID
pet
=
api_instance.
get_pet_by_id
(
pet_id
=
789
)
(
pet
)
except
ApiException
as
e:
(
"Exception when calling PetApi->get_pet_by_id: %s\n"
% e
)
Other Language Support
Swagger Codegen supports multiple languages and frameworks, including but not limited to:
- JavaScript/TypeScript (Node.js, Angular, React, etc.)
- Ruby
- PHP
- C#/.NET
- Go
- Swift
- Kotlin
- Scala
View the list of supported languages:
swagger-codegen langs
Generate Server Stub Code
Spring Server Code Generation
Generate Spring Boot server stub:
swagger-codegen generate \
-i https://petstore.swagger.io/v2/swagger.json \
-l spring \
-o ./spring-server
Generated Spring server code structure:
spring-server/
├── pom.xml # Maven项目文件
├── README.md # 说明文档
├── src/
│ ├── main/
│ │ ├── java/ # 控制器接口和模型类
│ │ └── resources/ # 配置文件和静态资源
│ └── test/ # 测试代码
└── .gitignore
Implement the generated controller interface:
Example
@Controller
public
class
PetApiController
implements
PetApi
{
@Override
public
ResponseEntity
<
Pet
getPetById
(
Long
petId
)
{// Implement API logic
Pet pet
=
new
Pet
(
)
;
pet.
setId
(
petId
)
;
pet.
setName
(
"Example pet"
)
;
pet.
setStatus
(
Pet.
StatusEnum
.
AVAILABLE
)
;
return
ResponseEntity.
ok
(
pet
)
;
}
}
Node.js Server Code Generation
Generate Node.js server code:
swagger-codegen generate \
-i https://petstore.swagger.io/v2/swagger.json \
-l nodejs-server \
-o ./nodejs-server
Node.js server usage example:
Example
// Implement business logic in the generated service file
module.
exports
.
getPetById
=
function
(
petId
)
{
return
new
Promise
(
function
(
resolve
,
reject
)
{
var
examples
=
{
}
;
examples
[
'application/json'
]
=
{
"id"
:
petId
,
"name"
:
"Example pet"
,
"status"
:
"available"
}
;
resolve
(
examples
[
Object
.
keys
(
examples
)
[
0
]
]
)
;
}
)
;
}
Advanced OpenAPI Generator
OpenAPI Generator vs Swagger Codegen
OpenAPI Generator is a fork of Swagger Codegen that began independent development in 2018. Its main advantages include:
- More active community maintenance
- Broader template support
- Better OpenAPI 3.0 support
- More configuration options and customization capabilities
Install OpenAPI Generator:
# 使用npm安装
npm install @openapitools/openapi-generator-cli -g
# Install using Homebrew
brew install openapi-generator
# Download JAR file
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.0.1/openapi-generator-cli-6.0.1.jar -O openapi-generator-cli.jar
Installation and Basic Usage
Basic usage method:
# Show help information
openapi-generator help
# Generate Java client
openapi-generator generate \
-i https://petstore.swagger.io/v2/swagger.json \
-g java \
-o ./java-client
# List supported generators
openapi-generator list
Custom Templates
Template Basics
OpenAPI Generator uses the Mustache template engine. To customize the generated code, you need to:
- Obtain the default templates
- Modify the templates to meet your needs
- Generate code using custom templates
Create a custom template<
# 使用JAR文件获取特定语言的模板
java -jar openapi-generator-cli.jar author template
-g java
-o ./custom-templates/java
Template file example (Java's api.mustache):
{{>licenseInfo}}
package {{package}};
{{#imports}}import {{import}};
{{/imports}}
{{#operations}}
public interface {{classname}} {
{{#operation}}
{{#summary}}
/**
* {{summary}}
* {{/summary}}
{{#notes}}
* {{notes}}
{{/notes}}
*/
{{#returnType}}{{returnType}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{dataType}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
{{/operation}}
}
{{/operations}}
Apply templates to generate code
Generate code using custom templates:
openapi-generator generate \
-i https://petstore.swagger.io/v2/swagger.json \
-g java \
-o ./java-client-custom \
-t ./custom-templates/java
Custom Configuration
Global Configuration Options
OpenAPI Generator supports various global configuration options:
openapi-generator generate \
-i spec.yaml \
-g java \
-o output \
--api-package com.example.api \
--model-package com.example.model \
--package-name com.example \
--git-repo-id my-repo \
--git-user-id my-username
Language-Specific Configuration
Different generators have their own specific configuration options:
# Java客户端生成器的特定选项
openapi-generator generate \
-i spec.yaml \
-g java \
-o output \
--library retrofit2 \
--java8 true \
--use-rx-java true
Using Configuration Files
You can create a configuration file to save commonly used settings:
config.json file
{
"artifactId"
:
"petstore-client"
,
"groupId"
:
"com.example"
,
"library"
:
"retrofit2"
,
"apiPackage"
:
"com.example.api"
,
"modelPackage"
:
"com.example.model"
,
"invokerPackage"
:
"com.example.client"
,
"dateLibrary"
:
"java8"
,
"java8"
:
true
}
Using the configuration file:
openapi-generator generate \
-i spec.yaml \
-g java \
-o output \
-c config.json
Practical Project Case Study
API Design from Scratch
Design an API using Swagger Editor:
- Access the https://editor.swagger.io/
- Create an OpenAPI specification file:
Example
openapi
:
3.0.0
info
:
title
:
Product Management API
version
:
1.0.0
description
:
A RESTful API for managing products
servers
:
url
:
https
:
//api.example.com/v1
paths
:
/
products
:
get
:
summary
:
Get product list
responses
:
'200'
:
description
:
Success
content
:
application
/
json
:
schema
:
type
:
array
items
:
$ref
:
'#/components/schemas/Product'
post
:
summary
:
Create new product
requestBody
:
content
:
application
/
json
:
schema
:
$ref
:
'#/components/schemas/ProductInput'
responses
:
'201'
:
description
:
Creation successful
content
:
application
/
json
:
schema
:
$ref
:
'#/components/schemas/Product'
/
products
/
{
productId
}
:
get
:
summary
:
Get a single product
parameters
:
name
:
productId
in
:
path
required
:
true
schema
:
type
:
string
responses
:
'200'
:
description
:
Success
content
:
application
/
json
:
schema
:
$ref
:
'#/components/schemas/Product'
components
:
schemas
:
Product
:
type
:
object
properties
:
id
:
type
:
string
name
:
type
:
string
price
:
type
:
number
category
:
type
:
string
createdAt
:
type
:
string
format
:
date
time
ProductInput
:
type
:
object
required
:
name
price
properties
:
name
:
type
:
string
price
:
type
:
number
category
:
type
:
string
Complete Project Code Generation
Generate a complete project from the designed API specification:
- Save the API specification as
product-api.yaml - Generate frontend and backend code:
# 生成Spring Boot服务端
openapi-generator generate \
-i product-api.yaml \
-g spring \
-o ./product-service \
--additional-properties=java8=true,dateLibrary=java8
# Generate React frontend
openapi-generator generate \
-i product-api.yaml \
-g typescript-fetch \
-o ./product-frontend \
--additional-properties=supportsES6=true,npmName=product-api-client
Common Problems and Solutions
-
The generated code cannot be compiled
-
Custom templates not taking effect
-
The generated code is missing certain features
-
The generated code is incompatible with the existing project
Advanced Features and Best Practices
Version Management
Best practices for managing API versions:
- Specify the version number explicitly in the OpenAPI specification
- Use semantic versioning (SemVer)
- Use different base paths for different API versions
- Save specification files for all versions
CI/CD Integration
Integrate code generation into the CI/CD pipeline:
Example
GitHub Actions workflow example
name
:
Generate API Client
on
:
push
:
paths
:
'api-specs/**'
jobs
:
generate
:
runs
on
:
ubuntu
latest
steps
:
uses
:
actions
/
checkout
@
v2
name
:
Set up JDK
uses
:
actions
/
setup
java
@
v2
with
:
java
version
:
'11'
name
:
Install OpenAPI Generator
run
:
npm install
@
openapitools
/
openapi
generator
cli
g
name
:
Generate Client
run
:
|
openapi
generator generate \
i api
specs
/
product
api.
yaml
\
g typescript
fetch \
o .
/
generated
client
name
:
Commit and Push
run
:
|
git config
--
global user.
name
'GitHub Actions'
git config
--
global user.
'actions@github.com'
git add .
/
generated
client
git commit
m
"Auto-generate API client"
git push
Enterprise Application Recommendations
For enterprise-level projects:
-
Centralize API specification management
-
Establish style guidelines for generated code
-
Mix generated code and hand-written code
-
Consider a microservices architecture