YAML Swagger OpenAPI
Swagger is a unified front and back end tool for generating documents and code. It uses YAML/JSON as the description language to describe the API through the OpenAPI Specification. Finally, Codegen is used to generate various languages, library codes and Docs according to different configurations.
Ideally, a single description file (YAML/JSON) is needed to generate the back end, the front end (Android ios Web…) This ensures the consistency of the front and back ends, and only the YAML files need to be updated.
YAML
JSON is already familiar. Swagger can use JSON as a description language, but YAML is more concise and intuitive, so YAML is more recommended. The basic syntax of YAML is not complicated. Here are some basic syntax:
-
Yaml files start with… At the end
-
Members of the same level (such as list members) can be identified by “-“
-
Comment a line starting with #
-
list:
fruits:
- Apple
- Orange
- Strawberry
- Mango
Copy the code
- key / value
martin:
name: Martin D'vloper
job: Developer
skill: Elite
Copy the code
- List/map is used together
- martin:
name: Martin D'vloper
job: Developer
skills:
- python
- perl
- pascal
- tabitha:
name: Tabitha Bitumen
job: Developer
skills:
- lisp
- fortran
- erlang
Copy the code
- Short for list/map
martin: {name: Martin D'vloper, job: Developer, skill: Elite}
fruits: ['Apple', 'Orange', 'Strawberry', 'Mango']
Copy the code
- There are no strict restrictions on how Boolean values can be written
create_key: yes
needs_agent: no
knows_oop: True
likes_emacs: TRUE
uses_cvs: false
Copy the code
-
|
Using a newline>
Ignore a newline
include_newlines: |
exactly as you see
will appear these three
lines of poetry
ignore_newlines: >
this is really a
single line of text
despite appearances
Copy the code
OpenAPI-Specification
OpenAPI is a set of specifications for describing RESTful APIs.
The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.
An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases.
All kinds of code, documentation, and tools can be generated as long as they conform to OpenAPI specifications. The latest version of OpenAPI is 3.0.0, and the API structure has been adjusted compared to 2.0. For details about the document, see OpenAPI-Specification 3.0.0
I compiled a mind map of the apis I focused on while reading the 3.0 specification (not perfect, will be updated)
Swagger
Swagger actually contains a number of tools Editor Codegen UI…
- Editor is used to edit YAML using OpenAPI
- Codegen is used to generate code for different language libraries
- The UI is used to generate documents
Here’s how to use Codegen:
-
Download Swagger – codeGen -cli.jar first
-
Make sure maven is installed
-
Ready to swagger. Yaml
-
Json configuration file because we mentioned earlier that Swagger can generate various lang lib code, here is the configuration: see config help
java -jar swagger-codegen-cli.jar config-help -l java Copy the code
CONFIG OPTIONS sortParamsByRequiredFlag Sort method arguments to place required parameters before optional parameters. (Default: true) ensureUniqueParams Whether to ensure parameter names are unique in an operation (rename parameters that are not). (Default: true) allowUnicodeIdentifiers boolean, toggles whether unicode identifiers are allowed in names or not, default is false (Default: false) modelPackage package for generated models apiPackage package for generated api classes invokerPackage root package for generated code groupId groupId in generated pom.xml artifactId artifactId in generated pom.xml artifactVersion artifact version in generated pom.xml artifactUrl artifact URL in generated pom.xml artifactDescription artifact description in generated pom.xml scmConnection SCM connection in generated pom.xml scmDeveloperConnection SCM developer connection in generated pom.xml scmUrl SCM URL in generated pom.xml developerName developer name in generated pom.xml developerEmail developer email in generated pom.xml developerOrganization developer organization in generated pom.xml developerOrganizationUrl developer organization URL in generated pom.xml licenseName The name of the license licenseUrl The URL of the license sourceFolder source folder for generated code localVariablePrefix prefix for generated code members and local variables serializableModel boolean - toggle "implements Serializable" for generated models (Default: false) bigDecimalAsString Treat BigDecimal values as Strings to avoid precision loss. (Default: false) fullJavaUtil whether to use fully qualified name for classes under java.util. This option only works for Java API client (Default: false) hideGenerationTimestamp hides the timestamp when files were generated withXml whether to include support for application/xml content type. This option only works for Java API client (resttemplate) (Default: false) dateLibrary Option. Date library to use joda - Joda (for legacy app only) legacy - Legacy java.util.Date (if you really have a good reason not to use threetenbp java8-localdatetime - Java 8 using LocalDateTime (for legacy app only) Java 8 Native JSR310 preferred for JDK 1.8+ This also sets "java8" to true threetenbP-backport of JSR310 (Preferred for JDK < 1.8) Java8 option. Use java8 classes instead of third party equivalents true - Use Java 8 classes such as Base64 false - Various third party libraries as needed useRxJava Whether to use the RxJava adapter with the retrofit2 library. (Default: false) useRxJava2 Whether to use the RxJava2 adapter with the retrofit2 library. (Default: false) parcelableModel Whether to generate models for Android that implement Parcelable with the okhttp-gson library. (Default: false) usePlay24WS Use Play! 2.4 Async HTTP Client (Play WS API) (Default: false) supportJava6 Whether to support Java6 with the Jersey1 library. (Default: false) useBeanValidation Use BeanValidation API annotations (Default: false) performBeanValidation Perform BeanValidation (Default: false) useGzipFeature Send gzip-encoded requests (Default: false) useRuntimeException Use RuntimeException instead of Exception (Default: false) library library template (sub-template) to use (Default: okhttp-gson) jersey1 - HTTP client: Jersey Client 1.19.4. JSON processing: Jackson 2.8.9. Enable Java6 support using '-dSupportJava6 =true'. Enable gZIP Request Encoding using '-dusegzipfeature =true'. Feign-http client: OpenFeign 9.4.0. JSON processing: Jackson 2.8.9 Jersey2 - HTTP client: Jersey Client 2.25.1. JSON processing: Jackson 2.8.9 okhttp-gson-http client: okhttp 2.7.5. JSON processing: Enable Parcelable Models on Android using '-dParcelableModel =true'. Enable gzip Request encoding using '-dusegzipfeature =true'. Retrofit-http client: OkHttp 2.7.5. JSON processing: Gson 2.3.1 (Retrofit 1.9.0). IMPORTANT NOTE: retrofit1.x is no longer actively maintained so please upgrade to 'retrofit2' instead. retrofit2 - HTTP client: OkHttp 3.8.0. JSON processing: Gson 2.6.1 (Retrofit 2.3.0). Enable the RxJava adapter using '-dUserxJava [2]=true'. (RxJava 1.x or 2.x HTTP client: Spring RestTemplate 4.3.9-release. JSON processing: Jackson 2.8.9 Resteasy-HTTP client: Resteasy Client 3.1.3.Final. JSON processing: Jackson 2.8.9Copy the code
There are several main configuration parameters:
- Library, which generates code to pay for classes, has several types: Jersey1, Jersey2, OkHTTP-Gson, RestTemplate, Resteasy, Feign, Retrofit, RetroFIT2, and we chose RetroFIT2
- DeveloperName, the developerName, will appear in the code file
- DeveloperEmail, developerEmail, will appear in the code file
- DeveloprOrganization, the developer organization, is going to be in the code
- InvokerPackage, the package name of the project
- ApiPackage, the package name of the generated *** api.java file
- ModelPackage, the generated data model Java file package name
- DateLibrary, time – using class open
- UseRxJava, whether to useRxJava to generate the API interface
- UseRxJava2, whether to call the interface as rxJava2
-
Generate the generated code first prints parameter information
java -jar swagger-codegen-cli.jar generate help Copy the code
NAME swagger-codegen-cli generate - Generate code with chosen lang SYNOPSIS swagger-codegen-cli generate [(-a <authorization> | --auth <authorization>)] [--additional-properties <additional properties>...] [--api-package <api package>] [--artifact-id <artifact id>] [--artifact-version <artifact version>] [(-c <configuration file> | --config <configuration file>)] [-D <system properties>...] [--git-repo-id <git repo id>] [--git-user-id <git user id>] [--group-id <group id>] [--http-user-agent <http user agent>] (-i <spec file> | --input-spec <spec file>) [--ignore-file-override <ignore file override location>] [--import-mappings <import mappings>...] [--instantiation-types <instantiation types>...] [--invoker-package <invoker package>] (-l <language> | --lang <language>) [--language-specific-primitives <language specific primitives>...] [--library <library>] [--model-name-prefix <model name prefix>] [--model-name-suffix <model name suffix>] [--model-package <model package>] [(-o <output directory> | --output <output directory>)] [--release-note <release note>] [--remove-operation-id-prefix] [--reserved-words-mappings <reserved word mappings>...] [(-s | --skip-overwrite)] [(-t <template directory> | --template-dir <template directory>)] [--type-mappings <type mappings>...] [(-v | --verbose)] OPTIONS -a <authorization>, --auth <authorization> adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values --additional-properties <additional properties> sets additional properties that can be referenced by the mustache templates in the format of name=value,name=value. You can also have multiple occurrences of this option. --api-package <api package> package for generated api classes --artifact-id <artifact id> artifactId in generated pom.xml --artifact-version <artifact version> artifact version in generated pom.xml -c <configuration file>, --config <configuration file> Path to json configuration file. File content should be in a json format {"optionKey":"optionValue", "optionKey1":"optionValue1"...} Supported options can be different for each language. Run config-help -l {lang} command for language specific config options. -D <system properties> sets specified system properties in the format of name=value,name=value (or multiple options, each with name=value) --git-repo-id <git repo id> Git repo ID, e.g. swagger-codegen. --git-user-id <git user id> Git user ID, e.g. swagger-api. --group-id <group id> groupId in generated pom.xml --http-user-agent <http user agent> HTTP user agent, e.g. codegen_csharp_api_client, default to 'Swagger-Codegen/{packageVersion}}/{language}' -i <spec file>, --input-spec <spec file> location of the swagger spec, as URL or file (required) --ignore-file-override <ignore file override location> Specifies an override location for the .swagger-codegen-ignore file. Most useful on initial generation. --import-mappings <import mappings> specifies mappings between a given class and the import that should be used for that class in the format of type=import,type=import. You can also have multiple occurrences of this option. --instantiation-types <instantiation types> sets instantiation type mappings in the format of type=instantiatedType,type=instantiatedType.For example (in Java): array=ArrayList,map=HashMap. In other words array types will get instantiated as ArrayList in generated code. You can also have multiple occurrences of this option. --invoker-package <invoker package> root package for generated code -l <language>, --lang <language> client language to generate (maybe class name in classpath, required) --language-specific-primitives <language specific primitives> specifies additional language specific primitive types in the format of type1,type2,type3,type3. For example: String,boolean,Boolean,Double. You can also have multiple occurrences of this option. --library <library> library template (sub-template) --model-name-prefix <model name prefix> Prefix that will be prepended to all model names. Default is the empty string. --model-name-suffix <model name suffix> Suffix that will be appended to all model names. Default is the empty string. --model-package <model package> package for generated models -o <output directory>, --output <output directory> where to write the generated files (current dir by default) --release-note <release note> Release note, default to 'Minor update'. --remove-operation-id-prefix Remove prefix of operationId, e.g. config_getId => getId --reserved-words-mappings <reserved word mappings> specifies how a reserved name should be escaped to. Otherwise, the default _<name> is used. For example id=identifier. You can also have multiple occurrences of this option. -s, --skip-overwrite specifies if the existing files should be overwritten during the generation. -t <template directory>, --template-dir <template directory> folder containing the template files --type-mappings <type mappings> sets mappings between swagger spec types and generated code types in the format of swaggerType=generatedType,swaggerType=generatedType. For example: array=List,map=Map,string=String. You can also have multiple occurrences of this option. -v, --verbose verbose mode Copy the code
Several main parameters:
- -i indicates the input file. Editor Indicates the generated design file path, for example, -i ~/Desktop/swagger.yaml
- -o code generation directory, Swagger CodeGen code generation to where, e.g. -o ~/Desktop
- -l generates the code language, we generate Java, such as -l Java
- -c Specifies the configuration file path, for example, -c ~/Desktop/config.json
Finally generate the code
java -jar swagger-codegen-cli.jar generate -i swagger.yaml -o client -l java -c config.json Copy the code
Successfully generated the corresponding code and doc under ~/Desktop
IO /docs/specif… www.jianshu.com/p/c178c18aa… Github.com/OAI/OpenAPI… github.com/swagger-api