Mr Dk.'s BlogMr Dk.'s Blog
  • 🦆 About Me
  • ⛏️ Technology Stack
  • 🔗 Links
  • 🗒️ About Blog
  • Algorithm
  • C++
  • Compiler
  • Cryptography
  • DevOps
  • Docker
  • Git
  • Java
  • Linux
  • MS Office
  • MySQL
  • Network
  • Operating System
  • Performance
  • PostgreSQL
  • Productivity
  • Solidity
  • Vue.js
  • Web
  • Wireless
  • 🐧 How Linux Works (notes)
  • 🐧 Linux Kernel Comments (notes)
  • 🐧 Linux Kernel Development (notes)
  • 🐤 μc/OS-II Source Code (notes)
  • ☕ Understanding the JVM (notes)
  • ⛸️ Redis Implementation (notes)
  • 🗜️ Understanding Nginx (notes)
  • ⚙️ Netty in Action (notes)
  • ☁️ Spring Microservices (notes)
  • ⚒️ The Annotated STL Sources (notes)
  • ☕ Java Development Kit 8
GitHub
  • 🦆 About Me
  • ⛏️ Technology Stack
  • 🔗 Links
  • 🗒️ About Blog
  • Algorithm
  • C++
  • Compiler
  • Cryptography
  • DevOps
  • Docker
  • Git
  • Java
  • Linux
  • MS Office
  • MySQL
  • Network
  • Operating System
  • Performance
  • PostgreSQL
  • Productivity
  • Solidity
  • Vue.js
  • Web
  • Wireless
  • 🐧 How Linux Works (notes)
  • 🐧 Linux Kernel Comments (notes)
  • 🐧 Linux Kernel Development (notes)
  • 🐤 μc/OS-II Source Code (notes)
  • ☕ Understanding the JVM (notes)
  • ⛸️ Redis Implementation (notes)
  • 🗜️ Understanding Nginx (notes)
  • ⚙️ Netty in Action (notes)
  • ☁️ Spring Microservices (notes)
  • ⚒️ The Annotated STL Sources (notes)
  • ☕ Java Development Kit 8
