Swagger Codegen (Code Generation)
Swagger is a set of open-source tools built around the OpenAPI Specification (formerly known as the Swagger Specification), used for designing, building, documenting, and consuming RESTful Web services.
Swagger mainly includes:
- Swagger Editor: A browser-based editor that allows you to write OpenAPI specifications
- Swagger UI: A visual API documentation interface that allows developers to interactively explore APIs
- Swagger Codegen: Automatically generates client code and server stubs based on the OpenAPI specification
The OpenAPI Specification is a language-independent definition format used to describe RESTful APIs.
OpenAPI allows both humans and computers to discover and understand the capabilities of a service without requiring access to source code or additional documentation.
Swagger Codegen (Code Generation)
Environment Preparation
Before you begin, make sure the following are installed on your system:
- Java 8+
- Maven (for Java projects)
- Git (for obtaining source code)
Install Swagger Codegen:
# 方法1: 使用homebrew (macOS) brew install swagger-codegen # 方法2: 从GitHub下载JAR文件 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 SDK
Java Client Generation
Use the Petstore API as an example to generate a Java client:
# 使用命令行工具 swagger-codegen generate -i https://petstore.swagger.io/v2/swagger.json -l java -o ./java-client # 或使用JAR文件 java -jar swagger-codegen-cli.jar generate \ -i https://petstore.swagger.io/v2/swagger.json \ -l java \ -o ./java-client
The structure of the generated client SDK:
java-client/ ├── pom.xml # Maven项目文件 ├── README.md # 说明文档 ├── src/ │ ├── main/ │ │ ├── java/ # 生成的Java代码 │ │ └── resources/ # 配置文件 │ └── test/ # 测试代码 └── .gitignore
Using the generated Java client:
Example
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 authentication
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 a Python client:
swagger-codegen generate -i https://petstore.swagger.io/v2/swagger.json -l python -o ./python-client
Usage example for the Python client:
Example
from swagger_client.rest import ApiException
# Create an API client instance
api_instance = swagger_client.PetApi()
api_client = api_instance.api_client
# Set the API key
api_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'
try:
# Get the pet with the specified ID
pet = api_instance.get_pet_by_id(pet_id=789)
print(pet)
except ApiException as e:
print("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 a Spring Boot server stub:
swagger-codegen generate \ -i https://petstore.swagger.io/v2/swagger.json \ -l spring \ -o ./spring-server
The structure of the generated Spring server code:
spring-server/ ├── pom.xml # Maven项目文件 ├── README.md # 说明文档 ├── src/ │ ├── main/ │ │ ├── java/ # 控制器接口和模型类 │ │ └── resources/ # 配置文件和静态资源 │ └── test/ # 测试代码 └── .gitignore
Implement the generated controller interface:
Example
public class PetApiController implements PetApi {
@Override
public ResponseEntity<Pet> getPetById(Long petId) {
// Implement API logic
Pet pet = new Pet();
pet.setId(petId);
pet.setName("sample 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
Usage example for the Node.js server:
Example
module.exports.getPetById = function(petId) {
return new Promise(function(resolve, reject) {
var examples = {};
examples['application/json'] = {
"id": petId,
"name": "sample pet",
"status": "available"
};
resolve(examples[Object.keys(examples)[0]]);
});
}
OpenAPI Generator Advanced
OpenAPI Generator vs Swagger Codegen
OpenAPI Generator is a fork of Swagger Codegen, which began independent development in 2018. Its main advantages include:
- More active community maintenance
- Broader template support
- Better support for OpenAPI 3.0
- More configuration options and customization capabilities
Install OpenAPI Generator:
# 使用npm安装 npm install @openapitools/openapi-generator-cli -g # 使用Homebrew安装 brew install openapi-generator # 下载JAR文件 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:
# 显示帮助信息 openapi-generator help # 生成Java客户端 openapi-generator generate \ -i https://petstore.swagger.io/v2/swagger.json \ -g java \ -o ./java-client # 列出支持的生成器 openapi-generator list
Custom Templates
Template Basics
OpenAPI Generator uses the Mustache template engine. To customize the generated code, you need to:
- Obtain default templates
- Modify templates to meet your needs
- Generate code using custom templates
Create custom templates<# 使用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 template 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 common 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 a configuration file:
openapi-generator generate \ -i spec.yaml \ -g java \ -o output \ -c config.json
Practical Project Cases
API Design from Scratch
Design your API using Swagger Editor:
- Visithttps://editor.swagger.io/
- Create an OpenAPI specification file:
Example
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 a 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 # 生成React前端 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
-
Generated code fails to compile
- Ensure the OpenAPI specification complies with standards
- Check custom templates for syntax errors
- Update to the latest version of the generator
-
Custom templates do not take effect
- Ensure the template path is correct
- Check that the template file name matches the original template
- Use absolute paths instead of relative paths
-
The generated code is missing certain features
- Check whether the OpenAPI specification fully defines the required functionality
- Confirm that the correct generator and configuration options are used
- Consider using custom templates to add extra functionality
-
The generated code is incompatible with existing projects
- Use configuration options to adjust package names and naming conventions
- Adjust code style through custom templates
- Consider generating only the API interfaces and implementing the specific logic manually
Advanced Features and Best Practices
Version Management
Best practices for managing API versions:
- Clearly specify the version number in the OpenAPI specification
- Use Semantic Versioning (SemVer)
- Use different base paths for different versions of the API
- Save specification files for all versions
CI/CD Integration
Integrate code generation into the CI/CD pipeline:
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.email '[email protected]'
git add ./generated-client
git commit -m "Auto-generate API client"
git push
Enterprise Application Recommendations
For enterprise-level projects:
-
Centrally manage API specifications
- Use a dedicated Git repository to manage API specifications
- Implement a code review process to ensure quality
-
Establish a style guide for generated code
- Create consistent naming conventions
- Define error handling standards
- Design a unified authentication handling approach
-
Mix generated code and handwritten code
- Generate the basic framework and data models
- Implement complex business logic manually
- Use the adapter pattern to isolate generated code and handwritten code
-
Consider a microservices architecture
- Maintain independent API specifications for each microservice
- Use an API gateway to unify external interfaces
- Implement client code between services through code generation