Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swagger Codegen (Code Generation)

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:

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:

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

)

   

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:

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:

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:

  1. Obtain the default templates
  2. Modify the templates to meet your needs
  3. 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:

  1. Access the https://editor.swagger.io/
  2. 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:

  1. Save the API specification as product-api.yaml
  2. 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

  1. The generated code cannot be compiled

  2. Ensure the OpenAPI specification conforms to the standard
  3. Check custom template syntax errors
  4. Update to the latest version of the generator
  5. - Ensure the OpenAPI specification conforms to the standard - Check custom template syntax errors - Update to the latest version of the generator
    1. Custom templates not taking effect

    2. Ensure the template path is correct
    3. Check that the template file name matches the original template
    4. Use absolute paths instead of relative paths
    5. - Ensure the template path is correct - Check that the template file name matches the original template - Use absolute paths instead of relative paths
      1. The generated code is missing certain features

      2. Check whether the OpenAPI specification fully defines the required features
      3. Confirm that the correct generator and configuration options are used
      4. Consider using custom templates to add extra features
      5. - Check whether the OpenAPI specification fully defines the required features - Confirm that the correct generator and configuration options are used - Consider using custom templates to add extra features
        1. The generated code is incompatible with the existing project

        2. Use configuration options to adjust package names and naming conventions
        3. Adjust code style through custom templates
        4. Consider generating only the API interfaces and implementing the specific logic manually
        5. - 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:

          1. Specify the version number explicitly in the OpenAPI specification
          2. Use semantic versioning (SemVer)
          3. Use different base paths for different API versions
          4. 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.

          email

          'actions@github.com'

                    git add .

          /

          generated

          client

                    git commit

          m

          "Auto-generate API client"

                    git push

          Enterprise Application Recommendations

          For enterprise-level projects:

          1. Centralize API specification management

          2. Use a dedicated Git repository to manage API specifications
          3. Implement code review processes to ensure quality
          4. - Use a dedicated Git repository to manage API specifications - Implement code review processes to ensure quality
            1. Establish style guidelines for generated code

            2. Create consistent naming conventions
            3. Establish error handling standards
            4. Design a unified authentication handling approach
            5. - Create consistent naming conventions - Establish error handling standards - Design a unified authentication handling approach
              1. Mix generated code and hand-written code

              2. Generate the base framework and data models
              3. Manually implement complex business logic
              4. Use the adapter pattern to isolate generated code from hand-written code
              5. - Generate the base framework and data models - Manually implement complex business logic - Use the adapter pattern to isolate generated code from hand-written code
                1. Consider a microservices architecture

                2. Maintain an independent API specification for each microservice
                3. Use an API gateway to unify external interfaces
                4. Implement inter-service clients through code generation
                5. - Maintain an independent API specification for each microservice - Use an API gateway to unify external interfaces - Implement inter-service clients through code generation