GitHub
  • 📝 Notes
    • Algorithm
      • Algorithm - Bloom Filter
      • Algorithm - Disjoint Set
      • Algorithm - Fast Power
      • Algorithm - KMP
      • Algorithm - Monotonic Stack
      • Algorithm - RB-Tree
      • Algorithm - Regular Expression
      • Algorithm - Sliding Window
      • Online Judge - I/O
    • C++
      • C++ - Const
      • C++ File I/O
      • C++ - Object Layout
      • C++ - Operator Overload
      • C++ - Polymorphism
      • C++ STL algorithm
      • C++ STL map
      • C++ STL multimap
      • C++ STL priority_queue
      • C++ STL set
      • C++ STL string
      • C++ STL unordered_map
      • C++ STL vector
      • C++ - Smart Pointer
      • C++ - Template & Genericity
    • Compiler
      • ANTLR - Basic
      • Compiler - LLVM Architecture
      • Compiler - Multi-version GCC
    • Cryptography
      • Cryptography - Certbot
      • Cryptography - Digital Signature & PKCS #7
      • Cryptography - GPG
      • Cryptography - JWT
      • Cryptography - Keystore & Certificates
      • Cryptography - OAuth 2.0
      • Cryptography - Java 实现对称与非对称加密算法
      • Cryptography - TLS
    • DevOps
      • DevOps - Travis CI
    • Docker
      • Docker - Image & Storage Management
      • Docker - Image
      • Docker - Libcontainer
      • Docker - Multi-Arch Image
      • Docker - Multi-Stage Build
      • Docker - Network
      • Docker - Orchestration & Deployment
      • Docker - Overview
      • Docker - Service Building
      • Docker - Volume & Network Usage
      • Docker - Volume
      • Linux - Control Group
      • Linux - Namespace
    • Git
      • Git - Branch & Merge
      • Git - Cached
      • Git - Cherry Pick
      • Git - Commit
      • Git - Patch
      • Git - Proxy
      • Git - Rebase
      • Git - Reset
      • Git - Stash
      • Git - Theme for Git-Bash
    • Java
      • JVM - Synchronized
      • JVM - Volatile
      • Java - Annotation 注解
      • Java - BIO & NIO
      • Java - Class Path
      • Java - Condition and LockSupport
      • Java - Current Timestamp
      • Java - Deep Copy
      • Java - 运行环境配置
      • Java - Equals
      • Java - Exporting JAR
      • Java - Javadoc
      • Java - Lock
      • Java - Maven 项目构建工具
      • Java - References
      • Java - Reflection Mechanism
      • Java - String Split
      • Java - Thread Pool
      • Java - Thread
      • Tomcat - Class Loader
      • Tomcat - Container
    • Linux
      • addr2line
      • cut
      • df
      • du
      • fallocate
      • find
      • fio
      • grep
      • groupadd
      • gzip
      • head / tail
      • hexdump
      • iostat
      • iotop
      • kill
      • ldd
      • lsof
      • ltrace / strace
      • mpstat
      • netstat
      • nm
      • pidstat
      • pmap
      • readlink
      • readlink
      • rpm2cpio / rpm2archive
      • sort
      • tee
      • uniq
      • useradd
      • usermod
      • watch
      • wc
      • which
      • xargs
    • MS Office
      • MS Office - Add-in Dev
      • MS Office - Application
    • MySQL
      • InnoDB - Architecture
      • InnoDB - Backup
      • InnoDB - Checkpoint
      • InnoDB - Critical Features
      • InnoDB - Files
      • InnoDB - Index
      • InnoDB - Insert Buffer
      • InnoDB - Lock
      • InnoDB - Partition Table
      • InnoDB - Table Storage
      • MySQL - Server Configuration
      • MySQL - Storage Engine
    • Network
      • Network - ARP
      • Network - FTP
      • Network - GitHub Accelerating
      • HTTP - Message Format
      • HTTP - POST 提交表单的两种方式
      • Network - Proxy Server
      • Network - SCP
      • Network - SSH
      • Network - TCP Congestion Control
      • Network - TCP Connection Management
      • Network - TCP Flow Control
      • Network - TCP Retransmission
      • Network - Traceroute
      • Network - V2Ray
      • Network - WebSocket
      • Network - Windows 10 Mail APP
      • Network - frp
    • Operating System
      • Linux - Kernel Compilation
      • Linux - Multi-OS
      • Linux - Mutex & Condition
      • Linux - Operations
      • Linux: Package Manager
      • Linux - Process Manipulation
      • Linux - User ID
      • Linux - Execve
      • OS - Compile and Link
      • OS - Dynamic Linking
      • OS - ELF
      • Linux - Image
      • OS - Loading
      • OS - Shared Library Organization
      • OS - Static Linking
      • Syzkaller - Architecture
      • Syzkaller - Description Syntax
      • Syzkaller - Usage
      • Ubuntu - Desktop Recover (Python)
      • WSL: CentOS 8
    • Performance
      • Linux Performance - Perf Event
      • Linux Performance - Perf Record
      • Linux Performance - Perf Report
      • Linux Performance - Flame Graphs
      • Linux Performance - Off CPU Analyze
    • PostgreSQL
      • PostgreSQL - ANALYZE
      • PostgreSQL - Atomics
      • PostgreSQL - CREATE INDEX CONCURRENTLY
      • PostgreSQL - COPY FROM
      • PostgreSQL - COPY TO
      • PostgreSQL - Executor: Append
      • PostgreSQL - Executor: Group
      • PostgreSQL - Executor: Limit
      • PostgreSQL - Executor: Material
      • PostgreSQL - Executor: Nest Loop Join
      • PostgreSQL - Executor: Result
      • PostgreSQL - Executor: Sequential Scan
      • PostgreSQL - Executor: Sort
      • PostgreSQL - Executor: Unique
      • PostgreSQL - FDW Asynchronous Execution
      • PostgreSQL - GUC
      • PostgreSQL - Locking
      • PostgreSQL - LWLock
      • PostgreSQL - Multi Insert
      • PostgreSQL - Plan Hint GUC
      • PostgreSQL - Process Activity
      • PostgreSQL - Query Execution
      • PostgreSQL - Spinlock
      • PostgreSQL - Storage Management
      • PostgreSQL - VFD
      • PostgreSQL - WAL Insert
      • PostgreSQL - WAL Prefetch
    • Productivity
      • LaTeX
      • Venn Diagram
      • VuePress
    • Solidity
      • Solidity - ABI Specification
      • Solidity - Contracts
      • Solidity - Expressions and Control Structures
      • Solidity - Layout and Structure
      • Solidity - Remix IDE
      • Solidity - Slither
      • Solidity - Types
      • Solidity - Units and Globally Available Variables
    • Vue.js
      • Vue.js - Environment Variable
    • Web
      • Web - CORS
      • Web - OpenAPI Specification
    • Wireless
      • Wireless - WEP Cracking by Aircrack-ng
      • Wireless - WPS Cracking by Reaver
      • Wireless - wifiphisher

