Swagger 是一个统一前后端用于生成文档和代码的工具,它使用 yaml / json 作为描述语言 通过 OpenAPI Specification 来描述 API,最后使用 Codegen 根据不同的配置来生成各种 language、library 的 Code、Docs.

其最理想的情况则是只需一份描述文件(yaml/json) 生成 后端、前端(android ios web...)的代码和文档,这样的话保证了前后端的统一,且需要升级改动也只需要修改 yaml 文件。

YAML

JSON 都已经很熟悉了,虽然 Swagger 可以使用 JSON 作为描述语言,但是因为 YAML 更为简洁直观,所以更推荐 YAML。 YAML 的基本语法并不复杂,这里介绍一些基本语法:

  • yaml 文件 以---开始 ...结尾

  • 同一级别的成员(如 list 成员)可以通过"- "来辨识

  • 注释以#开头的一行

  • list:

fruits:- Apple- Orange- Strawberry- Mango
复制代码
  • key / value
martin:name: Martin D'vloperjob: Developerskill: Elite
复制代码
  • list / map 混合使用
-  martin:name: Martin D'vloperjob: Developerskills:- python- perl- pascal
-  tabitha:name: Tabitha Bitumenjob: Developerskills:- lisp- fortran- erlang
复制代码
  • list / map 的简写
