Swagger Codegen
Swagger is an open-source toolset 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**: Browser-based editor for writing OpenAPI specifications
* **Swagger UI**: Visual API documentation interface that allows developers to interactively explore APIs
* **Swagger Codegen**: Automatically generates client code and server stubs based on OpenAPI specifications
The OpenAPI Specification is a language-agnostic definition format for describing RESTful APIs.
OpenAPI allows both 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 starting, ensure your system has installed:
* Java 8+
* Maven (for Java projects)
* Git (for obtaining source code)
Install Swagger Codegen:
# Method 1: Using 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
### Generating Client SDKs
#### Java Client Generation
Generate Java client using Petstore API as an example:
# Using command line tool swagger-codegen generate -i https://petstore.swagger.io/v2/swagger.json -l java -o ./java-client# Or using 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 project fileβββ README.md # Documentationβββ src/β βββ main/β β βββ java/ # Generated Java codeβ β βββ resources/ # Configuration filesβ βββ test/ # Test codeβββ .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)
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 supported language list:
swagger-codegen langs
### Generating Server Stubs
#### 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 project fileβββ README.md # Documentationβββ src/β βββ main/β β βββ java/ # Controller interfaces and model classesβ β βββ resources/ # Configuration files and static resourcesβ βββ test/ # Test codeβββ .gitignore
Implementing the generated controller interface:
## Example
@Controller
public class PetApiController implements PetApi {
@Override
public ResponseEntity 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)]);
});
}
## OpenAPI Generator Advanced
### OpenAPI Generator vs Swagger Codegen
OpenAPI Generator is a fork of Swagger Codegen that started independent development in 2018. Main advantages include:
* More active community maintenance
* Broader template support
* Better OpenAPI 3.0 support
* More configuration options and customization capabilities
Install OpenAPI Generator:
# Install using 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:
# Display 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 generated code, you need to:
1. Obtain default templates
2. Modify templates to meet requirements
3. Generate code using custom templates
#### Creating Custom Templates<# Get templates for specific language using JAR file 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}}
#### Applying 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:
# Specific options for Java client generator openapi-generator generate \ -i spec.yaml \ -g java \ -o output \ --library retrofit2 \ --java8 true \ --use-rx-java true
#### Using Configuration Files
You can create configuration files 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 configuration file:
openapi-generator generate \ -i spec.yaml \ -g java \ -o output \ -c config.json
* * *
## Practical Project Cases
### API Design from Scratch
Design API using Swagger Editor:
1. Visit [https://editor.swagger.io/](https://editor.swagger.io/)
2. Create OpenAPI specification file:
## Example
openapi: 3.0.0
info:
title: Product Management API
version: 1.0.0
description: 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: Created successfully
content:
application/json:
schema:
$ref:'#/components/schemas/Product'
/products/{productId}:
get:
summary: Get 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 complete project from designed API specification:
1. Save API specification as `product-api.yaml`
2. Generate frontend and backend code:
# Generate Spring Boot server 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=suppo
YouTip