Web - OpenAPI Specification

Created by : Mr Dk.

2019 / 09 / 28 12:34

Nanjing, Jiangsu, China


Background

OpenAPI Specification (OAS),以前叫做 Swagger 标准,是用于描述 RESTful Web 服务的接口文件。可以对接口进行描述、可视化等等。在 2016 年从 Swagger 项目中独立出来称为独立项目。

版本:

  • 2017-07-26: OpenAPI 3.0.0+
  • 2014-09-08: Swagger 2.0
  • 2012-08-22: Swagger 1.1
  • ...

算是 RESTful 的世界标准?好吧,接触过的几个 RESTful 的应用一个都没有使用 OAS,但毕竟是 RESTful 领域中的官方标准了。最近又准备做一做 RESTful fuzzing,所以研究了一下 OAS 的文档并做一些梳理。


Concept

OpenAPI 文档中经常用到一些概念

OpenAPI Document

用于形容 API 的文档

Path Templating

使用 {} 来标识路径中可被替换的部分

Media Types

服从 RFC6838

  • text/plain; charset=utf-8
  • application/json
  • ...

HTTP Status Code

服从 RFC7231

Specification Versions

一般来说是 OAS 3.*.*

在 API 文档中有一个字段需要注明标准的版本

Format

JSON 格式或 YAML 格式

大小写除非特殊说明,否则都是敏感的

  • 这个只要平时做事足够规范,取名足够合理,通常不会有什么问题

Documentation Structure

根 API 文档建议命名为 openapi.json 或 openapi.yaml


Schema

OpenAPI Object

OpenAPI 文档的 root document:

Field NameTypeDescription
openapistringOAS version
infoInfo ObjectMetadata of API (描述 API 的具体信息,之后展开)
servers[ Server Object ]服务器的连接信息
pathsPaths ObjectAPI 路径
componentsComponents Object该 OAS 中预定义的一些 Schema
security[ Security Requirement Object ]安全机制
tags[ Tag Object ]额外的 metadata
externalDocsExternal Documentation Object额外的文档

接下来先解决其中的几个简单的对象:

Server Object

Field NameTypeDescription
urlstring指向目标服务器的 URL
descriptionstring用于描述这个服务器 (似乎还支持 Markdown)
variablesMap<string, Server Variable Object>变量名 + 变量值,用于替换 URL 中的 path template

Server Variable Object

Field NamesTypeDescription
enum[ string ]变量的所有可选值
default (REQUIRED)string变量默认值
descriptionstringMarkdown 支持的哦
{
  "servers": [
    {
      "url": "https://{username}.gigantic-server.com:{port}/{basePath}",
      "description": "The production API server",
      "variables": {
        "username": {
          "default": "demo",
          "description": "this value is assigned by the service provider, in this example `gigantic-server.com`"
        },
        "port": {
          "enum": ["8443", "443"],
          "default": "8443"
        },
        "basePath": {
          "default": "v2"
        }
      }
    }
  ]
}

Path Object

Field NameTypeDescription
/{path}Path Item ObjectEndpoint 的相对路径

Path Item Object