martin: {name: Martin D'vloper, job: Developer, skill: Elite}
fruits: ['Apple', 'Orange', 'Strawberry', 'Mango']
复制代码
  • boolean 值的写法没有严格限制
create_key: yes
needs_agent: no
knows_oop: True
likes_emacs: TRUE
uses_cvs: false
复制代码
  • |使用换行 >忽略换行
include_newlines: |exactly as you seewill appear these threelines of poetryignore_newlines: >this is really asingle line of textdespite appearances
复制代码

OpenAPI-Specification

OpenAPI 是一套用于描述 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.

只要符合 OpenAPI 规范的都可以生成各类代码、文档、工具。 目前 OpenAPI 最新 3.0.0 ,对比 2.0 对 API 结构进行了调整。
文档内容繁多请参考 OpenAPI-Specification 3.0.0

下面是 Uber API 的 example

# this is an example of the Uber API
# as a demonstration of an API spec in YAML
openapi: "3.0.0"
info:title: Uber APIdescription: Move your app forward with the Uber APIversion: "1.0.0"
servers:- url: https://api.uber.com/v1
paths:/products:get:summary: Product Typesdescription: The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.parameters:- name: latitudein: querydescription: Latitude component of location.required: trueschema:type: numberformat: double- name: longitudein: querydescription: Longitude component of location.required: trueschema:type: numberformat: doublesecurity: - apikey: []tags: - Productsresponses:  '200':description: An array of productscontent:application/json:schema:$ref: "#/components/schemas/ProductList"default:description: Unexpected errorcontent:application/json:schema:$ref: "#/components/schemas/Error"/estimates/price:get:summary: Price Estimatesdescription: The Price Estimates endpoint returns an estimated price range for each product offered at a given location. The price estimate is provided as a formatted string with the full price range and the localized currency symbol.<br><br>The response also includes low and high estimates, and the [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for situations requiring currency conversion. When surge is active for a particular product, its surge_multiplier will be greater than 1, but the price estimate already factors in this multiplier.parameters:- name: start_latitudein: querydescription: Latitude component of start location.required: trueschema:type: numberformat: double- name: start_longitudein: querydescription: Longitude component of start location.required: trueschema:type: numberformat: double- name: end_latitudein: querydescription: Latitude component of end location.required: trueschema:type: numberformat: double- name: end_longitudein: querydescription: Longitude component of end location.required: trueschema:type: numberformat: doubletags: - Estimatesresponses:  '200':description: An array of price estimates by productcontent:application/json:schema:type: arrayitems:$ref: "#/components/schemas/PriceEstimate"default:description: Unexpected errorcontent:application/json:schema:$ref: "#/components/schemas/Error"/estimates/time:get:summary: Time Estimatesdescription: The Time Estimates endpoint returns ETAs for all products offered at a given location, with the responses expressed as integers in seconds. We recommend that this endpoint be called every minute to provide the most accurate, up-to-date ETAs.parameters:- name: start_latitudein: querydescription: Latitude component of start location.required: trueschema:type: numberformat: double- name: start_longitudein: querydescription: Longitude component of start location.required: trueschema:type: numberformat: double- name: customer_uuidin: queryschema:type: stringformat: uuiddescription: Unique customer identifier to be used for experience customization.- name: product_idin: queryschema:type: stringdescription: Unique identifier representing a specific product for a given latitude & longitude.tags: - Estimatesresponses:  '200':description: An array of productscontent:application/json:schema:type: arrayitems:$ref: "#/components/schemas/Product"default:description: Unexpected errorcontent:application/json:schema:$ref: "#/components/schemas/Error"/me:get:summary: User Profiledescription: The User Profile endpoint returns information about the Uber user that has authorized with the application.tags: - Userresponses:'200':description: Profile information for a usercontent:application/json:schema:$ref: "#/components/schemas/Profile"default:description: Unexpected errorcontent:application/json:schema:$ref: "#/components/schemas/Error"/history:get:summary: User Activitydescription: The User Activity endpoint returns data about a user's lifetime activity with Uber. The response will include pickup locations and times, dropoff locations and times, the distance of past requests, and information about which products were requested.<br><br>The history array in the response will have a maximum length based on the limit parameter. The response value count may exceed limit, therefore subsequent API requests may be necessary.parameters:- name: offsetin: queryschema:type: integerformat: int32description: Offset the list of returned results by this amount. Default is zero.- name: limitin: queryschema:type: integerformat: int32 description: Number of items to retrieve. Default is 5, maximum is 100.tags: - Userresponses:'200':description: History information for the given usercontent:application/json:schema:$ref: "#/components/schemas/Activities"default:description: Unexpected errorcontent:application/json:schema:$ref: "#/components/schemas/Error"
components:securitySchemes:apikey:type: apiKeyname: server_tokenin: queryschemas:Product:properties:product_id:type: stringdescription: Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles.description:type: stringdescription: Description of product.display_name:type: stringdescription: Display name of product.capacity:type: integerdescription: Capacity of product. For example, 4 people.image:type: stringdescription: Image URL representing the product.ProductList:properties:products:description: Contains the list of productstype: arrayitems: $ref: "#/components/schemas/Product"PriceEstimate:properties:product_id:type: stringdescription: Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angelescurrency_code:type: stringdescription: "[ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code."display_name:type: stringdescription: Display name of product.estimate: type: stringdescription: Formatted string of estimate in local currency of the start location. Estimate could be a range, a single number (flat rate) or "Metered" for TAXI.low_estimate:type: numberdescription: Lower bound of the estimated price.high_estimate:type: numberdescription: Upper bound of the estimated price.surge_multiplier:type: numberdescription: Expected surge multiplier. Surge is active if surge_multiplier is greater than 1. Price estimate already factors in the surge multiplier.Profile:properties:first_name:type: stringdescription: First name of the Uber user.last_name:type: stringdescription: Last name of the Uber user.email:type: stringdescription: Email address of the Uber userpicture:type: stringdescription: Image URL of the Uber user.promo_code:type: stringdescription: Promo code of the Uber user.   Activity:properties:uuid:type: stringdescription: Unique identifier for the activityActivities:properties:offset:type: integerformat: int32description: Position in pagination.limit:type: integerformat: int32description: Number of items to retrieve (100 max).count:type: integerformat: int32description: Total number of items available.history:type: arrayitems:$ref: "#/components/schemas/Activity"Error:properties:code:type: stringmessage:type: stringfields:type: string
复制代码

这里将 OpenAPI 3.0 规范中把重点使用的 api 整理了一张思维导图(还不完善,会持续更新)

Swagger

Swagger 实际上包含了一系列的工具 Editor Codegen UI ...

  • Editor 用于使用 OpenAPI 编辑 yaml
  • Codegen 用于生成不同的 language library 的代码
  • UI 用于生成文档

下面介绍一下 Codegen 的使用:

  1. 首先下载 swagger-codegen-cli.jar

  2. 确保装好了 maven

  3. 准备 swagger.yaml

  4. 编写 config.json 配置文件
    因为之前提到 Swagger 可以生成各种 lang lib 的代码,所以这里便是进行此类配置:
    查看配置 help

    java -jar swagger-codegen-cli.jar config-help -l java
    复制代码
    CONFIG OPTIONSsortParamsByRequiredFlagSort method arguments to place required parameters before optional parameters. (Default: true)ensureUniqueParamsWhether to ensure parameter names are unique in an operation (rename parameters that are not). (Default: true)allowUnicodeIdentifiersboolean, toggles whether unicode identifiers are allowed in names or not, default is false (Default: false)modelPackagepackage for generated modelsapiPackagepackage for generated api classesinvokerPackageroot package for generated codegroupIdgroupId in generated pom.xmlartifactIdartifactId in generated pom.xmlartifactVersionartifact version in generated pom.xmlartifactUrlartifact URL in generated pom.xmlartifactDescriptionartifact description in generated pom.xmlscmConnectionSCM connection in generated pom.xmlscmDeveloperConnectionSCM developer connection in generated pom.xmlscmUrlSCM URL in generated pom.xmldeveloperNamedeveloper name in generated pom.xmldeveloperEmaildeveloper email in generated pom.xmldeveloperOrganizationdeveloper organization in generated pom.xmldeveloperOrganizationUrldeveloper organization URL in generated pom.xmllicenseNameThe name of the licenselicenseUrlThe URL of the licensesourceFoldersource folder for generated codelocalVariablePrefixprefix for generated code members and local variablesserializableModelboolean - toggle "implements Serializable" for generated models (Default: false)bigDecimalAsStringTreat BigDecimal values as Strings to avoid precision loss. (Default: false)fullJavaUtilwhether to use fully qualified name for classes under java.util. This option only works for Java API client (Default: false)hideGenerationTimestamphides the timestamp when files were generatedwithXmlwhether to include support for application/xml content type. This option only works for Java API client (resttemplate) (Default: false)dateLibraryOption. Date library to usejoda - Joda (for legacy app only)legacy - Legacy java.util.Date (if you really have a good reason not to use threetenbpjava8-localdatetime - Java 8 using LocalDateTime (for legacy app only)java8 - Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets "java8" to truethreetenbp - Backport of JSR310 (preferred for jdk < 1.8)java8Option. Use Java8 classes instead of third party equivalentstrue - Use Java 8 classes such as Base64false - Various third party libraries as neededuseRxJavaWhether to use the RxJava adapter with the retrofit2 library. (Default: false)useRxJava2Whether to use the RxJava2 adapter with the retrofit2 library. (Default: false)parcelableModelWhether to generate models for Android that implement Parcelable with the okhttp-gson library. (Default: false)usePlay24WSUse Play! 2.4 Async HTTP client (Play WS API) (Default: false)supportJava6Whether to support Java6 with the Jersey1 library. (Default: false)useBeanValidationUse BeanValidation API annotations (Default: false)performBeanValidationPerform BeanValidation (Default: false)useGzipFeatureSend gzip-encoded requests (Default: false)useRuntimeExceptionUse RuntimeException instead of Exception (Default: false)librarylibrary 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.9jersey2 - HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.8.9okhttp-gson - HTTP client: OkHttp 2.7.5. JSON processing: Gson 2.8.1. 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)resttemplate - HTTP client: Spring RestTemplate 4.3.9-RELEASE. JSON processing: Jackson 2.8.9resteasy - HTTP client: Resteasy client 3.1.3.Final. JSON processing: Jackson 2.8.9复制代码

    几个主要的配置参数:

    • library,生成的代码支付的类,有jersey1、jersey2、okhttp-gson、resttemplate、resteasy、feign、retrofit、retrofit2等几种类型,我们选择的retrofit2
    • developerName,开发者名字,会出现在代码文件里
    • developerEmail,开发者邮箱,会出现在代码文件里
    • developrOrganization,开发者组织,会出现在代码里
    • invokerPackage,项目的包名
    • apiPackage,生成的***Api.java文件的包名
    • modelPackage,生成的数据模型java文件包名
    • dateLibrary,时间使用的类开
    • useRxJava,是否使用rxjava生成api接口
    • useRxJava2,是否使用rxjava2的方式调用接口
  5. generate 生成代码 首先打印参数信息

    java -jar swagger-codegen-cli.jar generate help
    复制代码
    NAMEswagger-codegen-cli generate - Generate code with chosen langSYNOPSISswagger-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 definitionsremotely. Pass in a URL-encoded string of name:header with a commaseparating multiple values--additional-properties <additional properties>sets additional properties that can be referenced by the mustachetemplates in the format of name=value,name=value. You can also havemultiple 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 jsonformat {"optionKey":"optionValue", "optionKey1":"optionValue1"...}Supported options can be different for each language. Runconfig-help -l {lang} command for language specific config options.-D <system properties>sets specified system properties in the format ofname=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 shouldbe used for that class in the format of type=import,type=import. Youcan also have multiple occurrences of this option.--instantiation-types <instantiation types>sets instantiation type mappings in the format oftype=instantiatedType,type=instantiatedType.For example (in Java):array=ArrayList,map=HashMap. In other words array types will getinstantiated as ArrayList in generated code. You can also havemultiple 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 formatof type1,type2,type3,type3. For example:String,boolean,Boolean,Double. You can also have multipleoccurrences 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 theempty string.--model-name-suffix <model name suffix>Suffix that will be appended to all model names. Default is theempty 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-prefixRemove prefix of operationId, e.g. config_getId => getId--reserved-words-mappings <reserved word mappings>specifies how a reserved name should be escaped to. Otherwise, thedefault _<name> is used. For example id=identifier. You can alsohave multiple occurrences of this option.-s, --skip-overwritespecifies if the existing files should be overwritten during thegeneration.-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 inthe format of swaggerType=generatedType,swaggerType=generatedType.For example: array=List,map=Map,string=String. You can also havemultiple occurrences of this option.-v, --verboseverbose mode
    复制代码

    几个主要参数:

    • -i 表示输入的文件,editor生成的设计文件路径,如:-i ~/Desktop/swagger.yaml
    • -o 代码生成目录,swagger codegen 把代码生成到什么地方,如:-o ~/Desktop
    • -l 生成代码语言,我们是生成java,如:-l java
    • -c 配置文件,配制文件路径,如:-c ~/Desktop/config.json

    最后生成代码

    java -jar swagger-codegen-cli.jar generate -i swagger.yaml -o client -l java -c config.json
    复制代码

    成功在 ~/Desktop 下生成了相应的 code 和 doc

    参考资料以及推荐阅读的资料
    docs.ansible.com/ansible/lat… swagger.io/docs/specif…
    www.jianshu.com/p/c178c18aa…
    github.com/OAI/OpenAPI…
    github.com/swagger-api www.gitbook.com/book/huangw…

Swagger (YAML OpenAPI) 从放弃到入门相关推荐

  1. Python 实现 Swagger yaml 格式 api 文档合并

    需求来源 公司业务系统中,API文档定义使用了Swagger,由于多人开发中每个人开发的节点不同,整体的业务过于复杂,维护一套完整的 API 文档十分繁重,且容易出现误修改,所以用 python 实现 ...

  2. swagger跟openAPI不同

    今年是OpenAPI 3.0的正式发布,这是OpenAPI规范的最新版本. 对于那些从事API开发的人来说,OAS 3.0的发布是一件大事. 为什么?该版本如此重要的最显着原因之一是,OpenAPI ...

  3. 【HTML/CSS】从放弃到入门-笔记1

    从放弃到入门1 ⇒ 从放弃到入门2 了解浏览器 浏览器和服务器(了解) 浏览器是一款软件,浏览器功能:1将网页渲染出来给用户查看,2让用户通过浏览器与网页交互 不同浏览器的内核不同,渲染效果会有小的差 ...

  4. ZYNQ从放弃到入门(三)- 中断(一)

    在检查PS端IO口状态时,常用的就是轮询,但是实际工程中很少用这种方式,主要是运行复杂逻辑时,轮询方式效率太低,CPU需要等待IO口状态变化,这种肯定不符合大多数应用,所以多数情况下都是使用中断方式进 ...

  5. 五分钟学后端技术:分布式系统理论 - 从放弃到入门

    转载声明 本系列文章转自某技术大佬的博客https://www.cnblogs.com/bangerlee/ 该系列文章是我在网上能够找到的最全面的分布式理论介绍文章了,一直没看到有人整理这个系列文章 ...

  6. ZYNQ从放弃到入门(八)-PS和PL交互

    之前的几篇文章主要集中在 Zynq SoC 的处理系统 (PS) 方面,包括: 使用 MIO 和 EMIO Zynq SoC 的中断结构 Zynq 私有定时器和看门狗 Zynq SoC 的三重定时器计 ...

  7. 1C语言 从放弃到入门-王桂林-专题视频课程

    <1>C语言 从放弃到入门-1052人已学习 课程介绍         C语言 从放弃到入门 课程收益     所有对C语言有入门恐惧的人. 讲师介绍     王桂林 更多讲师课程     ...

  8. 【HTML/CSS】从放弃到入门-笔记2

    从放弃到入门1 >> 从放弃到入门2 CSS三大特性练习(理解) div和span标签(掌握) DIV配合CSS完成网页的搭建 span常用来配合修改局部样式 区别:DIV一个容器级别的标 ...

  9. C++音视频开发从放弃到入门(基于FFmpeg+OpenCV)

    前言 音视频开发一定要学C++吗?答案是肯定的.虽然其它语言也能搞音视频开发,甚至使用起来更简单,但"语言越高级,离真相就越远",当你的功能需求日益增多,程序的性能需求越来越迫切, ...

最新文章

  1. 基于统计概率和机器学习的文本分类技术
  2. 王哲:Cocos2d-x 3.0引擎带来了什么?
  3. 2011年上海交通大学计算机研究生机试真题
  4. C++读取txt数据为二维数组 将数据保存到txt文本中
  5. 增量索引和全量索引_搜索引擎(七)高可用的solr搜索引擎服务架构
  6. java blockqueue_[Java基础] Java多线程-工具篇-BlockingQueue
  7. c语言 字符串不足用零代替,关于c语言的知识点不足的地方
  8. miniUI mini-monthpicker ie8兼容性问题
  9. 特征提取之——Haar特征
  10. 581. Shortest Unsorted Continuous Subarray
  11. YDUI Touch InfiniteScroll无限加载数据测试
  12. VIN码/车架号的详解,车架号识别,VIN码识别,OCR车架号识别能带来什么
  13. 怎么看PLC梯形图?
  14. win7升级win10正式版_Win7免费升级Win10
  15. Citrix Receiver for Linux安装和cert证书添加解决SSL错误
  16. 快速复现利用Log4j漏洞启动windows计算器
  17. CodeForces 13A【暴力】
  18. 2005年中国移动增值业务市场回顾与展望
  19. 强化学习教程(四):从PDG到DDPG的原理及tf代码实现详解
  20. 量化交易 实战第七课 单因子 IC 分析

热门文章

  1. MIMIC-IV v2.0数据库
  2. 笔记本未启用无线服务器,WiFi无线网络提示未启用DHCP无法上网的解决方法
  3. css盒模型(css的两种盒模型:标准盒模型、怪异盒模型)和 css3指定盒子模型种类的box-sizing属性
  4. char to hex
  5. sudo dolphin_如何使用Dolphin在PC上玩Wii和GameCube游戏
  6. python爬取pubmed的文献_使用python來調用pubmed API快速整理文獻
  7. iMeta期刊部分文章被PubMed收录
  8. 数据结构第二次实验-赫夫曼编码及其应用
  9. 【复试英语】应对考官三招解决尴尬局面!
  10. 西安拟制定羊肉泡馍肉夹馍制作标准