It's been a while since swagger became a hot topic. I use it very conveniently at work. While writing the API definition with swagger-editor, you can actually skip the request and check it, or ask another engineer to hit the API to check it. Since postman etc. can directly import swagger files, you can create simple management commands by swaggar-> postman-> curl generation.
However, when I try to use it for implementation, there are times when there is no generator for the web framework I am using, or a different http client library is used, so it is a little insufficient to use for my environment. think.
This is an introduction to how to use the code generator for such people.
swagger-codegen
Swagger Official java code generator. It has a Plagger implementation and can generate both clients and servers.
The code template engine is mustache.
mustache There are compatible implementations in various languages and swagger-codegen uses jmustache. Example of outputting "No repos: (" if there is repos in Map and the name of the member of repos is not output
python
{{#repos}}{{name}}{{/repos}}
{{^repos}}No repos :({{/repos}}
swagger-codegen is a maven project and you need to have maven installed to build. First check out and build.
python
git clone https://github.com/swagger-api/swagger-codegen
cd swagger-codegen
mvn
Then generate a generator template.
python
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar meta \
-o output/myLibrary -n myClientCodegen -p com.my.company.codegen
The template maven project is output to output / myLibrary. It is a simple implementation that inherits the DefaultCodegen class.
The directory structure is as follows
python
src
└── main
├── java
│ └── com
│ └── my
│ └── company
│ └── codegen
│ └── MyclientcodegenGenerator.java
└── resources
├── META-INF
│ └── services
│ └── io.swagger.codegen.CodegenConfig
└── myClientCodegen (Template file)
├── api.mustache
├── model.mustache
└── myFile.mustache
You can change the output of the fixed form by rewriting the template. If you want to make camel case a snake case, you will write it in java.
Build and run it as a trial. For some reason some guys haven't generated a template file so I'll add that too
python
cd output/myLibrary
touch src/main/resources/myClientCodegen/myFile.mustache
mvn install
cd ../../
java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar io.swagger.codegen.SwaggerCodegen generate -l myClientCodegen -i http://petstore.swagger.io/v2/swagger.json -o myClient
This will generate a library in the myClient directory.
Recommended Posts