├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE ├── README.md ├── data ├── v2 │ ├── k8s.json │ ├── petstore-simple.yaml │ ├── petstore_minimal.yaml │ ├── rocks.yaml │ └── uber.yaml └── v3.0 │ ├── api-with-examples.yaml │ ├── callback-example.yaml │ ├── link-example.yaml │ ├── petstore-expanded.yaml │ ├── petstore.yaml │ └── uspto.yaml ├── examples └── printer.rs ├── rustfmt.toml └── src ├── error.rs ├── lib.rs ├── v2 ├── mod.rs └── schema.rs └── v3_0 ├── components.rs ├── extension.rs ├── mod.rs └── schema.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | *.bk 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # required because of tarpaulin dependency 2 | sudo: required 3 | 4 | language: rust 5 | 6 | matrix: 7 | fast_finish: true 8 | include: 9 | - rust: nightly 10 | - rust: beta 11 | - rust: stable 12 | 13 | # only build pushes to master 14 | # prs are build separately 15 | # https://docs.travis-ci.com/user/pull-requests/#how-pull-requests-are-built 16 | branches: 17 | only: 18 | - master 19 | 20 | install: 21 | - | 22 | if [[ "$TRAVIS_RUST_VERSION" == stable ]]; then 23 | cargo install cargo-tarpaulin -f 24 | rustup component add rustfmt 25 | fi 26 | script: 27 | - | 28 | if [[ "$TRAVIS_RUST_VERSION" == stable ]]; then 29 | cargo fmt --all -- --check 30 | fi 31 | - cargo test 32 | 33 | # Cache `cargo install`ed tools, but don't cache the project's `target` 34 | # directory (which ends up over-caching and filling all disk space!) 35 | # https://levans.fr/rust_travis_cache.html 36 | cache: 37 | directories: 38 | - $HOME/.cargo 39 | - $HOME/.rustup 40 | 41 | before_cache: 42 | # But don't cache the cargo registry 43 | - rm -rf /home/travis/.cargo/registry 44 | # Travis can't cache files that are not readable by "others" 45 | - chmod -R a+r $HOME/.cargo 46 | 47 | addons: 48 | apt: 49 | packages: 50 | # required by tarpaulin code coverage tool 51 | - libssl-dev 52 | 53 | after_success: 54 | # report coverage to coveralls 55 | # see https://github.com/xd009642/tarpaulin for more information 56 | - '[ $TRAVIS_EVENT_TYPE != "cron" ] && 57 | [ $TRAVIS_RUST_VERSION = stable ] && 58 | [ $TRAVIS_BRANCH = master ] && 59 | [ $TRAVIS_PULL_REQUEST = false ] && 60 | cargo tarpaulin --ciserver travis-ci --coveralls $TRAVIS_JOB_ID || true' 61 | - '[ $TRAVIS_RUST_VERSION = stable ] && 62 | [ $TRAVIS_BRANCH = master ] && 63 | [ $TRAVIS_PULL_REQUEST = false ] 64 | && cargo doc --no-deps && 65 | echo "" > target/doc/index.html' 66 | 67 | deploy: 68 | provider: pages 69 | skip-cleanup: true 70 | github-token: $GH_TOKEN 71 | local-dir: target/doc 72 | keep-history: false 73 | on: 74 | branch: master 75 | condition: $TRAVIS_RUST_VERSION = stable 76 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 0.2 2 | 3 | * expose security definition as an enum type 4 | * expose schema types which define `parameters` with new `ParameterOrRef` type 5 | * Adds License object 6 | * Adds Contact object 7 | * Derives Default for all structs 8 | * Derives Clone for all structs 9 | * Changes the order of the output to be more similar to OpenAPI examples 10 | * switch to 2018 edition 11 | * swap error_chain for failure crate 12 | 13 | # 0.1.5 14 | 15 | * expose other schema types as public interfaces 16 | * re-export Result and ResultExt as top level interfaces 17 | 18 | # 0.1.4 19 | 20 | * added operational `parameters` field to `Operations` object 21 | 22 | # 0.1.3 23 | 24 | * added optional `required` and `enum_values` fields to `Schema` object 25 | 26 | # 0.1.2 27 | 28 | * added optional `format` fields to `Parameter` object 29 | 30 | # 0.1.1 31 | 32 | * added optional `summary` field to `Operation` object 33 | * made schemes and tags optional fields on `Operation` object 34 | 35 | # 0.1.0 36 | 37 | * initial release 38 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "openapi" 3 | version = "0.1.5" 4 | authors = ["softprops "] 5 | description = "Rust bindings for openapi schemas" 6 | documentation = "https://softprops.github.io/openapi" 7 | homepage = "https://github.com/softprops/openapi" 8 | repository = "https://github.com/softprops/openapi" 9 | keywords = ["openapi", "swagger"] 10 | license = "MIT" 11 | edition = "2018" 12 | 13 | [dependencies] 14 | failure = "0.1" 15 | semver = "0.11" 16 | serde = { version = "1.0", features = ["derive"] } 17 | serde_json = "1.0" 18 | serde_yaml = "0.8" 19 | thiserror = "1.0" 20 | url = { version = "2.0", features = ["serde"] } 21 | 22 | [dev-dependencies] 23 | anyhow = "1.0" 24 | pretty_assertions = "0.6" 25 | serde_test = "1.0.117" 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 Doug Tangren 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # open api [![Build Status](https://travis-ci.org/softprops/openapi.svg?branch=master)](https://travis-ci.org/softprops/openapi) [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE) [![crates.io](http://meritbadge.herokuapp.com/openapi)](https://crates.io/crates/openapi) 2 | 3 | > Rust crate for serializing and deserializing [open api](http://swagger.io/specification/) documents 4 | 5 | [Documentation](https://softprops.github.io/openapi) 6 | 7 | ## install 8 | 9 | add the following to your `Cargo.toml` file 10 | 11 | ```toml 12 | [dependencies] 13 | openapi = "0.1" 14 | ``` 15 | 16 | ## usage 17 | 18 | ```rust 19 | extern crate openapi; 20 | 21 | fn main() { 22 | match openapi::from_path("path/to/openapi.yaml") { 23 | Ok(spec) => println!("spec: {:?}", spec), 24 | Err(err) => println!("error: {}", err) 25 | } 26 | } 27 | ``` 28 | 29 | Doug Tangren (softprops) 2017 30 | -------------------------------------------------------------------------------- /data/v2/petstore-simple.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | swagger: "2.0" 3 | info: 4 | version: "1.0.0" 5 | title: "Swagger Petstore" 6 | description: "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification" 7 | termsOfService: "http://swagger.io/terms/" 8 | contact: 9 | name: "Swagger API Team" 10 | license: 11 | name: "MIT" 12 | host: "petstore.swagger.io" 13 | basePath: "/api" 14 | schemes: 15 | - "http" 16 | consumes: 17 | - "application/json" 18 | produces: 19 | - "application/json" 20 | paths: 21 | /pets: 22 | get: 23 | description: "Returns all pets from the system that the user has access to" 24 | operationId: "findPets" 25 | produces: 26 | - "application/json" 27 | - "application/xml" 28 | - "text/xml" 29 | - "text/html" 30 | parameters: 31 | - 32 | name: "tags" 33 | in: "query" 34 | description: "tags to filter by" 35 | required: false 36 | type: "array" 37 | items: 38 | type: "string" 39 | collectionFormat: "csv" 40 | - 41 | name: "limit" 42 | in: "query" 43 | description: "maximum number of results to return" 44 | required: false 45 | type: "integer" 46 | format: "int32" 47 | responses: 48 | "200": 49 | description: "pet response" 50 | schema: 51 | type: "array" 52 | items: 53 | $ref: "#/definitions/Pet" 54 | default: 55 | description: "unexpected error" 56 | schema: 57 | $ref: "#/definitions/ErrorModel" 58 | post: 59 | description: "Creates a new pet in the store. Duplicates are allowed" 60 | operationId: "addPet" 61 | produces: 62 | - "application/json" 63 | parameters: 64 | - 65 | name: "pet" 66 | in: "body" 67 | description: "Pet to add to the store" 68 | required: true 69 | schema: 70 | $ref: "#/definitions/NewPet" 71 | responses: 72 | "200": 73 | description: "pet response" 74 | schema: 75 | $ref: "#/definitions/Pet" 76 | default: 77 | description: "unexpected error" 78 | schema: 79 | $ref: "#/definitions/ErrorModel" 80 | /pets/{id}: 81 | get: 82 | description: "Returns a user based on a single ID, if the user does not have access to the pet" 83 | operationId: "findPetById" 84 | produces: 85 | - "application/json" 86 | - "application/xml" 87 | - "text/xml" 88 | - "text/html" 89 | parameters: 90 | - 91 | name: "id" 92 | in: "path" 93 | description: "ID of pet to fetch" 94 | required: true 95 | type: "integer" 96 | format: "int64" 97 | responses: 98 | "200": 99 | description: "pet response" 100 | schema: 101 | $ref: "#/definitions/Pet" 102 | default: 103 | description: "unexpected error" 104 | schema: 105 | $ref: "#/definitions/ErrorModel" 106 | delete: 107 | description: "deletes a single pet based on the ID supplied" 108 | operationId: "deletePet" 109 | parameters: 110 | - 111 | name: "id" 112 | in: "path" 113 | description: "ID of pet to delete" 114 | required: true 115 | type: "integer" 116 | format: "int64" 117 | responses: 118 | "204": 119 | description: "pet deleted" 120 | default: 121 | description: "unexpected error" 122 | schema: 123 | $ref: "#/definitions/ErrorModel" 124 | definitions: 125 | Pet: 126 | type: "object" 127 | allOf: 128 | - 129 | $ref: "#/definitions/NewPet" 130 | - 131 | required: 132 | - "id" 133 | properties: 134 | id: 135 | type: "integer" 136 | format: "int64" 137 | NewPet: 138 | type: "object" 139 | required: 140 | - "name" 141 | properties: 142 | name: 143 | type: "string" 144 | tag: 145 | type: "string" 146 | ErrorModel: 147 | type: "object" 148 | required: 149 | - "code" 150 | - "message" 151 | properties: 152 | code: 153 | type: "integer" 154 | format: "int32" 155 | message: 156 | type: "string" 157 | 158 | -------------------------------------------------------------------------------- /data/v2/petstore_minimal.yaml: -------------------------------------------------------------------------------- 1 | swagger: "2.0" 2 | info: 3 | version: "1.0.0" 4 | title: "Swagger Petstore" 5 | description: "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification" 6 | termsOfService: "http://swagger.io/terms/" 7 | contact: 8 | name: "Swagger API Team" 9 | license: 10 | name: "MIT" 11 | host: "petstore.swagger.io" 12 | basePath: "/api" 13 | schemes: 14 | - "http" 15 | consumes: 16 | - "application/json" 17 | produces: 18 | - "application/json" 19 | paths: 20 | /pets: 21 | get: 22 | description: "Returns all pets from the system that the user has access to" 23 | produces: 24 | - "application/json" 25 | responses: 26 | "200": 27 | description: "A list of pets." 28 | schema: 29 | type: "array" 30 | items: 31 | $ref: "#/definitions/Pet" 32 | definitions: 33 | Pet: 34 | type: "object" 35 | required: 36 | - "id" 37 | - "name" 38 | properties: 39 | id: 40 | type: "integer" 41 | format: "int64" 42 | name: 43 | type: "string" 44 | tag: 45 | type: "string" -------------------------------------------------------------------------------- /data/v2/rocks.yaml: -------------------------------------------------------------------------------- 1 | swagger: "2.0" 2 | info: 3 | description: "My service rocks." 4 | version: "1.0.0" 5 | title: SOA Resource 6 | termsOfService: https://github.com/mdsol/resource_rocks 7 | schemes: 8 | - https 9 | consumes: 10 | - application/json 11 | produces: 12 | - application/json 13 | 14 | paths: 15 | /v1/resource: 16 | get: 17 | description: "A filtered collection of resource " 18 | operationId: getResource 19 | parameters: 20 | - $ref: "#/parameters/per_page" 21 | 22 | responses: 23 | "404": 24 | description: Resource not found 25 | 26 | parameters: 27 | per_page: 28 | in: query 29 | name: per_page 30 | description: The number of results per page 31 | required: false 32 | type: integer 33 | default: 25 34 | -------------------------------------------------------------------------------- /data/v2/uber.yaml: -------------------------------------------------------------------------------- 1 | # this is an example of the Uber API 2 | # as a demonstration of an API spec in YAML 3 | swagger: "2.0" 4 | info: 5 | title: Uber API 6 | description: Move your app forward with the Uber API 7 | version: "1.0.0" 8 | # the domain of the service 9 | host: api.uber.com 10 | # array of all schemes that your API supports 11 | schemes: 12 | - https 13 | # will be prefixed to all paths 14 | basePath: /v1 15 | securityDefinitions: 16 | apikey: 17 | type: apiKey 18 | name: server_token 19 | in: query 20 | produces: 21 | - application/json 22 | paths: 23 | /products: 24 | get: 25 | summary: Product Types 26 | description: 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. 27 | parameters: 28 | - name: latitude 29 | in: query 30 | description: Latitude component of location. 31 | required: true 32 | type: number 33 | format: double 34 | - name: longitude 35 | in: query 36 | description: Longitude component of location. 37 | required: true 38 | type: number 39 | format: double 40 | security: 41 | - apikey: [] 42 | tags: 43 | - Products 44 | responses: 45 | "200": 46 | description: An array of products 47 | schema: 48 | type: array 49 | items: 50 | $ref: '#/definitions/Product' 51 | default: 52 | description: Unexpected error 53 | schema: 54 | $ref: '#/definitions/Error' 55 | /estimates/price: 56 | get: 57 | summary: Price Estimates 58 | description: 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.

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. 59 | parameters: 60 | - name: start_latitude 61 | in: query 62 | description: Latitude component of start location. 63 | required: true 64 | type: number 65 | format: double 66 | - name: start_longitude 67 | in: query 68 | description: Longitude component of start location. 69 | required: true 70 | type: number 71 | format: double 72 | - name: end_latitude 73 | in: query 74 | description: Latitude component of end location. 75 | required: true 76 | type: number 77 | format: double 78 | - name: end_longitude 79 | in: query 80 | description: Longitude component of end location. 81 | required: true 82 | type: number 83 | format: double 84 | tags: 85 | - Estimates 86 | responses: 87 | "200": 88 | description: An array of price estimates by product 89 | schema: 90 | type: array 91 | items: 92 | $ref: '#/definitions/PriceEstimate' 93 | default: 94 | description: Unexpected error 95 | schema: 96 | $ref: '#/definitions/Error' 97 | /estimates/time: 98 | get: 99 | summary: Time Estimates 100 | description: 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. 101 | parameters: 102 | - name: start_latitude 103 | in: query 104 | description: Latitude component of start location. 105 | required: true 106 | type: number 107 | format: double 108 | - name: start_longitude 109 | in: query 110 | description: Longitude component of start location. 111 | required: true 112 | type: number 113 | format: double 114 | - name: customer_uuid 115 | in: query 116 | type: string 117 | format: uuid 118 | description: Unique customer identifier to be used for experience customization. 119 | - name: product_id 120 | in: query 121 | type: string 122 | description: Unique identifier representing a specific product for a given latitude & longitude. 123 | tags: 124 | - Estimates 125 | responses: 126 | "200": 127 | description: An array of products 128 | schema: 129 | type: array 130 | items: 131 | $ref: '#/definitions/Product' 132 | default: 133 | description: Unexpected error 134 | schema: 135 | $ref: '#/definitions/Error' 136 | /me: 137 | get: 138 | summary: User Profile 139 | description: The User Profile endpoint returns information about the Uber user that has authorized with the application. 140 | tags: 141 | - User 142 | responses: 143 | "200": 144 | description: Profile information for a user 145 | schema: 146 | $ref: '#/definitions/Profile' 147 | default: 148 | description: Unexpected error 149 | schema: 150 | $ref: '#/definitions/Error' 151 | /history: 152 | get: 153 | summary: User Activity 154 | description: 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.

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. 155 | parameters: 156 | - name: offset 157 | in: query 158 | type: integer 159 | format: int32 160 | description: Offset the list of returned results by this amount. Default is zero. 161 | - name: limit 162 | in: query 163 | type: integer 164 | format: int32 165 | description: Number of items to retrieve. Default is 5, maximum is 100. 166 | tags: 167 | - User 168 | responses: 169 | "200": 170 | description: History information for the given user 171 | schema: 172 | $ref: '#/definitions/Activities' 173 | default: 174 | description: Unexpected error 175 | schema: 176 | $ref: '#/definitions/Error' 177 | definitions: 178 | Product: 179 | properties: 180 | product_id: 181 | type: string 182 | description: 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. 183 | description: 184 | type: string 185 | description: Description of product. 186 | display_name: 187 | type: string 188 | description: Display name of product. 189 | capacity: 190 | type: integer 191 | description: Capacity of product. For example, 4 people. 192 | image: 193 | type: string 194 | description: Image URL representing the product. 195 | ProductList: 196 | properties: 197 | products: 198 | description: Contains the list of products 199 | type: array 200 | items: 201 | $ref: "#/definitions/Product" 202 | PriceEstimate: 203 | properties: 204 | product_id: 205 | type: string 206 | description: 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 207 | currency_code: 208 | type: string 209 | description: "[ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code." 210 | display_name: 211 | type: string 212 | description: Display name of product. 213 | estimate: 214 | type: string 215 | description: 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. 216 | low_estimate: 217 | type: number 218 | description: Lower bound of the estimated price. 219 | high_estimate: 220 | type: number 221 | description: Upper bound of the estimated price. 222 | surge_multiplier: 223 | type: number 224 | description: Expected surge multiplier. Surge is active if surge_multiplier is greater than 1. Price estimate already factors in the surge multiplier. 225 | Profile: 226 | properties: 227 | first_name: 228 | type: string 229 | description: First name of the Uber user. 230 | last_name: 231 | type: string 232 | description: Last name of the Uber user. 233 | email: 234 | type: string 235 | description: Email address of the Uber user 236 | picture: 237 | type: string 238 | description: Image URL of the Uber user. 239 | promo_code: 240 | type: string 241 | description: Promo code of the Uber user. 242 | Activity: 243 | properties: 244 | uuid: 245 | type: string 246 | description: Unique identifier for the activity 247 | Activities: 248 | properties: 249 | offset: 250 | type: integer 251 | format: int32 252 | description: Position in pagination. 253 | limit: 254 | type: integer 255 | format: int32 256 | description: Number of items to retrieve (100 max). 257 | count: 258 | type: integer 259 | format: int32 260 | description: Total number of items available. 261 | history: 262 | type: array 263 | items: 264 | $ref: '#/definitions/Activity' 265 | Error: 266 | properties: 267 | code: 268 | type: integer 269 | format: int32 270 | message: 271 | type: string 272 | fields: 273 | type: string 274 | -------------------------------------------------------------------------------- /data/v3.0/api-with-examples.yaml: -------------------------------------------------------------------------------- 1 | openapi: "3.0.0" 2 | info: 3 | title: Simple API overview 4 | version: v2 5 | paths: 6 | /: 7 | get: 8 | operationId: listVersionsv2 9 | summary: List API versions 10 | responses: 11 | '200': 12 | description: |- 13 | 200 response 14 | content: 15 | application/json: 16 | examples: 17 | foo: 18 | value: { 19 | "versions": [ 20 | { 21 | "status": "CURRENT", 22 | "updated": "2011-01-21T11:33:21Z", 23 | "id": "v2.0", 24 | "links": [ 25 | { 26 | "href": "http://127.0.0.1:8774/v2/", 27 | "rel": "self" 28 | } 29 | ] 30 | }, 31 | { 32 | "status": "EXPERIMENTAL", 33 | "updated": "2013-07-23T11:33:21Z", 34 | "id": "v3.0", 35 | "links": [ 36 | { 37 | "href": "http://127.0.0.1:8774/v3/", 38 | "rel": "self" 39 | } 40 | ] 41 | } 42 | ] 43 | } 44 | '300': 45 | description: |- 46 | 300 response 47 | content: 48 | application/json: 49 | examples: 50 | foo: 51 | value: | 52 | { 53 | "versions": [ 54 | { 55 | "status": "CURRENT", 56 | "updated": "2011-01-21T11:33:21Z", 57 | "id": "v2.0", 58 | "links": [ 59 | { 60 | "href": "http://127.0.0.1:8774/v2/", 61 | "rel": "self" 62 | } 63 | ] 64 | }, 65 | { 66 | "status": "EXPERIMENTAL", 67 | "updated": "2013-07-23T11:33:21Z", 68 | "id": "v3.0", 69 | "links": [ 70 | { 71 | "href": "http://127.0.0.1:8774/v3/", 72 | "rel": "self" 73 | } 74 | ] 75 | } 76 | ] 77 | } 78 | /v2: 79 | get: 80 | operationId: getVersionDetailsv2 81 | summary: Show API version details 82 | responses: 83 | '200': 84 | description: |- 85 | 200 response 86 | content: 87 | application/json: 88 | examples: 89 | foo: 90 | value: { 91 | "version": { 92 | "status": "CURRENT", 93 | "updated": "2011-01-21T11:33:21Z", 94 | "media-types": [ 95 | { 96 | "base": "application/xml", 97 | "type": "application/vnd.openstack.compute+xml;version=2" 98 | }, 99 | { 100 | "base": "application/json", 101 | "type": "application/vnd.openstack.compute+json;version=2" 102 | } 103 | ], 104 | "id": "v2.0", 105 | "links": [ 106 | { 107 | "href": "http://127.0.0.1:8774/v2/", 108 | "rel": "self" 109 | }, 110 | { 111 | "href": "http://docs.openstack.org/api/openstack-compute/2/os-compute-devguide-2.pdf", 112 | "type": "application/pdf", 113 | "rel": "describedby" 114 | }, 115 | { 116 | "href": "http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl", 117 | "type": "application/vnd.sun.wadl+xml", 118 | "rel": "describedby" 119 | }, 120 | { 121 | "href": "http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl", 122 | "type": "application/vnd.sun.wadl+xml", 123 | "rel": "describedby" 124 | } 125 | ] 126 | } 127 | } 128 | '203': 129 | description: |- 130 | 203 response 131 | content: 132 | application/json: 133 | examples: 134 | foo: 135 | value: { 136 | "version": { 137 | "status": "CURRENT", 138 | "updated": "2011-01-21T11:33:21Z", 139 | "media-types": [ 140 | { 141 | "base": "application/xml", 142 | "type": "application/vnd.openstack.compute+xml;version=2" 143 | }, 144 | { 145 | "base": "application/json", 146 | "type": "application/vnd.openstack.compute+json;version=2" 147 | } 148 | ], 149 | "id": "v2.0", 150 | "links": [ 151 | { 152 | "href": "http://23.253.228.211:8774/v2/", 153 | "rel": "self" 154 | }, 155 | { 156 | "href": "http://docs.openstack.org/api/openstack-compute/2/os-compute-devguide-2.pdf", 157 | "type": "application/pdf", 158 | "rel": "describedby" 159 | }, 160 | { 161 | "href": "http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl", 162 | "type": "application/vnd.sun.wadl+xml", 163 | "rel": "describedby" 164 | } 165 | ] 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /data/v3.0/callback-example.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | title: Callback Example 4 | version: 1.0.0 5 | paths: 6 | /streams: 7 | post: 8 | description: subscribes a client to receive out-of-band data 9 | parameters: 10 | - name: callbackUrl 11 | in: query 12 | required: true 13 | description: | 14 | the location where data will be sent. Must be network accessible 15 | by the source server 16 | schema: 17 | type: string 18 | format: uri 19 | example: https://tonys-server.com 20 | responses: 21 | '201': 22 | description: subscription successfully created 23 | content: 24 | application/json: 25 | schema: 26 | description: subscription information 27 | required: 28 | - subscriptionId 29 | properties: 30 | subscriptionId: 31 | description: this unique identifier allows management of the subscription 32 | type: string 33 | example: 2531329f-fb09-4ef7-887e-84e648214436 34 | callbacks: 35 | # the name `onData` is a convenience locator 36 | onData: 37 | # when data is sent, it will be sent to the `callbackUrl` provided 38 | # when making the subscription PLUS the suffix `/data` 39 | '{$request.query.callbackUrl}/data': 40 | post: 41 | requestBody: 42 | description: subscription payload 43 | content: 44 | application/json: 45 | schema: 46 | properties: 47 | timestamp: 48 | type: string 49 | format: date-time 50 | userData: 51 | type: string 52 | responses: 53 | '202': 54 | description: | 55 | Your server implementation should return this HTTP status code 56 | if the data was received successfully 57 | '204': 58 | description: | 59 | Your server should return this HTTP status code if no longer interested 60 | in further updates 61 | -------------------------------------------------------------------------------- /data/v3.0/link-example.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | title: Link Example 4 | version: 1.0.0 5 | paths: 6 | /2.0/users/{username}: 7 | get: 8 | operationId: getUserByName 9 | parameters: 10 | - name: username 11 | in: path 12 | required: true 13 | schema: 14 | type: string 15 | responses: 16 | '200': 17 | description: The User 18 | content: 19 | application/json: 20 | schema: 21 | $ref: '#/components/schemas/user' 22 | links: 23 | userRepositories: 24 | $ref: '#/components/links/UserRepositories' 25 | /2.0/repositories/{username}: 26 | get: 27 | operationId: getRepositoriesByOwner 28 | parameters: 29 | - name: username 30 | in: path 31 | required: true 32 | schema: 33 | type: string 34 | responses: 35 | '200': 36 | description: repositories owned by the supplied user 37 | content: 38 | application/json: 39 | schema: 40 | type: array 41 | items: 42 | $ref: '#/components/schemas/repository' 43 | links: 44 | userRepository: 45 | $ref: '#/components/links/UserRepository' 46 | /2.0/repositories/{username}/{slug}: 47 | get: 48 | operationId: getRepository 49 | parameters: 50 | - name: username 51 | in: path 52 | required: true 53 | schema: 54 | type: string 55 | - name: slug 56 | in: path 57 | required: true 58 | schema: 59 | type: string 60 | responses: 61 | '200': 62 | description: The repository 63 | content: 64 | application/json: 65 | schema: 66 | $ref: '#/components/schemas/repository' 67 | links: 68 | repositoryPullRequests: 69 | $ref: '#/components/links/RepositoryPullRequests' 70 | /2.0/repositories/{username}/{slug}/pullrequests: 71 | get: 72 | operationId: getPullRequestsByRepository 73 | parameters: 74 | - name: username 75 | in: path 76 | required: true 77 | schema: 78 | type: string 79 | - name: slug 80 | in: path 81 | required: true 82 | schema: 83 | type: string 84 | - name: state 85 | in: query 86 | schema: 87 | type: string 88 | enum: 89 | - open 90 | - merged 91 | - declined 92 | responses: 93 | '200': 94 | description: an array of pull request objects 95 | content: 96 | application/json: 97 | schema: 98 | type: array 99 | items: 100 | $ref: '#/components/schemas/pullrequest' 101 | /2.0/repositories/{username}/{slug}/pullrequests/{pid}: 102 | get: 103 | operationId: getPullRequestsById 104 | parameters: 105 | - name: username 106 | in: path 107 | required: true 108 | schema: 109 | type: string 110 | - name: slug 111 | in: path 112 | required: true 113 | schema: 114 | type: string 115 | - name: pid 116 | in: path 117 | required: true 118 | schema: 119 | type: string 120 | responses: 121 | '200': 122 | description: a pull request object 123 | content: 124 | application/json: 125 | schema: 126 | $ref: '#/components/schemas/pullrequest' 127 | links: 128 | pullRequestMerge: 129 | $ref: '#/components/links/PullRequestMerge' 130 | /2.0/repositories/{username}/{slug}/pullrequests/{pid}/merge: 131 | post: 132 | operationId: mergePullRequest 133 | parameters: 134 | - name: username 135 | in: path 136 | required: true 137 | schema: 138 | type: string 139 | - name: slug 140 | in: path 141 | required: true 142 | schema: 143 | type: string 144 | - name: pid 145 | in: path 146 | required: true 147 | schema: 148 | type: string 149 | responses: 150 | '204': 151 | description: the PR was successfully merged 152 | components: 153 | links: 154 | UserRepositories: 155 | # returns array of '#/components/schemas/repository' 156 | operationId: getRepositoriesByOwner 157 | parameters: 158 | username: $response.body#/username 159 | UserRepository: 160 | # returns '#/components/schemas/repository' 161 | operationId: getRepository 162 | parameters: 163 | username: $response.body#/owner/username 164 | slug: $response.body#/slug 165 | RepositoryPullRequests: 166 | # returns '#/components/schemas/pullrequest' 167 | operationId: getPullRequestsByRepository 168 | parameters: 169 | username: $response.body#/owner/username 170 | slug: $response.body#/slug 171 | PullRequestMerge: 172 | # executes /2.0/repositories/{username}/{slug}/pullrequests/{pid}/merge 173 | operationId: mergePullRequest 174 | parameters: 175 | username: $response.body#/author/username 176 | slug: $response.body#/repository/slug 177 | pid: $response.body#/id 178 | schemas: 179 | user: 180 | type: object 181 | properties: 182 | username: 183 | type: string 184 | uuid: 185 | type: string 186 | repository: 187 | type: object 188 | properties: 189 | slug: 190 | type: string 191 | owner: 192 | $ref: '#/components/schemas/user' 193 | pullrequest: 194 | type: object 195 | properties: 196 | id: 197 | type: integer 198 | title: 199 | type: string 200 | repository: 201 | $ref: '#/components/schemas/repository' 202 | author: 203 | $ref: '#/components/schemas/user' 204 | -------------------------------------------------------------------------------- /data/v3.0/petstore-expanded.yaml: -------------------------------------------------------------------------------- 1 | openapi: "3.0.0" 2 | info: 3 | version: 1.0.0 4 | title: Swagger Petstore 5 | description: A sample API that uses a petstore as an example to demonstrate features in the OpenAPI 3.0 specification 6 | termsOfService: http://swagger.io/terms/ 7 | contact: 8 | name: Swagger API Team 9 | email: foo@example.com 10 | url: http://madskristensen.net/ 11 | license: 12 | name: MIT 13 | url: http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT 14 | servers: 15 | - url: http://petstore.swagger.io/api 16 | paths: 17 | /pets: 18 | get: 19 | description: | 20 | Returns all pets from the system that the user has access to 21 | Nam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia. 22 | 23 | Sed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien. 24 | operationId: findPets 25 | parameters: 26 | - name: tags 27 | in: query 28 | description: tags to filter by 29 | required: false 30 | style: form 31 | schema: 32 | type: array 33 | items: 34 | type: string 35 | - name: limit 36 | in: query 37 | description: maximum number of results to return 38 | required: false 39 | schema: 40 | type: integer 41 | format: int32 42 | responses: 43 | '200': 44 | description: pet response 45 | content: 46 | application/json: 47 | schema: 48 | type: array 49 | items: 50 | $ref: '#/components/schemas/Pet' 51 | default: 52 | description: unexpected error 53 | content: 54 | application/json: 55 | schema: 56 | $ref: '#/components/schemas/Error' 57 | post: 58 | description: Creates a new pet in the store. Duplicates are allowed 59 | operationId: addPet 60 | requestBody: 61 | description: Pet to add to the store 62 | required: true 63 | content: 64 | application/json: 65 | schema: 66 | $ref: '#/components/schemas/NewPet' 67 | responses: 68 | '200': 69 | description: pet response 70 | content: 71 | application/json: 72 | schema: 73 | $ref: '#/components/schemas/Pet' 74 | default: 75 | description: unexpected error 76 | content: 77 | application/json: 78 | schema: 79 | $ref: '#/components/schemas/Error' 80 | /pets/{id}: 81 | get: 82 | description: Returns a user based on a single ID, if the user does not have access to the pet 83 | operationId: find pet by id 84 | parameters: 85 | - name: id 86 | in: path 87 | description: ID of pet to fetch 88 | required: true 89 | schema: 90 | type: integer 91 | format: int64 92 | responses: 93 | '200': 94 | description: pet response 95 | content: 96 | application/json: 97 | schema: 98 | $ref: '#/components/schemas/Pet' 99 | default: 100 | description: unexpected error 101 | content: 102 | application/json: 103 | schema: 104 | $ref: '#/components/schemas/Error' 105 | delete: 106 | description: deletes a single pet based on the ID supplied 107 | operationId: deletePet 108 | parameters: 109 | - name: id 110 | in: path 111 | description: ID of pet to delete 112 | required: true 113 | schema: 114 | type: integer 115 | format: int64 116 | responses: 117 | '204': 118 | description: pet deleted 119 | default: 120 | description: unexpected error 121 | content: 122 | application/json: 123 | schema: 124 | $ref: '#/components/schemas/Error' 125 | components: 126 | schemas: 127 | Pet: 128 | allOf: 129 | - $ref: '#/components/schemas/NewPet' 130 | - required: 131 | - id 132 | properties: 133 | id: 134 | type: integer 135 | format: int64 136 | 137 | NewPet: 138 | required: 139 | - name 140 | properties: 141 | name: 142 | type: string 143 | tag: 144 | type: string 145 | 146 | Error: 147 | required: 148 | - code 149 | - message 150 | properties: 151 | code: 152 | type: integer 153 | format: int32 154 | message: 155 | type: string 156 | 157 | PetSpecies: 158 | oneOf: 159 | - $ref: '#/components/schemas/Dog' 160 | - $ref: '#/components/schemas/Cat' 161 | 162 | Dog: 163 | properties: 164 | name: 165 | type: string 166 | age: 167 | type: int 168 | 169 | Cat: 170 | properties: 171 | name: 172 | type: string 173 | age: 174 | type: int 175 | lives: 176 | type: int 177 | -------------------------------------------------------------------------------- /data/v3.0/petstore.yaml: -------------------------------------------------------------------------------- 1 | openapi: "3.0.0" 2 | info: 3 | version: 1.0.0 4 | title: Swagger Petstore 5 | license: 6 | name: MIT 7 | servers: 8 | - url: http://petstore.swagger.io/v1 9 | paths: 10 | /pets: 11 | get: 12 | summary: List all pets 13 | operationId: listPets 14 | tags: 15 | - pets 16 | parameters: 17 | - name: limit 18 | in: query 19 | description: How many items to return at one time (max 100) 20 | required: false 21 | schema: 22 | type: integer 23 | format: int32 24 | responses: 25 | '200': 26 | description: An paged array of pets 27 | headers: 28 | x-next: 29 | description: A link to the next page of responses 30 | schema: 31 | type: string 32 | content: 33 | application/json: 34 | schema: 35 | $ref: "#/components/schemas/Pets" 36 | default: 37 | description: unexpected error 38 | content: 39 | application/json: 40 | schema: 41 | $ref: "#/components/schemas/Error" 42 | post: 43 | summary: Create a pet 44 | operationId: createPets 45 | tags: 46 | - pets 47 | responses: 48 | '201': 49 | description: Null response 50 | default: 51 | description: unexpected error 52 | content: 53 | application/json: 54 | schema: 55 | $ref: "#/components/schemas/Error" 56 | /pets/{petId}: 57 | get: 58 | summary: Info for a specific pet 59 | operationId: showPetById 60 | tags: 61 | - pets 62 | parameters: 63 | - name: petId 64 | in: path 65 | required: true 66 | description: The id of the pet to retrieve 67 | schema: 68 | type: string 69 | responses: 70 | '200': 71 | description: Expected response to a valid request 72 | content: 73 | application/json: 74 | schema: 75 | $ref: "#/components/schemas/Pets" 76 | default: 77 | description: unexpected error 78 | content: 79 | application/json: 80 | schema: 81 | $ref: "#/components/schemas/Error" 82 | components: 83 | schemas: 84 | Pet: 85 | required: 86 | - id 87 | - name 88 | properties: 89 | id: 90 | type: integer 91 | format: int64 92 | name: 93 | type: string 94 | tag: 95 | type: string 96 | Pets: 97 | type: array 98 | items: 99 | $ref: "#/components/schemas/Pet" 100 | Error: 101 | required: 102 | - code 103 | - message 104 | properties: 105 | code: 106 | type: integer 107 | format: int32 108 | message: 109 | type: string 110 | -------------------------------------------------------------------------------- /data/v3.0/uspto.yaml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | servers: 3 | - url: '{scheme}://developer.uspto.gov/ds-api' 4 | variables: 5 | scheme: 6 | description: 'The Data Set API is accessible via https and http' 7 | enum: 8 | - 'https' 9 | - 'http' 10 | default: 'https' 11 | info: 12 | description: >- 13 | The Data Set API (DSAPI) allows the public users to discover and search 14 | USPTO exported data sets. This is a generic API that allows USPTO users to 15 | make any CSV based data files searchable through API. With the help of GET 16 | call, it returns the list of data fields that are searchable. With the help 17 | of POST call, data can be fetched based on the filters on the field names. 18 | Please note that POST call is used to search the actual data. The reason for 19 | the POST call is that it allows users to specify any complex search criteria 20 | without worry about the GET size limitations as well as encoding of the 21 | input parameters. 22 | version: 1.0.0 23 | title: USPTO Data Set API 24 | contact: 25 | name: Open Data Portal 26 | url: 'https://developer.uspto.gov/' 27 | email: developer@uspto.gov 28 | tags: 29 | - name: metadata 30 | description: Find out about the data sets 31 | - name: search 32 | description: Search a data set 33 | paths: 34 | /: 35 | get: 36 | tags: 37 | - metadata 38 | operationId: list-data-sets 39 | summary: List available data sets 40 | responses: 41 | '200': 42 | description: Returns a list of data sets 43 | content: 44 | application/json: 45 | schema: 46 | $ref: '#/components/schemas/dataSetList' 47 | example: 48 | { 49 | "total": 2, 50 | "apis": [ 51 | { 52 | "apiKey": "oa_citations", 53 | "apiVersionNumber": "v1", 54 | "apiUrl": "https://developer.uspto.gov/ds-api/oa_citations/v1/fields", 55 | "apiDocumentationUrl": "https://developer.uspto.gov/ds-api-docs/index.html?url=https://developer.uspto.gov/ds-api/swagger/docs/oa_citations.json" 56 | }, 57 | { 58 | "apiKey": "cancer_moonshot", 59 | "apiVersionNumber": "v1", 60 | "apiUrl": "https://developer.uspto.gov/ds-api/cancer_moonshot/v1/fields", 61 | "apiDocumentationUrl": "https://developer.uspto.gov/ds-api-docs/index.html?url=https://developer.uspto.gov/ds-api/swagger/docs/cancer_moonshot.json" 62 | } 63 | ] 64 | } 65 | /{dataset}/{version}/fields: 66 | get: 67 | tags: 68 | - metadata 69 | summary: >- 70 | Provides the general information about the API and the list of fields 71 | that can be used to query the dataset. 72 | description: >- 73 | This GET API returns the list of all the searchable field names that are 74 | in the oa_citations. Please see the 'fields' attribute which returns an 75 | array of field names. Each field or a combination of fields can be 76 | searched using the syntax options shown below. 77 | operationId: list-searchable-fields 78 | parameters: 79 | - name: dataset 80 | in: path 81 | description: 'Name of the dataset. In this case, the default value is oa_citations' 82 | required: true 83 | schema: 84 | type: string 85 | default: oa_citations 86 | - name: version 87 | in: path 88 | description: Version of the dataset. 89 | required: true 90 | schema: 91 | type: string 92 | default: v1 93 | responses: 94 | '200': 95 | description: >- 96 | The dataset api for the given version is found and it is accessible 97 | to consume. 98 | content: 99 | application/json: 100 | schema: 101 | type: string 102 | '404': 103 | description: >- 104 | The combination of dataset name and version is not found in the 105 | system or it is not published yet to be consumed by public. 106 | content: 107 | application/json: 108 | schema: 109 | type: string 110 | /{dataset}/{version}/records: 111 | post: 112 | tags: 113 | - search 114 | summary: >- 115 | Provides search capability for the data set with the given search 116 | criteria. 117 | description: >- 118 | This API is based on Solr/Lucense Search. The data is indexed using 119 | SOLR. This GET API returns the list of all the searchable field names 120 | that are in the Solr Index. Please see the 'fields' attribute which 121 | returns an array of field names. Each field or a combination of fields 122 | can be searched using the Solr/Lucene Syntax. Please refer 123 | https://lucene.apache.org/core/3_6_2/queryparsersyntax.html#Overview for 124 | the query syntax. List of field names that are searchable can be 125 | determined using above GET api. 126 | operationId: perform-search 127 | parameters: 128 | - name: version 129 | in: path 130 | description: Version of the dataset. 131 | required: true 132 | schema: 133 | type: string 134 | default: v1 135 | - name: dataset 136 | in: path 137 | description: 'Name of the dataset. In this case, the default value is oa_citations' 138 | required: true 139 | schema: 140 | type: string 141 | default: oa_citations 142 | responses: 143 | '200': 144 | description: successful operation 145 | content: 146 | application/json: 147 | schema: 148 | type: array 149 | items: 150 | type: object 151 | additionalProperties: 152 | type: object 153 | '404': 154 | description: No matching record found for the given criteria. 155 | requestBody: 156 | content: 157 | application/x-www-form-urlencoded: 158 | schema: 159 | type: object 160 | properties: 161 | criteria: 162 | description: >- 163 | Uses Lucene Query Syntax in the format of 164 | propertyName:value, propertyName:[num1 TO num2] and date 165 | range format: propertyName:[yyyyMMdd TO yyyyMMdd]. In the 166 | response please see the 'docs' element which has the list of 167 | record objects. Each record structure would consist of all 168 | the fields and their corresponding values. 169 | type: string 170 | default: '*:*' 171 | start: 172 | description: Starting record number. Default value is 0. 173 | type: integer 174 | default: 0 175 | rows: 176 | description: >- 177 | Specify number of rows to be returned. If you run the search 178 | with default values, in the response you will see 'numFound' 179 | attribute which will tell the number of records available in 180 | the dataset. 181 | type: integer 182 | default: 100 183 | required: 184 | - criteria 185 | components: 186 | schemas: 187 | dataSetList: 188 | type: object 189 | properties: 190 | total: 191 | type: integer 192 | apis: 193 | type: array 194 | items: 195 | type: object 196 | properties: 197 | apiKey: 198 | type: string 199 | description: To be used as a dataset parameter value 200 | apiVersionNumber: 201 | type: string 202 | description: To be used as a version parameter value 203 | apiUrl: 204 | type: string 205 | format: uriref 206 | description: "The URL describing the dataset's fields" 207 | apiDocumentationUrl: 208 | type: string 209 | format: uriref 210 | description: A URL to the API console for each API 211 | -------------------------------------------------------------------------------- /examples/printer.rs: -------------------------------------------------------------------------------- 1 | use anyhow::Result; 2 | 3 | fn main() -> Result<()> { 4 | if let Some(path) = std::env::args().nth(1) { 5 | let spec = openapi::from_path(path)?; 6 | /*for (path, op) in spec.paths { 7 | println!("{}", path); 8 | println!("{:#?}", op); 9 | } 10 | for (name, definition) in spec.definitions { 11 | println!("{}", name); 12 | println!("{:#?}", definition); 13 | }*/ 14 | println!("{}", openapi::to_json(&spec)?); 15 | } 16 | Ok(()) 17 | } 18 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | # https://github.com/rust-lang/rustfmt/blob/master/Configurations.md#fn_args_density 2 | fn_args_density = "Vertical" 3 | # https://github.com/rust-lang/rustfmt/blob/master/Configurations.md#merge_imports 4 | merge_imports = true -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | //! Error types 2 | 3 | use semver::{SemVerError, Version}; 4 | use serde_json::Error as JsonError; 5 | use serde_yaml::Error as YamlError; 6 | use std::io::Error as IoError; 7 | use thiserror::Error; 8 | 9 | /// errors that openapi functions may return 10 | #[derive(Error, Debug)] 11 | pub enum Error { 12 | #[error("I/O error")] 13 | Io(#[from] IoError), 14 | #[error("YAML serialization or deserialization error")] 15 | Yaml(#[from] YamlError), 16 | #[error("JSON serialization error")] 17 | Serialize(#[from] JsonError), 18 | #[error("Semantic Versioning parsing error")] 19 | SemVerError(#[from] SemVerError), 20 | #[error("Unsupported spec file version ({0})")] 21 | UnsupportedSpecFileVersion(Version), 22 | } 23 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Openapi provides structures and support for serializing and deserializing [openapi](https://github.com/OAI/OpenAPI-Specification) specifications 2 | //! 3 | //! # Examples 4 | //! 5 | //! Typical use deserialing an existing to a persisted spec to rust form or 6 | //! visa versa 7 | //! 8 | //! The hyper client should be configured with tls. 9 | //! 10 | //! ```no_run 11 | //! extern crate openapi; 12 | //! 13 | //! fn main() { 14 | //! match openapi::from_path("path/to/openapi.yaml") { 15 | //! Ok(spec) => println!("spec: {:?}", spec), 16 | //! Err(err) => println!("error: {}", err) 17 | //! } 18 | //! } 19 | //! ``` 20 | //! 21 | //! # Errors 22 | //! 23 | //! Operations typically result in a [`Result`] type, an alias for 24 | //! [`std::result::Result`] with the `Err` type fixed to [`Error`], 25 | //! which implements [`std::error::Error`]. 26 | //! 27 | use serde::{Deserialize, Serialize}; 28 | use std::{fs::File, io::Read, path::Path, result::Result as StdResult}; 29 | 30 | pub mod error; 31 | pub mod v2; 32 | pub mod v3_0; 33 | 34 | pub use error::Error; 35 | 36 | const MINIMUM_OPENAPI30_VERSION: &str = ">= 3.0"; 37 | 38 | pub type Result = StdResult; 39 | 40 | /// Supported versions of the OpenApi. 41 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 42 | #[serde(untagged)] 43 | pub enum OpenApi { 44 | /// Version 2.0 of the OpenApi specification. 45 | /// 46 | /// Refer to the official 47 | /// [specification](https://github.com/OAI/OpenAPI-Specification/blob/0dd79f6/versions/2.0.md) 48 | /// for more information. 49 | V2(v2::Spec), 50 | 51 | /// Version 3.0.1 of the OpenApi specification. 52 | /// 53 | /// Refer to the official 54 | /// [specification](https://github.com/OAI/OpenAPI-Specification/blob/0dd79f6/versions/3.0.1.md) 55 | /// for more information. 56 | #[allow(non_camel_case_types)] 57 | V3_0(v3_0::Spec), 58 | } 59 | 60 | /// deserialize an open api spec from a path 61 | pub fn from_path

(path: P) -> Result 62 | where 63 | P: AsRef, 64 | { 65 | from_reader(File::open(path)?) 66 | } 67 | 68 | /// deserialize an open api spec from type which implements Read 69 | pub fn from_reader(read: R) -> Result 70 | where 71 | R: Read, 72 | { 73 | Ok(serde_yaml::from_reader::(read)?) 74 | } 75 | 76 | /// serialize to a yaml string 77 | pub fn to_yaml(spec: &OpenApi) -> Result { 78 | Ok(serde_yaml::to_string(spec)?) 79 | } 80 | 81 | /// serialize to a json string 82 | pub fn to_json(spec: &OpenApi) -> Result { 83 | Ok(serde_json::to_string_pretty(spec)?) 84 | } 85 | 86 | #[cfg(test)] 87 | mod tests { 88 | use super::*; 89 | use pretty_assertions::assert_eq; 90 | use std::{ 91 | fs::{self, read_to_string, File}, 92 | io::Write, 93 | }; 94 | 95 | /// Helper function to write string to file. 96 | fn write_to_file

(path: P, filename: &str, data: &str) 97 | where 98 | P: AsRef + std::fmt::Debug, 99 | { 100 | println!(" Saving string to {:?}...", path); 101 | std::fs::create_dir_all(&path).unwrap(); 102 | let full_filename = path.as_ref().to_path_buf().join(filename); 103 | let mut f = File::create(&full_filename).unwrap(); 104 | f.write_all(data.as_bytes()).unwrap(); 105 | } 106 | 107 | /// Convert a YAML `&str` to a JSON `String`. 108 | fn convert_yaml_str_to_json(yaml_str: &str) -> String { 109 | let yaml: serde_yaml::Value = serde_yaml::from_str(yaml_str).unwrap(); 110 | let json: serde_json::Value = serde_yaml::from_value(yaml).unwrap(); 111 | serde_json::to_string_pretty(&json).unwrap() 112 | } 113 | 114 | /// Deserialize and re-serialize the input file to a JSON string through two different 115 | /// paths, comparing the result. 116 | /// 1. File -> `String` -> `serde_yaml::Value` -> `serde_json::Value` -> `String` 117 | /// 2. File -> `Spec` -> `serde_json::Value` -> `String` 118 | /// Both conversion of `serde_json::Value` -> `String` are done 119 | /// using `serde_json::to_string_pretty`. 120 | /// Since the first conversion is independant of the current crate (and only 121 | /// uses serde's json and yaml support), no information should be lost in the final 122 | /// JSON string. The second conversion goes through our `OpenApi`, so the final JSON 123 | /// string is a representation of _our_ implementation. 124 | /// By comparing those two JSON conversions, we can validate our implementation. 125 | fn compare_spec_through_json( 126 | input_file: &Path, 127 | save_path_base: &Path, 128 | ) -> (String, String, String) { 129 | // First conversion: 130 | // File -> `String` -> `serde_yaml::Value` -> `serde_json::Value` -> `String` 131 | 132 | // Read the original file to string 133 | let spec_yaml_str = read_to_string(&input_file) 134 | .unwrap_or_else(|e| panic!("failed to read contents of {:?}: {}", input_file, e)); 135 | // Convert YAML string to JSON string 136 | let spec_json_str = convert_yaml_str_to_json(&spec_yaml_str); 137 | 138 | // Second conversion: 139 | // File -> `Spec` -> `serde_json::Value` -> `String` 140 | 141 | // Parse the input file 142 | let parsed_spec = from_path(&input_file).unwrap(); 143 | // Convert to serde_json::Value 144 | let parsed_spec_json = serde_json::to_value(parsed_spec).unwrap(); 145 | // Convert to a JSON string 146 | let parsed_spec_json_str: String = serde_json::to_string_pretty(&parsed_spec_json).unwrap(); 147 | 148 | // Save JSON strings to file 149 | let api_filename = input_file 150 | .file_name() 151 | .unwrap() 152 | .to_str() 153 | .unwrap() 154 | .replace(".yaml", ".json"); 155 | 156 | let mut save_path = save_path_base.to_path_buf(); 157 | save_path.push("yaml_to_json"); 158 | write_to_file(&save_path, &api_filename, &spec_json_str); 159 | 160 | let mut save_path = save_path_base.to_path_buf(); 161 | save_path.push("yaml_to_spec_to_json"); 162 | write_to_file(&save_path, &api_filename, &parsed_spec_json_str); 163 | 164 | // Return the JSON filename and the two JSON strings 165 | (api_filename, parsed_spec_json_str, spec_json_str) 166 | } 167 | 168 | // Just tests if the deserialization does not blow up. But does not test correctness 169 | #[test] 170 | fn can_deserialize() { 171 | for entry in fs::read_dir("data/v2").unwrap() { 172 | let path = entry.unwrap().path(); 173 | // cargo test -- --nocapture to see this message 174 | println!("Testing if {:?} is deserializable", path); 175 | from_path(path).unwrap(); 176 | } 177 | } 178 | 179 | #[test] 180 | fn can_deserialize_and_reserialize_v2() { 181 | let save_path_base: std::path::PathBuf = 182 | ["target", "tests", "can_deserialize_and_reserialize_v2"] 183 | .iter() 184 | .collect(); 185 | 186 | for entry in fs::read_dir("data/v2").unwrap() { 187 | let path = entry.unwrap().path(); 188 | 189 | println!("Testing if {:?} is deserializable", path); 190 | 191 | let (api_filename, parsed_spec_json_str, spec_json_str) = 192 | compare_spec_through_json(&path, &save_path_base); 193 | 194 | assert_eq!( 195 | parsed_spec_json_str.lines().collect::>(), 196 | spec_json_str.lines().collect::>(), 197 | "contents did not match for api {}", 198 | api_filename 199 | ); 200 | } 201 | } 202 | 203 | #[test] 204 | fn can_deserialize_and_reserialize_v3() { 205 | let save_path_base: std::path::PathBuf = 206 | ["target", "tests", "can_deserialize_and_reserialize_v3"] 207 | .iter() 208 | .collect(); 209 | 210 | for entry in fs::read_dir("data/v3.0").unwrap() { 211 | let entry = entry.unwrap(); 212 | let path = entry.path(); 213 | 214 | println!("Testing if {:?} is deserializable", path); 215 | 216 | let (api_filename, parsed_spec_json_str, spec_json_str) = 217 | compare_spec_through_json(&path, &save_path_base); 218 | 219 | assert_eq!( 220 | parsed_spec_json_str.lines().collect::>(), 221 | spec_json_str.lines().collect::>(), 222 | "contents did not match for api {}", 223 | api_filename 224 | ); 225 | } 226 | } 227 | 228 | #[test] 229 | fn can_deserialize_one_of_v3() { 230 | let openapi = from_path("data/v3.0/petstore-expanded.yaml").unwrap(); 231 | if let OpenApi::V3_0(spec) = openapi { 232 | let components = spec.components.unwrap(); 233 | let schemas = components.schemas.unwrap(); 234 | let obj_or_ref = schemas.get("PetSpecies"); 235 | 236 | if let Some(v3_0::ObjectOrReference::Object(schema)) = obj_or_ref { 237 | // there should be 2 schemas in there 238 | assert_eq!(schema.one_of.as_ref().unwrap().len(), 2); 239 | } else { 240 | panic!("object should have been schema"); 241 | } 242 | } 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /src/v2/mod.rs: -------------------------------------------------------------------------------- 1 | //! Support for OpenApi version 2.0 specification. 2 | //! 3 | //! See the 4 | //! [specification](https://github.com/OAI/OpenAPI-Specification/blob/0dd79f6/versions/2.0.md) 5 | //! for more information. 6 | 7 | mod schema; 8 | 9 | pub use crate::v2::schema::*; 10 | -------------------------------------------------------------------------------- /src/v2/schema.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use std::collections::BTreeMap; 3 | 4 | // http://json.schemastore.org/swagger-2.0 5 | 6 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 7 | #[serde(rename_all = "lowercase")] 8 | pub enum Scheme { 9 | Http, 10 | Https, 11 | Ws, 12 | Wss, 13 | } 14 | 15 | impl Default for Scheme { 16 | fn default() -> Self { 17 | Scheme::Http 18 | } 19 | } 20 | 21 | /// top level document 22 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 23 | #[serde(rename_all = "camelCase")] 24 | pub struct Spec { 25 | /// The Swagger version of this document. 26 | pub swagger: String, 27 | pub info: Info, 28 | /// The host (name or ip) of the API. Example: 'swagger.io' 29 | /// ^[^{}/ :\\\\]+(?::\\d+)?$ 30 | #[serde(skip_serializing_if = "Option::is_none")] 31 | pub host: Option, 32 | /// The base path to the API. Example: '/api'. 33 | #[serde(skip_serializing_if = "Option::is_none")] 34 | #[serde(rename = "basePath")] 35 | pub base_path: Option, 36 | #[serde(skip_serializing_if = "Option::is_none")] 37 | pub schemes: Option>, 38 | /// A list of MIME types accepted by the API. 39 | #[serde(skip_serializing_if = "Option::is_none")] 40 | pub consumes: Option>, 41 | /// A list of MIME types the API can produce. 42 | #[serde(skip_serializing_if = "Option::is_none")] 43 | pub produces: Option>, 44 | #[serde(skip_serializing_if = "Option::is_none")] 45 | pub tags: Option>, 46 | /// Relative paths to the individual endpoints. They must be relative 47 | /// to the 'basePath'. 48 | pub paths: BTreeMap, 49 | #[serde(skip_serializing_if = "Option::is_none")] 50 | pub definitions: Option>, 51 | #[serde(skip_serializing_if = "Option::is_none")] 52 | pub parameters: Option>, 53 | /// mappings to http response codes or "default" 54 | #[serde(skip_serializing_if = "Option::is_none")] 55 | pub responses: Option>, 56 | #[serde(skip_serializing_if = "Option::is_none")] 57 | pub security_definitions: Option>, 58 | #[serde(skip_serializing_if = "Option::is_none")] 59 | pub security: Option>>>, 60 | #[serde(skip_serializing_if = "Option::is_none")] 61 | pub external_docs: Option>, 62 | } 63 | 64 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 65 | #[serde(rename_all = "lowercase")] 66 | pub struct Tag { 67 | pub name: String, 68 | #[serde(skip_serializing_if = "Option::is_none")] 69 | pub description: Option, 70 | #[serde(skip_serializing_if = "Option::is_none")] 71 | pub external_docs: Option>, 72 | } 73 | 74 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 75 | pub struct ExternalDoc { 76 | pub url: String, 77 | #[serde(skip_serializing_if = "Option::is_none")] 78 | pub description: Option, 79 | } 80 | 81 | /// General information about the API. 82 | /// 83 | /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#info-object 84 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 85 | #[serde(rename_all = "lowercase")] 86 | pub struct Info { 87 | /// A unique and precise title of the API. 88 | #[serde(skip_serializing_if = "Option::is_none")] 89 | pub title: Option, 90 | /// A semantic version number of the API. 91 | #[serde(skip_serializing_if = "Option::is_none")] 92 | pub description: Option, 93 | #[serde(rename = "termsOfService", skip_serializing_if = "Option::is_none")] 94 | pub terms_of_service: Option, 95 | #[serde(skip_serializing_if = "Option::is_none")] 96 | pub contact: Option, 97 | #[serde(skip_serializing_if = "Option::is_none")] 98 | pub license: Option, 99 | #[serde(skip_serializing_if = "Option::is_none")] 100 | pub version: Option, 101 | } 102 | 103 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 104 | pub struct Contact { 105 | #[serde(skip_serializing_if = "Option::is_none")] 106 | pub name: Option, 107 | // TODO: Make sure the url is a valid URL 108 | #[serde(skip_serializing_if = "Option::is_none")] 109 | pub url: Option, 110 | // TODO: Make sure the email is a valid email 111 | #[serde(skip_serializing_if = "Option::is_none")] 112 | pub email: Option, 113 | } 114 | 115 | /// todo x-* properties 116 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 117 | pub struct License { 118 | /// The name of the license type. It's encouraged to use an OSI 119 | /// compatible license. 120 | #[serde(skip_serializing_if = "Option::is_none")] 121 | pub name: Option, 122 | /// The URL pointing to the license. 123 | // TODO: Make sure the url is a valid URL 124 | #[serde(skip_serializing_if = "Option::is_none")] 125 | pub url: Option, 126 | } 127 | 128 | /// todo support x-* properties 129 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 130 | pub struct PathItem { 131 | #[serde(skip_serializing_if = "Option::is_none")] 132 | pub get: Option, 133 | #[serde(skip_serializing_if = "Option::is_none")] 134 | pub post: Option, 135 | #[serde(skip_serializing_if = "Option::is_none")] 136 | pub put: Option, 137 | #[serde(skip_serializing_if = "Option::is_none")] 138 | pub patch: Option, 139 | #[serde(skip_serializing_if = "Option::is_none")] 140 | pub delete: Option, 141 | #[serde(skip_serializing_if = "Option::is_none")] 142 | pub options: Option, 143 | #[serde(skip_serializing_if = "Option::is_none")] 144 | pub head: Option, 145 | #[serde(skip_serializing_if = "Option::is_none")] 146 | pub parameters: Option>, 147 | } 148 | 149 | /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operation-object 150 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 151 | #[serde(rename_all = "lowercase")] 152 | pub struct Operation { 153 | #[serde(skip_serializing_if = "Option::is_none")] 154 | pub summary: Option, 155 | #[serde(skip_serializing_if = "Option::is_none")] 156 | pub description: Option, 157 | #[serde(skip_serializing_if = "Option::is_none")] 158 | pub consumes: Option>, 159 | #[serde(skip_serializing_if = "Option::is_none")] 160 | pub produces: Option>, 161 | #[serde(skip_serializing_if = "Option::is_none")] 162 | pub schemes: Option>, 163 | #[serde(skip_serializing_if = "Option::is_none")] 164 | pub tags: Option>, 165 | #[serde(rename = "operationId", skip_serializing_if = "Option::is_none")] 166 | pub operation_id: Option, 167 | pub responses: BTreeMap, 168 | #[serde(skip_serializing_if = "Option::is_none")] 169 | pub parameters: Option>, 170 | #[serde(skip_serializing_if = "Option::is_none")] 171 | pub security: Option>, 172 | } 173 | 174 | /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securityRequirementObject 175 | pub type SecurityRequirement = BTreeMap>; 176 | 177 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 178 | #[serde(rename_all = "camelCase")] 179 | pub struct Parameter { 180 | pub name: String, 181 | #[serde(rename = "in")] 182 | pub location: String, 183 | #[serde(skip_serializing_if = "Option::is_none")] 184 | pub required: Option, 185 | #[serde(skip_serializing_if = "Option::is_none")] 186 | pub schema: Option, 187 | #[serde(skip_serializing_if = "Option::is_none")] 188 | pub unique_items: Option, 189 | #[serde(skip_serializing_if = "Option::is_none")] 190 | #[serde(rename = "type")] 191 | pub param_type: Option, 192 | #[serde(skip_serializing_if = "Option::is_none")] 193 | pub format: Option, 194 | #[serde(skip_serializing_if = "Option::is_none")] 195 | pub description: Option, 196 | #[serde(skip_serializing_if = "Option::is_none")] 197 | pub items: Option, 198 | #[serde(skip_serializing_if = "Option::is_none")] 199 | default: Option, 200 | } 201 | 202 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 203 | pub struct Response { 204 | pub description: String, 205 | #[serde(skip_serializing_if = "Option::is_none")] 206 | pub schema: Option, 207 | } 208 | 209 | // todo: support x-* fields 210 | /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameter-object 211 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 212 | #[serde(untagged)] 213 | pub enum ParameterOrRef { 214 | /// both bodyParameter and nonBodyParameter in one for now 215 | Parameter { 216 | /// The name of the parameter. 217 | name: String, 218 | /// values depend on parameter type 219 | /// may be `header`, `query`, 'path`, `formData` 220 | #[serde(rename = "in")] 221 | location: String, 222 | #[serde(skip_serializing_if = "Option::is_none")] 223 | required: Option, 224 | #[serde(skip_serializing_if = "Option::is_none")] 225 | schema: Option, 226 | #[serde(skip_serializing_if = "Option::is_none")] 227 | #[serde(rename = "uniqueItems")] 228 | unique_items: Option, 229 | /// string, number, boolean, integer, array, file ( only for formData ) 230 | #[serde(skip_serializing_if = "Option::is_none")] 231 | #[serde(rename = "type")] 232 | param_type: Option, 233 | #[serde(skip_serializing_if = "Option::is_none")] 234 | format: Option, 235 | /// A brief description of the parameter. This could contain examples 236 | /// of use. GitHub Flavored Markdown is allowed. 237 | #[serde(skip_serializing_if = "Option::is_none")] 238 | description: Option, 239 | #[serde(rename = "collectionFormat", skip_serializing_if = "Option::is_none")] 240 | collection_format: Option, 241 | #[serde(skip_serializing_if = "Option::is_none")] 242 | default: Option, 243 | // maximum ? 244 | // exclusiveMaximum ?? 245 | // minimum ?? 246 | // exclusiveMinimum ?? 247 | // maxLength ?? 248 | // minLength ?? 249 | // pattern ?? 250 | // maxItems ?? 251 | // minItems ?? 252 | // enum ?? 253 | // multipleOf ?? 254 | // allowEmptyValue ( for query / body params ) 255 | #[serde(skip_serializing_if = "Option::is_none")] 256 | items: Option, 257 | #[serde( 258 | rename = "additionalProperties", 259 | skip_serializing_if = "Option::is_none" 260 | )] 261 | additional_properties: Option, 262 | }, 263 | Ref { 264 | #[serde(rename = "$ref")] 265 | ref_path: String, 266 | }, 267 | } 268 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 269 | #[serde(tag = "type")] 270 | pub enum Security { 271 | #[serde(rename = "apiKey")] 272 | ApiKey { 273 | name: String, 274 | #[serde(rename = "in")] 275 | location: String, 276 | #[serde(skip_serializing_if = "Option::is_none")] 277 | description: Option, 278 | }, 279 | #[serde(rename = "oauth2")] 280 | Oauth2 { 281 | flow: Flow, 282 | #[serde(rename = "authorizationUrl")] 283 | authorization_url: String, 284 | #[serde(rename = "tokenUrl")] 285 | #[serde(skip_serializing_if = "Option::is_none")] 286 | token_url: Option, 287 | scopes: BTreeMap, 288 | #[serde(skip_serializing_if = "Option::is_none")] 289 | description: Option, 290 | }, 291 | #[serde(rename = "basic")] 292 | Basic { 293 | #[serde(skip_serializing_if = "Option::is_none")] 294 | description: Option, 295 | }, 296 | } 297 | 298 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 299 | #[serde(rename_all = "camelCase")] 300 | pub enum Flow { 301 | Implicit, 302 | Password, 303 | Application, 304 | AccessCode, 305 | } 306 | 307 | /// A [JSON schema](http://json-schema.org/) definition describing 308 | /// the shape and properties of an object. 309 | /// 310 | /// This may also contain a `$ref` to another definition 311 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 312 | pub struct Schema { 313 | #[serde(skip_serializing_if = "Option::is_none")] 314 | /// [JSON reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) 315 | /// path to another defintion 316 | #[serde(rename = "$ref")] 317 | pub ref_path: Option, 318 | #[serde(skip_serializing_if = "Option::is_none")] 319 | pub description: Option, 320 | #[serde(skip_serializing_if = "Option::is_none")] 321 | #[serde(rename = "type")] 322 | pub schema_type: Option, 323 | #[serde(skip_serializing_if = "Option::is_none")] 324 | pub format: Option, 325 | #[serde(skip_serializing_if = "Option::is_none")] 326 | #[serde(rename = "enum")] 327 | pub enum_values: Option>, 328 | #[serde(skip_serializing_if = "Option::is_none")] 329 | pub required: Option>, 330 | #[serde(skip_serializing_if = "Option::is_none")] 331 | pub items: Option>, 332 | // implies object 333 | #[serde(skip_serializing_if = "Option::is_none")] 334 | pub properties: Option>, 335 | // composition 336 | #[serde(skip_serializing_if = "Option::is_none")] 337 | #[serde(rename = "allOf")] 338 | pub all_of: Option>>, 339 | // TODO: we need a validation step that we only collect x-* properties here. 340 | #[serde(flatten)] 341 | pub other: BTreeMap, 342 | } 343 | 344 | #[cfg(test)] 345 | mod tests { 346 | use super::*; 347 | use serde_json; 348 | use serde_yaml; 349 | use std::collections::BTreeMap; 350 | 351 | #[test] 352 | fn security_api_deserializes() { 353 | let json = r#"{"type":"apiKey", "name":"foo", "in": "query"}"#; 354 | assert_eq!( 355 | serde_yaml::from_str::(&json).unwrap(), 356 | Security::ApiKey { 357 | name: "foo".into(), 358 | location: "query".into(), 359 | description: None, 360 | } 361 | ); 362 | } 363 | 364 | #[test] 365 | fn security_api_serializes() { 366 | let json = r#"{"type":"apiKey","name":"foo","in":"query"}"#; 367 | assert_eq!( 368 | serde_json::to_string(&Security::ApiKey { 369 | name: "foo".into(), 370 | location: "query".into(), 371 | description: None, 372 | }) 373 | .unwrap(), 374 | json 375 | ); 376 | } 377 | 378 | #[test] 379 | fn security_basic_deserializes() { 380 | let json = r#"{"type":"basic"}"#; 381 | assert_eq!( 382 | serde_yaml::from_str::(&json).unwrap(), 383 | Security::Basic { description: None } 384 | ); 385 | } 386 | 387 | #[test] 388 | fn security_basic_serializes() { 389 | let json = r#"{"type":"basic"}"#; 390 | assert_eq!( 391 | json, 392 | serde_json::to_string(&Security::Basic { description: None }).unwrap() 393 | ); 394 | } 395 | 396 | #[test] 397 | fn security_oauth_deserializes() { 398 | let json = r#"{"type":"oauth2","flow":"implicit","authorizationUrl":"foo/bar","scopes":{"foo":"bar"}}"#; 399 | let mut scopes = BTreeMap::new(); 400 | scopes.insert("foo".into(), "bar".into()); 401 | assert_eq!( 402 | serde_yaml::from_str::(&json).unwrap(), 403 | Security::Oauth2 { 404 | flow: Flow::Implicit, 405 | authorization_url: "foo/bar".into(), 406 | token_url: None, 407 | scopes: scopes, 408 | description: None, 409 | } 410 | ); 411 | } 412 | 413 | #[test] 414 | fn security_oauth_serializes() { 415 | let json = r#"{"type":"oauth2","flow":"implicit","authorizationUrl":"foo/bar","scopes":{"foo":"bar"}}"#; 416 | let mut scopes = BTreeMap::new(); 417 | scopes.insert("foo".into(), "bar".into()); 418 | assert_eq!( 419 | json, 420 | serde_json::to_string(&Security::Oauth2 { 421 | flow: Flow::Implicit, 422 | authorization_url: "foo/bar".into(), 423 | token_url: None, 424 | scopes: scopes, 425 | description: None, 426 | }) 427 | .unwrap() 428 | ); 429 | } 430 | 431 | #[test] 432 | fn parameter_or_ref_deserializes_ref() { 433 | let json = r#"{"$ref":"foo/bar"}"#; 434 | assert_eq!( 435 | serde_yaml::from_str::(&json).unwrap(), 436 | ParameterOrRef::Ref { 437 | ref_path: "foo/bar".into() 438 | } 439 | ); 440 | } 441 | 442 | #[test] 443 | fn parameter_or_ref_serializes_pref() { 444 | let json = r#"{"$ref":"foo/bar"}"#; 445 | assert_eq!( 446 | json, 447 | serde_json::to_string(&ParameterOrRef::Ref { 448 | ref_path: "foo/bar".into() 449 | },) 450 | .unwrap() 451 | ); 452 | } 453 | } 454 | -------------------------------------------------------------------------------- /src/v3_0/components.rs: -------------------------------------------------------------------------------- 1 | use crate::v3_0::{ 2 | Callback, Example, Extensions, Header, Link, Parameter, RequestBody, Response, Schema, 3 | SecurityScheme, 4 | }; 5 | use serde::{Deserialize, Serialize}; 6 | use std::collections::BTreeMap; 7 | 8 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 9 | #[serde(untagged)] 10 | pub enum ObjectOrReference { 11 | Object(T), 12 | Ref { 13 | #[serde(rename = "$ref")] 14 | ref_path: String, 15 | }, 16 | } 17 | 18 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 19 | #[serde(untagged)] 20 | pub enum BooleanObjectOrReference { 21 | Boolean(bool), 22 | Object(T), 23 | Ref { 24 | #[serde(rename = "$ref")] 25 | ref_path: String, 26 | }, 27 | } 28 | 29 | /// Holds a set of reusable objects for different aspects of the OAS. 30 | /// 31 | /// All objects defined within the components object will have no effect on the API unless 32 | /// they are explicitly referenced from properties outside the components object. 33 | /// 34 | /// See . 35 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 36 | pub struct Components { 37 | /// An object to hold reusable Schema Objects. 38 | #[serde(skip_serializing_if = "Option::is_none")] 39 | pub schemas: Option>>, 40 | 41 | /// An object to hold reusable Response Objects. 42 | #[serde(skip_serializing_if = "Option::is_none")] 43 | pub responses: Option>>, 44 | 45 | /// An object to hold reusable Parameter Objects. 46 | #[serde(skip_serializing_if = "Option::is_none")] 47 | pub parameters: Option>>, 48 | 49 | /// An object to hold reusable Example 50 | #[serde(skip_serializing_if = "Option::is_none")] 51 | pub examples: Option>>, 52 | 53 | /// An object to hold reusable Request Body Objects. 54 | #[serde(skip_serializing_if = "Option::is_none", rename = "requestBodies")] 55 | pub request_bodies: Option>>, 56 | 57 | /// An object to hold reusable Header Objects. 58 | #[serde(skip_serializing_if = "Option::is_none")] 59 | pub headers: Option>>, 60 | 61 | /// An object to hold reusable Security Scheme Objects. 62 | #[serde(skip_serializing_if = "Option::is_none", rename = "securitySchemes")] 63 | pub security_schemes: Option>>, 64 | 65 | /// An object to hold reusable Link Objects. 66 | #[serde(skip_serializing_if = "Option::is_none")] 67 | pub links: Option>>, 68 | 69 | /// An object to hold reusable Callback Objects. 70 | #[serde(skip_serializing_if = "Option::is_none")] 71 | pub callbacks: Option>>, 72 | 73 | #[serde(flatten)] 74 | pub extensions: Extensions, 75 | } 76 | -------------------------------------------------------------------------------- /src/v3_0/extension.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::fmt; 3 | 4 | use serde::de::{MapAccess, Visitor}; 5 | use serde::ser::SerializeMap; 6 | use serde::{Deserialize, Deserializer, Serialize, Serializer}; 7 | 8 | /// Contains openapi specification extensions 9 | /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#specificationExtensions 10 | #[derive(Debug, Eq, PartialEq, Clone)] 11 | pub struct Extensions(HashMap); 12 | 13 | impl Extensions { 14 | fn add(&mut self, ext_id: String, value: serde_json::Value) { 15 | self.0.insert(ext_id, value); 16 | } 17 | 18 | /// Fetch extension by name 19 | pub fn get(&self, ext_id: &str) -> Option<&serde_json::Value> { 20 | self.0.get(ext_id) 21 | } 22 | 23 | /// A reference to all the captured extensions 24 | pub fn all(&self) -> &HashMap { 25 | &self.0 26 | } 27 | } 28 | 29 | impl Default for Extensions { 30 | fn default() -> Self { 31 | Self(HashMap::new()) 32 | } 33 | } 34 | 35 | impl<'de> Deserialize<'de> for Extensions { 36 | fn deserialize(deserializer: D) -> Result 37 | where 38 | D: Deserializer<'de>, 39 | { 40 | struct ExtensionsVisitor; 41 | impl<'de> Visitor<'de> for ExtensionsVisitor { 42 | type Value = Extensions; 43 | 44 | fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { 45 | formatter.write_str("struct Extensions") 46 | } 47 | 48 | fn visit_map(self, mut map: V) -> Result 49 | where 50 | V: MapAccess<'de>, 51 | { 52 | let mut extensions = Extensions::default(); 53 | while let Some(key) = map.next_key::()? { 54 | if key.starts_with("x-") { 55 | extensions.add(key, map.next_value()?); 56 | } 57 | } 58 | Ok(extensions) 59 | } 60 | } 61 | deserializer.deserialize_map(ExtensionsVisitor) 62 | } 63 | } 64 | 65 | impl Serialize for Extensions { 66 | fn serialize(&self, serializer: S) -> Result 67 | where 68 | S: Serializer, 69 | { 70 | let mut map = serializer.serialize_map(Some(self.0.len()))?; 71 | for (k, v) in self.0.clone() { 72 | map.serialize_entry(&k, &v)?; 73 | } 74 | map.end() 75 | } 76 | } 77 | 78 | #[cfg(test)] 79 | mod tests { 80 | use serde_json::Value; 81 | use serde_test::{assert_tokens, Token}; 82 | 83 | use crate::v3_0::extension::Extensions; 84 | 85 | #[test] 86 | fn test_serde_extensions() { 87 | let mut extensions = Extensions::default(); 88 | extensions.add(String::from("x-test"), Value::from("val")); 89 | assert_tokens( 90 | &extensions, 91 | &[ 92 | Token::Map { len: Some(1) }, 93 | Token::String("x-test"), 94 | Token::String("val"), 95 | Token::MapEnd, 96 | ], 97 | ) 98 | } 99 | 100 | #[test] 101 | fn test_get_extension() { 102 | let value = Value::from("val"); 103 | 104 | let mut extensions = Extensions::default(); 105 | extensions.add(String::from("x-test"), value.clone()); 106 | 107 | assert_eq!(extensions.get("x-test"), Some(&value)); 108 | } 109 | 110 | #[test] 111 | fn test_all_extensions() { 112 | let value = Value::from("val"); 113 | 114 | let mut extensions = Extensions::default(); 115 | extensions.add(String::from("x-test"), value.clone()); 116 | 117 | assert_eq!( 118 | extensions.all().get_key_value("x-test"), 119 | Some((&"x-test".to_string(), &value)) 120 | ); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/v3_0/mod.rs: -------------------------------------------------------------------------------- 1 | //! Support for OpenApi version 3.0.1 specification. 2 | //! 3 | //! See the 4 | //! [specification](https://github.com/OAI/OpenAPI-Specification/blob/0dd79f6/versions/3.0.1.md) 5 | //! for more information. 6 | 7 | mod components; 8 | mod extension; 9 | mod schema; 10 | 11 | pub use crate::v3_0::{components::*, extension::*, schema::*}; 12 | 13 | // Yet OpenAPI dont have an implemented representation 14 | // the `serde_json::Value` is used in place of a custom enum 15 | // We re-expose the `serde_json::Value`, this way users does not have to include the dependency. 16 | pub use serde_json::Value; 17 | -------------------------------------------------------------------------------- /src/v3_0/schema.rs: -------------------------------------------------------------------------------- 1 | //! Schema specification for [OpenAPI 3.0.0](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md) 2 | 3 | use crate::v3_0::extension::Extensions; 4 | use serde::{Deserialize, Serialize}; 5 | use std::collections::{BTreeMap, HashMap}; 6 | use url::Url; 7 | 8 | use crate::{ 9 | v3_0::components::{BooleanObjectOrReference, Components, ObjectOrReference}, 10 | Error, Result, MINIMUM_OPENAPI30_VERSION, 11 | }; 12 | 13 | impl Spec { 14 | pub fn validate_version(&self) -> Result { 15 | let spec_version = &self.openapi; 16 | let sem_ver = semver::Version::parse(spec_version)?; 17 | let required_version = semver::VersionReq::parse(MINIMUM_OPENAPI30_VERSION).unwrap(); 18 | if required_version.matches(&sem_ver) { 19 | Ok(sem_ver) 20 | } else { 21 | Err(Error::UnsupportedSpecFileVersion(sem_ver)) 22 | } 23 | } 24 | } 25 | 26 | /// top level document 27 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 28 | pub struct Spec { 29 | /// This string MUST be the [semantic version number](https://semver.org/spec/v2.0.0.html) 30 | /// of the 31 | /// [OpenAPI Specification version](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#versions) 32 | /// that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling 33 | /// specifications and clients to interpret the OpenAPI document. This is not related to 34 | /// the API 35 | /// [`info.version`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#infoVersion) 36 | /// string. 37 | pub openapi: String, 38 | /// Provides metadata about the API. The metadata MAY be used by tooling as required. 39 | pub info: Info, 40 | /// An array of Server Objects, which provide connectivity information to a target server. 41 | /// If the `servers` property is not provided, or is an empty array, the default value would 42 | /// be a 43 | /// [Server Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#serverObject) 44 | /// with a 45 | /// [url](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#serverUrl) 46 | /// value of `/`. 47 | // FIXME: Provide a default value as specified in documentation instead of `None`. 48 | #[serde(skip_serializing_if = "Option::is_none")] 49 | pub servers: Option>, 50 | 51 | /// Holds the relative paths to the individual endpoints and their operations. The path is 52 | /// appended to the URL from the 53 | /// [`Server Object`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#serverObject) 54 | /// in order to construct the full URL. The Paths MAY be empty, due to 55 | /// [ACL constraints](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#securityFiltering). 56 | pub paths: BTreeMap, 57 | 58 | /// An element to hold various schemas for the specification. 59 | #[serde(skip_serializing_if = "Option::is_none")] 60 | pub components: Option, 61 | 62 | // FIXME: Implement 63 | // /// A declaration of which security mechanisms can be used across the API. 64 | // /// The list of values includes alternative security requirement objects that can be used. 65 | // /// Only one of the security requirement objects need to be satisfied to authorize a request. 66 | // /// Individual operations can override this definition. 67 | // #[serde(skip_serializing_if = "Option::is_none")] 68 | // pub security: Option, 69 | /// A list of tags used by the specification with additional metadata. 70 | ///The order of the tags can be used to reflect on their order by the parsing tools. 71 | /// Not all tags that are used by the 72 | /// [Operation Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#operationObject) 73 | /// must be declared. The tags that are not declared MAY be organized randomly or 74 | /// based on the tools' logic. Each tag name in the list MUST be unique. 75 | #[serde(skip_serializing_if = "Option::is_none")] 76 | pub tags: Option>, 77 | 78 | /// Additional external documentation. 79 | #[serde(skip_serializing_if = "Option::is_none", rename = "externalDocs")] 80 | pub external_docs: Option, 81 | #[serde(flatten)] 82 | pub extensions: Extensions, 83 | } 84 | 85 | /// General information about the API. 86 | /// 87 | /// 88 | /// See . 89 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 90 | // #[serde(rename_all = "lowercase")] 91 | pub struct Info { 92 | /// The title of the application. 93 | pub title: String, 94 | /// A short description of the application. CommonMark syntax MAY be used for rich text representation. 95 | #[serde(skip_serializing_if = "Option::is_none")] 96 | pub description: Option, 97 | /// A URL to the Terms of Service for the API. MUST be in the format of a URL. 98 | #[serde(rename = "termsOfService", skip_serializing_if = "Option::is_none")] 99 | pub terms_of_service: Option, 100 | /// The version of the OpenAPI document (which is distinct from the [OpenAPI Specification 101 | /// version](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oasVersion) 102 | /// or the API implementation version). 103 | pub version: String, 104 | /// The contact information for the exposed API. 105 | #[serde(skip_serializing_if = "Option::is_none")] 106 | pub contact: Option, 107 | /// The license information for the exposed API. 108 | #[serde(skip_serializing_if = "Option::is_none")] 109 | pub license: Option, 110 | } 111 | 112 | /// Contact information for the exposed API. 113 | /// 114 | /// See . 115 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 116 | pub struct Contact { 117 | #[serde(skip_serializing_if = "Option::is_none")] 118 | pub name: Option, 119 | 120 | #[serde(skip_serializing_if = "Option::is_none")] 121 | pub url: Option, 122 | 123 | // TODO: Make sure the email is a valid email 124 | #[serde(skip_serializing_if = "Option::is_none")] 125 | pub email: Option, 126 | #[serde(flatten)] 127 | pub extensions: Extensions, 128 | } 129 | 130 | /// License information for the exposed API. 131 | /// 132 | /// See . 133 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 134 | pub struct License { 135 | /// The license name used for the API. 136 | pub name: String, 137 | /// A URL to the license used for the API. 138 | #[serde(skip_serializing_if = "Option::is_none")] 139 | pub url: Option, 140 | #[serde(flatten)] 141 | pub extensions: Extensions, 142 | } 143 | 144 | /// An object representing a Server. 145 | /// 146 | /// See . 147 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 148 | pub struct Server { 149 | /// A URL to the target host. This URL supports Server Variables and MAY be relative, to 150 | /// indicate that the host location is relative to the location where the OpenAPI document 151 | /// is being served. Variable substitutions will be made when a variable is named 152 | /// in {brackets}. 153 | pub url: String, 154 | /// An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text representation. 155 | #[serde(skip_serializing_if = "Option::is_none")] 156 | pub description: Option, 157 | /// A map between a variable name and its value. The value is used for substitution in 158 | /// the server's URL template. 159 | #[serde(skip_serializing_if = "Option::is_none")] 160 | pub variables: Option>, 161 | } 162 | 163 | /// An object representing a Server Variable for server URL template substitution. 164 | /// 165 | /// See . 166 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 167 | pub struct ServerVariable { 168 | /// The default value to use for substitution, and to send, if an alternate value is not 169 | /// supplied. Unlike the Schema Object's default, this value MUST be provided by the consumer. 170 | pub default: String, 171 | /// An enumeration of string values to be used if the substitution options are from a limited 172 | /// set. 173 | #[serde(rename = "enum", skip_serializing_if = "Option::is_none")] 174 | pub substitutions_enum: Option>, 175 | /// An optional description for the server variable. [CommonMark] syntax MAY be used for rich 176 | /// text representation. 177 | /// 178 | /// [CommonMark]: https://spec.commonmark.org/ 179 | #[serde(skip_serializing_if = "Option::is_none")] 180 | pub description: Option, 181 | } 182 | 183 | /// Describes the operations available on a single path. 184 | /// 185 | /// A Path Item MAY be empty, due to [ACL 186 | /// constraints](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#securityFiltering). 187 | /// The path itself is still exposed to the documentation viewer but they will not know which 188 | /// operations and parameters are available. 189 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 190 | pub struct PathItem { 191 | /// Allows for an external definition of this path item. The referenced structure MUST be 192 | /// in the format of a 193 | /// [Path Item Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#pathItemObject). 194 | /// If there are conflicts between the referenced definition and this Path Item's definition, 195 | /// the behavior is undefined. 196 | // FIXME: Should this ref be moved to an enum? 197 | #[serde(skip_serializing_if = "Option::is_none", rename = "$ref")] 198 | pub reference: Option, 199 | 200 | /// An optional, string summary, intended to apply to all operations in this path. 201 | #[serde(skip_serializing_if = "Option::is_none")] 202 | pub summary: Option, 203 | /// An optional, string description, intended to apply to all operations in this path. 204 | /// [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation. 205 | #[serde(skip_serializing_if = "Option::is_none")] 206 | pub description: Option, 207 | 208 | /// A definition of a GET operation on this path. 209 | #[serde(skip_serializing_if = "Option::is_none")] 210 | pub get: Option, 211 | /// A definition of a PUT operation on this path. 212 | #[serde(skip_serializing_if = "Option::is_none")] 213 | pub put: Option, 214 | /// A definition of a POST operation on this path. 215 | #[serde(skip_serializing_if = "Option::is_none")] 216 | pub post: Option, 217 | /// A definition of a DELETE operation on this path. 218 | #[serde(skip_serializing_if = "Option::is_none")] 219 | pub delete: Option, 220 | /// A definition of a OPTIONS operation on this path. 221 | #[serde(skip_serializing_if = "Option::is_none")] 222 | pub options: Option, 223 | /// A definition of a HEAD operation on this path. 224 | #[serde(skip_serializing_if = "Option::is_none")] 225 | pub head: Option, 226 | /// A definition of a PATCH operation on this path. 227 | #[serde(skip_serializing_if = "Option::is_none")] 228 | pub patch: Option, 229 | /// A definition of a TRACE operation on this path. 230 | #[serde(skip_serializing_if = "Option::is_none")] 231 | pub trace: Option, 232 | 233 | /// An alternative `server` array to service all operations in this path. 234 | #[serde(skip_serializing_if = "Option::is_none")] 235 | pub servers: Option>, 236 | 237 | /// A list of parameters that are applicable for all the operations described under this 238 | /// path. These parameters can be overridden at the operation level, but cannot be removed 239 | /// there. The list MUST NOT include duplicated parameters. A unique parameter is defined by 240 | /// a combination of a 241 | /// [name](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterName) 242 | /// and 243 | /// [location](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterIn). 244 | /// The list can use the 245 | /// [Reference Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#referenceObject) 246 | /// to link to parameters that are defined at the 247 | /// [OpenAPI Object's components/parameters](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#componentsParameters). 248 | #[serde(skip_serializing_if = "Option::is_none")] 249 | pub parameters: Option>>, 250 | #[serde(flatten)] 251 | pub extensions: Extensions, 252 | } 253 | /// Describes a single API operation on a path. 254 | /// 255 | /// See . 256 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 257 | // #[serde(rename_all = "lowercase")] 258 | pub struct Operation { 259 | /// A list of tags for API documentation control. Tags can be used for logical grouping of 260 | /// operations by resources or any other qualifier. 261 | #[serde(skip_serializing_if = "Option::is_none")] 262 | pub tags: Option>, 263 | /// A short summary of what the operation does. 264 | #[serde(skip_serializing_if = "Option::is_none")] 265 | pub summary: Option, 266 | /// A verbose explanation of the operation behavior. 267 | /// [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation. 268 | #[serde(skip_serializing_if = "Option::is_none")] 269 | pub description: Option, 270 | /// Additional external documentation for this operation. 271 | #[serde(skip_serializing_if = "Option::is_none", rename = "externalDocs")] 272 | pub external_docs: Option, 273 | /// Unique string used to identify the operation. The id MUST be unique among all operations 274 | /// described in the API. Tools and libraries MAY use the operationId to uniquely identify an 275 | /// operation, therefore, it is RECOMMENDED to follow common programming naming conventions. 276 | #[serde(skip_serializing_if = "Option::is_none", rename = "operationId")] 277 | pub operation_id: Option, 278 | 279 | /// A list of parameters that are applicable for this operation. If a parameter is already 280 | /// defined at the 281 | /// [Path Item](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#pathItemParameters), 282 | /// the new definition will override it but can never remove it. The list MUST NOT 283 | /// include duplicated parameters. A unique parameter is defined by a combination of a 284 | /// [name](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterName) 285 | /// and 286 | /// [location](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterIn). 287 | /// The list can use the 288 | /// [Reference Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#referenceObject) 289 | /// to link to parameters that are defined at the 290 | /// [OpenAPI Object's components/parameters](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#componentsParameters). 291 | #[serde(skip_serializing_if = "Option::is_none")] 292 | pub parameters: Option>>, 293 | 294 | /// The request body applicable for this operation. The requestBody is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers. 295 | #[serde(skip_serializing_if = "Option::is_none", rename = "requestBody")] 296 | pub request_body: Option>, 297 | 298 | /// The list of possible responses as they are returned from executing this operation. 299 | /// 300 | /// A container for the expected responses of an operation. The container maps a HTTP 301 | /// response code to the expected response. 302 | /// 303 | /// The documentation is not necessarily expected to cover all possible HTTP response codes 304 | /// because they may not be known in advance. However, documentation is expected to cover 305 | /// a successful operation response and any known errors. 306 | /// 307 | /// The `default` MAY be used as a default response object for all HTTP codes that are not 308 | /// covered individually by the specification. 309 | /// 310 | /// The `Responses Object` MUST contain at least one response code, and it SHOULD be the 311 | /// response for a successful operation call. 312 | /// 313 | /// See . 314 | pub responses: BTreeMap, 315 | 316 | /// A map of possible out-of band callbacks related to the parent operation. The key is 317 | /// a unique identifier for the Callback Object. Each value in the map is a 318 | /// [Callback Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#callbackObject) 319 | /// that describes a request that may be initiated by the API provider and the 320 | /// expected responses. The key value used to identify the callback object is 321 | /// an expression, evaluated at runtime, that identifies a URL to use for the 322 | /// callback operation. 323 | #[serde(skip_serializing_if = "Option::is_none")] 324 | pub callbacks: Option>, 325 | 326 | /// Declares this operation to be deprecated. Consumers SHOULD refrain from usage 327 | /// of the declared operation. Default value is `false`. 328 | #[serde(skip_serializing_if = "Option::is_none")] 329 | pub deprecated: Option, 330 | 331 | // FIXME: Implement 332 | // /// A declaration of which security mechanisms can be used for this operation. The list of 333 | // /// values includes alternative security requirement objects that can be used. Only one 334 | // /// of the security requirement objects need to be satisfied to authorize a request. 335 | // /// This definition overrides any declared top-level 336 | // /// [`security`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oasSecurity). 337 | // /// To remove a top-level security declaration, an empty array can be used. 338 | // pub security: Option, 339 | /// An alternative `server` array to service this operation. If an alternative `server` 340 | /// object is specified at the Path Item Object or Root level, it will be overridden by 341 | /// this value. 342 | #[serde(skip_serializing_if = "Option::is_none")] 343 | pub servers: Option>, 344 | #[serde(flatten)] 345 | pub extensions: Extensions, 346 | } 347 | 348 | // FIXME: Verify against OpenAPI 3.0 349 | /// Describes a single operation parameter. 350 | /// A unique parameter is defined by a combination of a 351 | /// [name](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterName) 352 | /// and [location](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterIn). 353 | /// 354 | /// See . 355 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 356 | pub struct Parameter { 357 | /// The name of the parameter. 358 | pub name: String, 359 | /// values depend on parameter type 360 | /// may be `header`, `query`, 'path`, `formData` 361 | #[serde(rename = "in")] 362 | pub location: String, 363 | #[serde(skip_serializing_if = "Option::is_none")] 364 | pub required: Option, 365 | #[serde(skip_serializing_if = "Option::is_none")] 366 | pub schema: Option, 367 | #[serde(skip_serializing_if = "Option::is_none")] 368 | #[serde(rename = "uniqueItems")] 369 | pub unique_items: Option, 370 | /// string, number, boolean, integer, array, file ( only for formData ) 371 | #[serde(skip_serializing_if = "Option::is_none")] 372 | #[serde(rename = "type")] 373 | pub param_type: Option, 374 | #[serde(skip_serializing_if = "Option::is_none")] 375 | pub format: Option, 376 | /// A brief description of the parameter. This could contain examples 377 | /// of use. GitHub Flavored Markdown is allowed. 378 | #[serde(skip_serializing_if = "Option::is_none")] 379 | pub description: Option, 380 | // collectionFormat: ??? 381 | // default: ??? 382 | // maximum ? 383 | // exclusiveMaximum ?? 384 | // minimum ?? 385 | // exclusiveMinimum ?? 386 | // maxLength ?? 387 | // minLength ?? 388 | // pattern ?? 389 | // maxItems ?? 390 | // minItems ?? 391 | // enum ?? 392 | // multipleOf ?? 393 | // allowEmptyValue ( for query / body params ) 394 | /// Describes how the parameter value will be serialized depending on the type of the parameter 395 | /// value. Default values (based on value of in): for `query` - `form`; for `path` - `simple`; for 396 | /// `header` - `simple`; for cookie - `form`. 397 | #[serde(skip_serializing_if = "Option::is_none")] 398 | style: Option, 399 | } 400 | 401 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 402 | #[serde(rename_all = "camelCase")] 403 | enum ParameterStyle { 404 | Matrix, 405 | Label, 406 | Form, 407 | Simple, 408 | SpaceDelimited, 409 | PipeDelimited, 410 | DeepObject, 411 | } 412 | 413 | // FIXME: Verify against OpenAPI 3.0 414 | /// The Schema Object allows the definition of input and output data types. 415 | /// These types can be objects, but also primitives and arrays. 416 | /// This object is an extended subset of the 417 | /// [JSON Schema Specification Wright Draft 00](http://json-schema.org/). 418 | /// For more information about the properties, see 419 | /// [JSON Schema Core](https://tools.ietf.org/html/draft-wright-json-schema-00) and 420 | /// [JSON Schema Validation](https://tools.ietf.org/html/draft-wright-json-schema-validation-00). 421 | /// Unless stated otherwise, the property definitions follow the JSON Schema. 422 | /// 423 | /// See . 424 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 425 | pub struct Schema { 426 | /// [JSON reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) 427 | /// path to another definition 428 | #[serde(skip_serializing_if = "Option::is_none")] 429 | #[serde(rename = "$ref")] 430 | pub ref_path: Option, 431 | 432 | #[serde(skip_serializing_if = "Option::is_none")] 433 | pub description: Option, 434 | 435 | #[serde(skip_serializing_if = "Option::is_none")] 436 | #[serde(rename = "type")] 437 | pub schema_type: Option, 438 | 439 | #[serde(skip_serializing_if = "Option::is_none")] 440 | pub format: Option, 441 | 442 | #[serde(skip_serializing_if = "Option::is_none")] 443 | #[serde(rename = "enum")] 444 | pub enum_values: Option>, 445 | 446 | #[serde(skip_serializing_if = "Option::is_none")] 447 | pub required: Option>, 448 | 449 | #[serde(skip_serializing_if = "Option::is_none")] 450 | pub items: Option>, 451 | 452 | #[serde(skip_serializing_if = "Option::is_none")] 453 | pub properties: Option>, 454 | 455 | #[serde(skip_serializing_if = "Option::is_none", rename = "readOnly")] 456 | pub read_only: Option, 457 | 458 | #[serde(skip_serializing_if = "Option::is_none")] 459 | pub nullable: Option, 460 | 461 | /// Value can be boolean or object. Inline or referenced schema MUST be of a 462 | /// [Schema Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#schemaObject) 463 | /// and not a standard JSON Schema. 464 | /// 465 | /// See . 466 | #[serde( 467 | skip_serializing_if = "Option::is_none", 468 | rename = "additionalProperties" 469 | )] 470 | pub additional_properties: Option>>, 471 | 472 | /// A free-form property to include an example of an instance for this schema. 473 | /// To represent examples that cannot be naturally represented in JSON or YAML, 474 | /// a string value can be used to contain the example with escaping where necessary. 475 | /// NOTE: According to [spec], _Primitive data types in the OAS are based on the 476 | /// types supported by the JSON Schema Specification Wright Draft 00._ 477 | /// This suggest using 478 | /// [`serde_json::Value`](https://docs.serde.rs/serde_json/value/enum.Value.html). [spec][https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#data-types] 479 | #[serde(skip_serializing_if = "Option::is_none")] 480 | pub example: Option, 481 | 482 | #[serde(skip_serializing_if = "Option::is_none")] 483 | pub title: Option, 484 | 485 | // The following properties are taken directly from the JSON Schema definition and 486 | // follow the same specifications: 487 | #[serde(skip_serializing_if = "Option::is_none", rename = "multipleOf")] 488 | pub multiple_of: Option, 489 | 490 | #[serde(skip_serializing_if = "Option::is_none")] 491 | pub maximum: Option, 492 | 493 | #[serde(skip_serializing_if = "Option::is_none", rename = "exclusiveMaximum")] 494 | pub exclusive_maximum: Option, 495 | 496 | #[serde(skip_serializing_if = "Option::is_none")] 497 | pub minimum: Option, 498 | 499 | #[serde(skip_serializing_if = "Option::is_none", rename = "exclusiveMinimum")] 500 | pub exclusive_minimum: Option, 501 | 502 | #[serde(skip_serializing_if = "Option::is_none", rename = "maxLength")] 503 | pub max_length: Option, 504 | 505 | #[serde(skip_serializing_if = "Option::is_none", rename = "minLength")] 506 | pub min_length: Option, 507 | 508 | #[serde(skip_serializing_if = "Option::is_none")] 509 | pub pattern: Option, 510 | 511 | #[serde(skip_serializing_if = "Option::is_none", rename = "maxItems")] 512 | pub max_items: Option, 513 | 514 | #[serde(skip_serializing_if = "Option::is_none", rename = "minItems")] 515 | pub min_items: Option, 516 | 517 | #[serde(skip_serializing_if = "Option::is_none", rename = "uniqueItems")] 518 | pub unique_items: Option, 519 | 520 | #[serde(skip_serializing_if = "Option::is_none", rename = "maxProperties")] 521 | pub max_properties: Option, 522 | 523 | #[serde(skip_serializing_if = "Option::is_none", rename = "minProperties")] 524 | pub min_properties: Option, 525 | 526 | // The following properties are taken from the JSON Schema definition but their 527 | // definitions were adjusted to the OpenAPI Specification. 528 | // - type - Value MUST be a string. Multiple types via an array are not supported. 529 | // - allOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. 530 | // - oneOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. 531 | // - anyOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. 532 | // - not - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. 533 | // - items - Value MUST be an object and not an array. Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. `items` MUST be present if the `type` is `array`. 534 | // - properties - Property definitions MUST be a [Schema Object](#schemaObject) and not a standard JSON Schema (inline or referenced). 535 | // - additionalProperties - Value can be boolean or object. Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. 536 | // - description - [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation. 537 | // - format - See [Data Type Formats](#dataTypeFormat) for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats. 538 | // - default - The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level. For example, if `type` is `string`, then `default` can be `"foo"` but cannot be `1`. 539 | /// The default value represents what would be assumed by the consumer of the input as the value 540 | /// of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the 541 | /// defined type for the Schema Object defined at the same level. For example, if type is 542 | /// `string`, then `default` can be `"foo"` but cannot be `1`. 543 | #[serde(skip_serializing_if = "Option::is_none")] 544 | pub default: Option, 545 | 546 | /// Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard 547 | /// JSON Schema. 548 | /// [allOf](https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/#allof) 549 | #[serde(rename = "allOf", skip_serializing_if = "Option::is_none")] 550 | pub all_of: Option>>, 551 | 552 | /// Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard 553 | /// JSON Schema. 554 | /// [oneOf](https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/#oneof) 555 | #[serde(rename = "oneOf", skip_serializing_if = "Option::is_none")] 556 | pub one_of: Option>>, 557 | 558 | /// Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard 559 | /// JSON Schema. 560 | /// [anyOf](https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/#anyof) 561 | #[serde(rename = "anyOf", skip_serializing_if = "Option::is_none")] 562 | pub any_of: Option>>, 563 | 564 | /// Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard 565 | /// JSON Schema. 566 | /// [not](https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/#not) 567 | #[serde(rename = "not", skip_serializing_if = "Option::is_none")] 568 | pub not: Option>>, 569 | 570 | /// [Specification extensions](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specificationExtensions) 571 | #[serde(flatten)] 572 | pub extensions: HashMap, 573 | } 574 | 575 | /// Describes a single response from an API Operation, including design-time, static `links` 576 | /// to operations based on the response. 577 | /// 578 | /// See . 579 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 580 | pub struct Response { 581 | /// A short description of the response. 582 | /// [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation. 583 | pub description: Option, 584 | 585 | /// Maps a header name to its definition. 586 | /// [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case 587 | /// insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL 588 | /// be ignored. 589 | #[serde(skip_serializing_if = "Option::is_none")] 590 | pub headers: Option>>, 591 | 592 | /// A map containing descriptions of potential response payloads. The key is a media type 593 | /// or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value 594 | /// describes it. For responses that match multiple keys, only the most specific key is 595 | /// applicable. e.g. text/plain overrides text/* 596 | #[serde(skip_serializing_if = "Option::is_none")] 597 | pub content: Option>, 598 | 599 | /// A map of operations links that can be followed from the response. The key of the map 600 | /// is a short name for the link, following the naming constraints of the names for 601 | /// [Component Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#componentsObject). 602 | #[serde(skip_serializing_if = "Option::is_none")] 603 | pub links: Option>>, 604 | #[serde(flatten)] 605 | pub extensions: Extensions, 606 | } 607 | 608 | /// The Header Object follows the structure of the 609 | /// [Parameter Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterObject) 610 | /// with the following changes: 611 | /// 1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. 612 | /// 1. `in` MUST NOT be specified, it is implicitly in `header`. 613 | /// 1. All traits that are affected by the location MUST be applicable to a location of 614 | /// `header` (for example, [`style`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterStyle)). 615 | /// 616 | /// See . 617 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 618 | pub struct Header { 619 | // FIXME: Is the third change properly implemented? 620 | // FIXME: Merge `ObjectOrReference

::Reference` and `ParameterOrRef::Reference` 621 | #[serde(skip_serializing_if = "Option::is_none")] 622 | pub required: Option, 623 | #[serde(skip_serializing_if = "Option::is_none")] 624 | pub schema: Option, 625 | #[serde(skip_serializing_if = "Option::is_none")] 626 | #[serde(rename = "uniqueItems")] 627 | pub unique_items: Option, 628 | /// string, number, boolean, integer, array, file ( only for formData ) 629 | #[serde(skip_serializing_if = "Option::is_none")] 630 | #[serde(rename = "type")] 631 | pub param_type: Option, 632 | #[serde(skip_serializing_if = "Option::is_none")] 633 | pub format: Option, 634 | /// A brief description of the parameter. This could contain examples 635 | /// of use. GitHub Flavored Markdown is allowed. 636 | #[serde(skip_serializing_if = "Option::is_none")] 637 | pub description: Option, 638 | // collectionFormat: ??? 639 | // default: ??? 640 | // maximum ? 641 | // exclusiveMaximum ?? 642 | // minimum ?? 643 | // exclusiveMinimum ?? 644 | // maxLength ?? 645 | // minLength ?? 646 | // pattern ?? 647 | // maxItems ?? 648 | // minItems ?? 649 | // enum ?? 650 | // multipleOf ?? 651 | // allowEmptyValue ( for query / body params ) 652 | } 653 | 654 | /// Describes a single request body. 655 | /// 656 | /// See . 657 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 658 | pub struct RequestBody { 659 | /// A brief description of the request body. This could contain examples of use. 660 | /// [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation. 661 | #[serde(skip_serializing_if = "Option::is_none")] 662 | pub description: Option, 663 | 664 | /// The content of the request body. The key is a media type or 665 | /// [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the 666 | /// value describes it. For requests that match multiple keys, only the most specific key 667 | /// is applicable. e.g. text/plain overrides text/* 668 | pub content: BTreeMap, 669 | 670 | #[serde(skip_serializing_if = "Option::is_none")] 671 | pub required: Option, 672 | } 673 | 674 | /// The Link object represents a possible design-time link for a response. 675 | /// 676 | /// The presence of a link does not guarantee the caller's ability to successfully invoke it, 677 | /// rather it provides a known relationship and traversal mechanism between responses and 678 | /// other operations. 679 | /// 680 | /// Unlike _dynamic_ links (i.e. links provided *in* the response payload), the OAS linking 681 | /// mechanism does not require link information in the runtime response. 682 | /// 683 | /// For computing links, and providing instructions to execute them, a 684 | /// [runtime expression](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#runtimeExpression) 685 | /// is used for accessing values in an operation and using them as parameters while invoking 686 | /// the linked operation. 687 | /// 688 | /// See . 689 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 690 | #[serde(untagged)] 691 | pub enum Link { 692 | /// A relative or absolute reference to an OAS operation. This field is mutually exclusive 693 | /// of the `operationId` field, and MUST point to an 694 | /// [Operation Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#operationObject). 695 | /// Relative `operationRef` values MAY be used to locate an existing 696 | /// [Operation Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#operationObject) 697 | /// in the OpenAPI definition. 698 | Ref { 699 | #[serde(rename = "operationRef")] 700 | operation_ref: String, 701 | 702 | // FIXME: Implement 703 | // /// A map representing parameters to pass to an operation as specified with `operationId` 704 | // /// or identified via `operationRef`. The key is the parameter name to be used, whereas 705 | // /// the value can be a constant or an expression to be evaluated and passed to the 706 | // /// linked operation. The parameter name can be qualified using the 707 | // /// [parameter location](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterIn) 708 | // /// `[{in}.]{name}` for operations that use the same parameter name in different 709 | // /// locations (e.g. path.id). 710 | // parameters: BTreeMap, 711 | #[serde(skip_serializing_if = "Option::is_none")] 712 | parameters: Option>, 713 | 714 | // FIXME: Implement 715 | // /// A literal value or 716 | // /// [{expression}](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#runtimeExpression) 717 | // /// to use as a request body when calling the target operation. 718 | // #[serde(rename = "requestBody")] 719 | // request_body: Any | {expression} 720 | /// A description of the link. [CommonMark syntax](http://spec.commonmark.org/) MAY be 721 | /// used for rich text representation. 722 | #[serde(skip_serializing_if = "Option::is_none")] 723 | description: Option, 724 | 725 | /// A server object to be used by the target operation. 726 | #[serde(skip_serializing_if = "Option::is_none")] 727 | server: Option, 728 | #[serde(flatten)] 729 | extensions: Extensions, 730 | }, 731 | /// The name of an _existing_, resolvable OAS operation, as defined with a unique 732 | /// `operationId`. This field is mutually exclusive of the `operationRef` field. 733 | Id { 734 | #[serde(rename = "operationId")] 735 | operation_id: String, 736 | 737 | // FIXME: Implement 738 | // /// A map representing parameters to pass to an operation as specified with `operationId` 739 | // /// or identified via `operationRef`. The key is the parameter name to be used, whereas 740 | // /// the value can be a constant or an expression to be evaluated and passed to the 741 | // /// linked operation. The parameter name can be qualified using the 742 | // /// [parameter location](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterIn) 743 | // /// `[{in}.]{name}` for operations that use the same parameter name in different 744 | // /// locations (e.g. path.id). 745 | // parameters: BTreeMap, 746 | #[serde(skip_serializing_if = "Option::is_none")] 747 | parameters: Option>, 748 | 749 | // FIXME: Implement 750 | // /// A literal value or 751 | // /// [{expression}](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#runtimeExpression) 752 | // /// to use as a request body when calling the target operation. 753 | // #[serde(rename = "requestBody")] 754 | // request_body: Any | {expression} 755 | /// A description of the link. [CommonMark syntax](http://spec.commonmark.org/) MAY be 756 | /// used for rich text representation. 757 | #[serde(skip_serializing_if = "Option::is_none")] 758 | description: Option, 759 | 760 | /// A server object to be used by the target operation. 761 | #[serde(skip_serializing_if = "Option::is_none")] 762 | server: Option, 763 | #[serde(flatten)] 764 | extensions: Extensions, 765 | }, 766 | } 767 | 768 | /// Each Media Type Object provides schema and examples for the media type identified by its key. 769 | /// 770 | /// See . 771 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 772 | pub struct MediaType { 773 | /// The schema defining the type used for the request body. 774 | #[serde(skip_serializing_if = "Option::is_none")] 775 | pub schema: Option>, 776 | 777 | /// Example of the media type. 778 | #[serde(flatten, skip_serializing_if = "Option::is_none")] 779 | pub examples: Option, 780 | 781 | /// A map between a property name and its encoding information. The key, being the 782 | /// property name, MUST exist in the schema as a property. The encoding object SHALL 783 | /// only apply to `requestBody` objects when the media type is `multipart` 784 | /// or `application/x-www-form-urlencoded`. 785 | #[serde(skip_serializing_if = "Option::is_none")] 786 | pub encoding: Option>, 787 | } 788 | 789 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 790 | #[serde(untagged)] 791 | pub enum MediaTypeExample { 792 | /// Example of the media type. The example object SHOULD be in the correct format as 793 | /// specified by the media type. The `example` field is mutually exclusive of the 794 | /// `examples` field. Furthermore, if referencing a `schema` which contains an example, 795 | /// the `example` value SHALL override the example provided by the schema. 796 | Example { example: serde_json::Value }, 797 | /// Examples of the media type. Each example object SHOULD match the media type and 798 | /// specified schema if present. The `examples` field is mutually exclusive of 799 | /// the `example` field. Furthermore, if referencing a `schema` which contains an 800 | /// example, the `examples` value SHALL override the example provided by the schema. 801 | Examples { 802 | examples: BTreeMap>, 803 | }, 804 | } 805 | 806 | /// A single encoding definition applied to a single schema property. 807 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 808 | pub struct Encoding { 809 | /// The Content-Type for encoding a specific property. Default value depends on the 810 | /// property type: for `string` with `format` being `binary` – `application/octet-stream`; 811 | /// for other primitive types – `text/plain`; for `object` - `application/json`; 812 | /// for `array` – the default is defined based on the inner type. The value can be a 813 | /// specific media type (e.g. `application/json`), a wildcard media type 814 | /// (e.g. `image/*`), or a comma-separated list of the two types. 815 | #[serde(skip_serializing_if = "Option::is_none", rename = "contentType")] 816 | pub content_type: Option, 817 | 818 | /// A map allowing additional information to be provided as headers, for example 819 | /// `Content-Disposition`. `Content-Type` is described separately and SHALL be 820 | /// ignored in this section. This property SHALL be ignored if the request body 821 | /// media type is not a `multipart`. 822 | #[serde(skip_serializing_if = "Option::is_none")] 823 | pub headers: Option>>, 824 | 825 | /// Describes how a specific property value will be serialized depending on its type. 826 | /// See [Parameter Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterObject) 827 | /// for details on the 828 | /// [`style`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#parameterStyle) 829 | /// property. The behavior follows the same values as `query` parameters, including 830 | /// default values. This property SHALL be ignored if the request body media type 831 | /// is not `application/x-www-form-urlencoded`. 832 | #[serde(skip_serializing_if = "Option::is_none")] 833 | pub style: Option, 834 | 835 | /// When this is true, property values of type `array` or `object` generate 836 | /// separate parameters for each value of the array, or key-value-pair of the map. 837 | /// For other types of properties this property has no effect. When 838 | /// [`style`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#encodingStyle) 839 | /// is `form`, the default value is `true`. For all other styles, the default value 840 | /// is `false`. This property SHALL be ignored if the request body media type is 841 | /// not `application/x-www-form-urlencoded`. 842 | #[serde(skip_serializing_if = "Option::is_none")] 843 | pub explode: Option, 844 | 845 | /// Determines whether the parameter value SHOULD allow reserved characters, as defined 846 | /// by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` 847 | /// to be included without percent-encoding. The default value is `false`. This 848 | /// property SHALL be ignored if the request body media type is 849 | /// not `application/x-www-form-urlencoded`. 850 | #[serde(skip_serializing_if = "Option::is_none", rename = "allowReserved")] 851 | pub allow_reserved: Option, 852 | } 853 | 854 | /// See . 855 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 856 | pub struct Example { 857 | /// Short description for the example. 858 | #[serde(skip_serializing_if = "Option::is_none")] 859 | pub summary: Option, 860 | 861 | /// Long description for the example. 862 | /// [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation. 863 | #[serde(skip_serializing_if = "Option::is_none")] 864 | pub description: Option, 865 | // FIXME: Implement (merge with externalValue as enum) 866 | /// Embedded literal example. The `value` field and `externalValue` field are mutually 867 | /// exclusive. To represent examples of media types that cannot naturally represented 868 | /// in JSON or YAML, use a string value to contain the example, escaping where necessary. 869 | #[serde(skip_serializing_if = "Option::is_none")] 870 | pub value: Option, 871 | // FIXME: Implement (merge with value as enum) 872 | // /// A URL that points to the literal example. This provides the capability to reference 873 | // /// examples that cannot easily be included in JSON or YAML documents. The `value` field 874 | // /// and `externalValue` field are mutually exclusive. 875 | // #[serde(skip_serializing_if = "Option::is_none")] 876 | // pub externalValue: Option, 877 | #[serde(flatten)] 878 | pub extensions: Extensions, 879 | } 880 | 881 | /// Defines a security scheme that can be used by the operations. Supported schemes are 882 | /// HTTP authentication, an API key (either as a header or as a query parameter), 883 | ///OAuth2's common flows (implicit, password, application and access code) as defined 884 | /// in [RFC6749](https://tools.ietf.org/html/rfc6749), and 885 | /// [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06). 886 | /// 887 | /// See . 888 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 889 | #[serde(tag = "type")] 890 | pub enum SecurityScheme { 891 | #[serde(rename = "apiKey")] 892 | ApiKey { 893 | name: String, 894 | #[serde(rename = "in")] 895 | location: String, 896 | }, 897 | #[serde(rename = "http")] 898 | Http { 899 | scheme: String, 900 | #[serde(rename = "bearerFormat")] 901 | bearer_format: String, 902 | }, 903 | #[serde(rename = "oauth2")] 904 | OAuth2 { flows: Flows }, 905 | #[serde(rename = "openIdConnect")] 906 | OpenIdConnect { 907 | #[serde(rename = "openIdConnectUrl")] 908 | open_id_connect_url: String, 909 | }, 910 | } 911 | 912 | /// Allows configuration of the supported OAuth Flows. 913 | /// See [link] 914 | /// [link][https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oauth-flows-object] 915 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 916 | #[serde(rename_all = "camelCase")] 917 | pub struct Flows { 918 | #[serde(skip_serializing_if = "Option::is_none")] 919 | pub implicit: Option, 920 | #[serde(skip_serializing_if = "Option::is_none")] 921 | pub password: Option, 922 | #[serde(skip_serializing_if = "Option::is_none")] 923 | pub client_credentials: Option, 924 | #[serde(skip_serializing_if = "Option::is_none")] 925 | pub authorization_code: Option, 926 | } 927 | 928 | /// Configuration details for a implicit OAuth Flow 929 | /// See [link] 930 | /// [link](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oauth-flow-object) 931 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 932 | #[serde(rename_all = "camelCase")] 933 | pub struct ImplicitFlow { 934 | pub authorization_url: Url, 935 | #[serde(skip_serializing_if = "Option::is_none")] 936 | pub refresh_url: Option, 937 | pub scopes: BTreeMap, 938 | } 939 | 940 | /// Configuration details for a password OAuth Flow 941 | /// See [link] 942 | /// [link](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oauth-flow-object 943 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 944 | #[serde(rename_all = "camelCase")] 945 | pub struct PasswordFlow { 946 | token_url: Url, 947 | #[serde(skip_serializing_if = "Option::is_none")] 948 | pub refresh_url: Option, 949 | pub scopes: BTreeMap, 950 | } 951 | 952 | /// Configuration details for a client credentials OAuth Flow 953 | /// See [link] 954 | /// [link](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oauth-flow-object 955 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 956 | #[serde(rename_all = "camelCase")] 957 | pub struct ClientCredentialsFlow { 958 | token_url: Url, 959 | #[serde(skip_serializing_if = "Option::is_none")] 960 | pub refresh_url: Option, 961 | pub scopes: BTreeMap, 962 | } 963 | 964 | /// Configuration details for a authorization code OAuth Flow 965 | /// See [link] 966 | /// [link](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oauth-flow-object 967 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 968 | #[serde(rename_all = "camelCase")] 969 | pub struct AuthorizationCodeFlow { 970 | pub authorization_url: Url, 971 | token_url: Url, 972 | #[serde(skip_serializing_if = "Option::is_none")] 973 | pub refresh_url: Option, 974 | pub scopes: BTreeMap, 975 | } 976 | 977 | // TODO: Implement 978 | /// A map of possible out-of band callbacks related to the parent operation. Each value in 979 | /// the map is a Path Item Object that describes a set of requests that may be initiated by 980 | /// the API provider and the expected responses. The key value used to identify the callback 981 | /// object is an expression, evaluated at runtime, that identifies a URL to use for the 982 | /// callback operation. 983 | /// 984 | /// See . 985 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 986 | pub struct Callback( 987 | /// A Path Item Object used to define a callback request and expected responses. 988 | serde_json::Value, // TODO: Add "Specification Extensions" https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#specificationExtensions} 989 | ); 990 | 991 | // FIXME: Implement 992 | // /// Allows configuration of the supported OAuth Flows. 993 | // /// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#oauthFlowsObject 994 | // #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 995 | // pub struct OAuthFlows { 996 | // } 997 | 998 | /// Adds metadata to a single tag that is used by the 999 | /// [Operation Object](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#operationObject). 1000 | /// It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. 1001 | /// 1002 | /// See . 1003 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Default)] 1004 | pub struct Tag { 1005 | /// The name of the tag. 1006 | pub name: String, 1007 | 1008 | /// A short description for the tag. 1009 | /// [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation. 1010 | #[serde(skip_serializing_if = "Option::is_none")] 1011 | pub description: Option, 1012 | // /// Additional external documentation for this tag. 1013 | // #[serde(skip_serializing_if = "Option::is_none")] 1014 | // pub external_docs: Option>, 1015 | #[serde(flatten)] 1016 | pub extensions: Extensions, 1017 | } 1018 | 1019 | /// Allows referencing an external resource for extended documentation. 1020 | /// 1021 | /// See . 1022 | #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] 1023 | pub struct ExternalDoc { 1024 | /// The URL for the target documentation. 1025 | pub url: Url, 1026 | 1027 | /// A short description of the target documentation. 1028 | /// [CommonMark syntax](http://spec.commonmark.org/) MAY be used for rich text representation. 1029 | #[serde(skip_serializing_if = "Option::is_none")] 1030 | pub description: Option, 1031 | #[serde(flatten)] 1032 | pub extensions: Extensions, 1033 | } 1034 | 1035 | #[cfg(test)] 1036 | mod tests { 1037 | use super::*; 1038 | 1039 | #[test] 1040 | fn test_security_scheme_oauth_deser() { 1041 | const IMPLICIT_OAUTH2_SAMPLE: &str = r#"{ 1042 | "type": "oauth2", 1043 | "flows": { 1044 | "implicit": { 1045 | "authorizationUrl": "https://example.com/api/oauth/dialog", 1046 | "scopes": { 1047 | "write:pets": "modify pets in your account", 1048 | "read:pets": "read your pets" 1049 | } 1050 | }, 1051 | "authorizationCode": { 1052 | "authorizationUrl": "https://example.com/api/oauth/dialog", 1053 | "tokenUrl": "https://example.com/api/oauth/token", 1054 | "scopes": { 1055 | "write:pets": "modify pets in your account", 1056 | "read:pets": "read your pets" 1057 | } 1058 | } 1059 | } 1060 | }"#; 1061 | let obj: SecurityScheme = serde_json::from_str(&IMPLICIT_OAUTH2_SAMPLE).unwrap(); 1062 | match obj { 1063 | SecurityScheme::OAuth2 { flows } => { 1064 | assert!(flows.implicit.is_some()); 1065 | let implicit = flows.implicit.unwrap(); 1066 | assert_eq!( 1067 | implicit.authorization_url, 1068 | Url::parse("https://example.com/api/oauth/dialog").unwrap() 1069 | ); 1070 | assert!(implicit.scopes.contains_key("write:pets")); 1071 | assert!(implicit.scopes.contains_key("read:pets")); 1072 | 1073 | assert!(flows.authorization_code.is_some()); 1074 | let auth_code = flows.authorization_code.unwrap(); 1075 | assert_eq!( 1076 | auth_code.authorization_url, 1077 | Url::parse("https://example.com/api/oauth/dialog").unwrap() 1078 | ); 1079 | assert_eq!( 1080 | auth_code.token_url, 1081 | Url::parse("https://example.com/api/oauth/token").unwrap() 1082 | ); 1083 | assert!(implicit.scopes.contains_key("write:pets")); 1084 | assert!(implicit.scopes.contains_key("read:pets")); 1085 | } 1086 | _ => assert!(false, "wrong security scheme type"), 1087 | } 1088 | } 1089 | } 1090 | --------------------------------------------------------------------------------