Field NameTypeDescription
$refstring该对象可以被定义在外部
summarystring
descriptionstringMarkdown ✔
getOperation Object定义了该路径下 GET 的操作
putOperation Object定义了该路径下 PUT 的操作
postOperation Object定义了该路径下 POST 的操作
deleteOperation Object定义了该路径下 DELETE 的操作
optionsOperation Object定义了该路径下 OPTIONS 的操作
headOperation Object定义了该路径下 HEAD 的操作
patchOperation Object定义了该路径下 PATCH 的操作
traceOperation Object定义了该路径下 TRACE 的操作
servers[ Server Object ]可被替换的服务器,用于服务该路径的所有操作
parameters[ Parameter Object | Reference Object ]在以上操作中可被使用的参数
{
  "/pets": {
    "get": {},
    "parameters": [{}]
  }
}

Operation Object

描述某一路径上的某一 API:

Field NameTypeDescription
tags[ string ]标签,用于 API 文档控制
summarystring
descriptionstring
externalDocsExternal Documentation Object额外的外部文档
operationIdstring用于识别这个操作的唯一标识
parameters[ Parameter Object | Reference Object ]在本操作中可被使用的参数
requestBody[ Request Body Object | Reference Object ]RFC7231 HTTP 1.1 标准
responsesResponses Object所有可能的回应
callBacksMap<string, Callback Object | Reference Object>与 Operation 相关的回调
deprecatedboolean
security[ Security Requirement Object ]
servers[ Server Object ]会覆盖 root document 中的 servers
{
  "tags": ["pet"],
  "summary": "Updates a pet in the store with form data",
  "operationId": "updatePetWithForm",
  "parameters": [{}],
  "requestBody": {},
  "responses": {},
  "security": [
    {
      "petstore_auth": ["write:pets", "read:pets"]
    }
  ]
}

Media Type Object

Field NameTypeDescirption
schemaSchema Object | Reference Object定义 request, response, parameter 内容
example
examplesMap<string, Example Object | Reference Object>
encodingMap<string, Encoding Object>The key, being the property name, MUST exist in the schema as a property
{
  "application/json": {
    "schema": {
      "$ref": "#/components/schemas/Pet"
    },
    "examples": {
      "cat": {
        "summary": "An example of a cat",
        "value": {
          "name": "Fluffy",
          "petType": "Cat",
          "color": "White",
          "gender": "male",
          "breed": "Persian"
        }
      },
      "dog": {
        "summary": "An example of a dog with a cat's name",
        "value": {
          "name": "Puma",
          "petType": "Dog",
          "color": "Black",
          "gender": "Female",
          "breed": "Mixed"
        }
      },
      "frog": {
        "$ref": "#/components/examples/frog-example"
      }
    }
  }
}

Request Body Object

Field NameTypeDescription
descriptionstring
content (REQUIRED)Map<string, Media Type Object>定义了对于每种请求 Media Type 的处理
requiredboolean该请求体是否必须存在于请求中
{
  "description": "user to add to the system",
  "content": {
    "application/json": {},
    "application/xml": {},
    "text/plain": {},
    "*/*": {}
  }
}

Responses Object

Field NameTypeDescription
defaultResponse Object | Reference Object对未指定的 HTTP 请求码的默认操作

Response Object

Field NameTypeDescription
descriptionstring
headersMap<string, Header Object | Reference Object>响应头部?
contentMap<string, Media Type Object>对于特定 Media Type 的响应内容
linksMap<string, Link Object | Reference Object>从 response 中可以被继续运行的 operation
{
  "responses": {
    "200": {
      "description": "Pet updated.",
      "content": {
        "application/json": {},
        "application/xml": {}
      }
    },
    "405": {
      "description": "Method Not Allowed",
      "content": {
        "application/json": {},
        "application/xml": {}
      }
    },
    "default": {
      "description": "Unexpected error",
      "content": {
        "application/json": {}
      }
    }
  }
}

Parameter Object

定义某一个操作需要使用的参数,参数由 name 和 location 唯一确定。Location 是参数在请求中的位置:

  • path - 参数值是操作 URL 的一部分 - /items/{itemId}
  • query - 参数值是附加在 URL 尾部 - /items?id=###
  • header - 参数值位于请求头中
  • cookie - 参数位于 cookie 中
Field NameTypeDescription
name (REQUIRED)string参数名
in (REQUIRED)string参数的位置 (location)
descriptionstring
requiredboolean
deprecatedboolean
allEmptyValueboolean
stylestring决定参数如何被序列化
explodeboolean如果为 true,参数值会将 array 中的每一个值和对象中的每对 key-pair 分开
allowReservedboolean决定参数中是否允许 RFC3986 中定义的保留字符
schemaSchema Object | Reference Object定义了参数的类型
example
examplesMap<string, Example Object | Reference Object>
contentMap<string, Media Type Object>MUST only contain one entry && A parameter MUST contain either a schema property, or a content property, but not both

带 schema 的例子:

{
  "name": "id",
  "in": "query",
  "description": "ID of the object to fetch",
  "required": false,
  "schema": {
    "type": "array",
    "items": {
      "type": "string"
    }
  },
  "style": "form",
  "explode": true
}

带 content 的例子:

{
  "in": "query",
  "name": "coordinates",
  "content": {
    "application/json": {
      "schema": {
        "type": "object",
        "required": ["lat", "long"],
        "properties": {
          "lat": {
            "type": "number"
          },
          "long": {
            "type": "number"
          }
        }
      }
    }
  }
}

Schema Object

定义输入/输出的数据类型。可以是原生数据类型,也可以是对象或数组:

Field NameTypeDescription
nullableboolean是否允许空值
discriminatorDiscriminator支持多态?
readOnlyboolean
writeOnlyboolean
xmlXML Object
externalDocsExternal Documentation Object
example
deprecatedboolean
{
  "type": "object",
  "properties": {
    "id": {
      "type": "integer",
      "format": "int64"
    },
    "name": {
      "type": "string"
    }
  },
  "required": ["name"],
  "example": {
    "name": "Puma",
    "id": 1
  }
}

嗯???咋例子和表格对不上呢? 🤨

Reference Object

Field NameTypeDescription
$ref (REQUIRED)stringThe reference string
{
  "$ref": "#/components/schemas/Pet"
}

Components Object

定义 OAS 中的一些可重用对象:

Field NameTypeDescription
schemasMap<string, Schema Object | Reference Object>
responsesMap<string, Response Object | Reference Object>
parametersMap<string, Parameter Object | Reference Object>
examplesMap<string, Example Object | Reference Object>
requestBodiesMap<string, Request Body Object | Reference Object>
headersMap<string, Header Object | Reference Object>
securitySchemesMap<string, Security Scheme Object | Reference Object>
linksMap<string, Link Object | Reference Object>
callbacksMap<string, Callback Object | Reference Object>

Tag Object

Field NameTypeDescription
namestring
descriptionstring
externalDocsExternal Documentation Object
{
  "name": "pet",
  "description": "Pets operations"
}

External Documentation Object

Field NameTypeDescription
descriptionstring
urlstringThe URL of the target documentation
{
  "description": "Find more info here",
  "url": "https://example.com"
}

Info Object

Field NameTypeDescription
title (REQUIRED)stringThe title of the application
descriptionstring对于 app 的描述
termsOfServicestringAPI Terms of Services 的 URL
contactContact Object联系信息
licenseLicense ObjectLicense 信息
version (REQUIRED)stringOpenAPI 文档的版本 (不是 OAS 的版本)
{
  "title": "Sample Pet Store App",
  "description": "This is a sample server for a pet store.",
  "termsOfService": "http://example.com/terms/",
  "contact": {
    "name": "API Support",
    "url": "http://www.example.com/support",
    "email": "support@example.com"
  },
  "license": {
    "name": "Apache 2.0",
    "url": "https://www.apache.org/licenses/LICENSE-2.0.html"
  },
  "version": "1.0.1"
}

Contact Object

Field NameTypeDescription
namestring联系人或组织的名称
urlstring指向信息的 URL
emailstring联系人或组织的 E-mail

License Object

Field NameTypeDescription
name (REQUIRED)stringAPI license 的名称
urlstringAPI license 的 URL

Reference

https://swagger.io/specification/


Edit this page on GitHub
Prev
Web - CORS