diff --git a/.changeset/openapi_31_support.md b/.changeset/openapi_31_support.md new file mode 100644 index 000000000..cf890d64b --- /dev/null +++ b/.changeset/openapi_31_support.md @@ -0,0 +1,22 @@ +--- +default: minor +--- + +# OpenAPI 3.1 support + +The generator will now attempt to generate code for OpenAPI documents with versions 3.1.x (previously, it would exit immediately on seeing a version other than 3.0.x). The following specific OpenAPI 3.1 features are now supported: + +- `null` as a type +- Arrays of types (e.g., `type: [string, null]`) +- `const` (defines `Literal` types) + +The generator does not currently validate that the OpenAPI document is valid for a specific version of OpenAPI, so it may be possible to generate code for documents that include both removed 3.0 syntax (e.g., `nullable`) and new 3.1 syntax (e.g., `null` as a type). + +Thanks to everyone who helped make this possible with discussions and testing, including: + +- @frco9 +- @vogre +- @naddeoa +- @staticdev +- @philsturgeon +- @johnthagen diff --git a/.changeset/removed_query_parameter_nullablerequired_special_case.md b/.changeset/removed_query_parameter_nullablerequired_special_case.md new file mode 100644 index 000000000..77aad0a94 --- /dev/null +++ b/.changeset/removed_query_parameter_nullablerequired_special_case.md @@ -0,0 +1,7 @@ +--- +default: major +--- + +# Removed query parameter nullable/required special case + +In previous versions, setting _either_ `nullable: true` or `required: false` on a query parameter would act like both were set, resulting in a type signature like `Union[None, Unset, YourType]`. This special case has been removed, query parameters will now act like all other types of parameters. diff --git a/.gitignore b/.gitignore index 5097b9891..eb6f53cd4 100644 --- a/.gitignore +++ b/.gitignore @@ -27,4 +27,5 @@ htmlcov/ # Generated end to end test data my-test-api-client/ -custom-e2e/ \ No newline at end of file +custom-e2e/ +3-1-features-client \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f00a386ac..7e4cdf17f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,8 +12,8 @@ A bug is one of: 2. The generated code is invalid or incorrect 3. An error message is unclear or incorrect 4. Something which used to work no longer works, except: - 1. Intentional breaking changes, which are documented in the [changelog](https://github.com/openapi-generators/openapi-python-client/blob/main/CHANGELOG.md) - 2. Breaking changes to unstable features, like custom templates + 1. Intentional breaking changes, which are documented in the [changelog](https://github.com/openapi-generators/openapi-python-client/blob/main/CHANGELOG.md) + 2. Breaking changes to unstable features, like custom templates If your issue does not fall under one of the above, it is not a bug; check out "[Requesting a feature](#requesting-a-feature). @@ -27,14 +27,14 @@ A feature is usually: 1. An improvement to the way the generated code works 2. A feature of the generator itself which makes its use easier (e.g., a new config option) -3. **Support for part of the OpenAPI spec**; this generate _does not yet_ support every OpenAPI feature, these missing features **are not bugs**. +3. **Support for part of the OpenAPI spec**; this generator _does not yet_ support every OpenAPI feature, these missing features **are not bugs**. To request a feature: 1. Search through [discussions](https://github.com/openapi-generators/openapi-python-client/discussions/categories/feature-request) to see if the feature you want has already been requested. If it has: - 1. Upvote it with the little arrow on the original post. This enables code contributors to prioritize the most-demanded features. - 2. Optionally leave a comment describing why _you_ want the feature, if no existing thread already covers your use-case -3. If a relevant discussion does not already exist, create a new one. If you are not requesting support for part of the OpenAPI spec, **you must** describe _why_ you want the feature. What real-world use-case does it improve? For example, "raise exceptions for invalid responses" might have a description of "it's not worth the effort to check every error case by hand for the one-off scripts I'm writing". + 1. Upvote it with the little arrow on the original post. This enables code contributors to prioritize the most-demanded features. + 2. Optionally leave a comment describing why _you_ want the feature, if no existing thread already covers your use-case +2. If a relevant discussion does not already exist, create a new one. If you are not requesting support for part of the OpenAPI spec, **you must** describe _why_ you want the feature. What real-world use-case does it improve? For example, "raise exceptions for invalid responses" might have a description of "it's not worth the effort to check every error case by hand for the one-off scripts I'm writing". ## Contributing Code @@ -45,36 +45,41 @@ To request a feature: 3. Use `poetry install` in the project directory to create a virtual environment with the relevant dependencies. 4. Enter a `poetry shell` to make running commands easier. -### Writing Code +### Writing tests -1. Write some code and make sure it's covered by unit tests. All unit tests are in the `tests` directory and the file structure should mirror the structure of the source code in the `openapi_python_client` directory. +All changes must be tested, I recommend writing the test first, then writing the code to make it pass. 100% code coverage is enforced in CI, a check will fail in GitHub if your code does not have 100% coverage. An HTML report will be added to the test artifacts in this case to help you locate missed lines. -#### Run Checks and Tests +If you think that some of the added code is not testable (or testing it would add little value), mention that in your PR and we can discuss it. -2. When in a Poetry shell (`poetry shell`) run `task check` in order to run most of the same checks CI runs. This will auto-reformat the code, check type annotations, run unit tests, check code coverage, and lint the code. +1. If you're adding support for a new OpenAPI feature or covering a new edge case, add an [end-to-end test](#end-to-end-tests) +2. If you're modifying the way an existing feature works, make sure an existing test generates the _old_ code in `end_to_end_tests/golden-record`. You'll use this to check for the new code once your changes are complete. +3. If you're improving an error or adding a new error, add a [unit test](#unit-tests) -#### Rework end-to-end tests +#### End-to-end tests -3. If you're writing a new feature, try to add it to the end-to-end test. - 1. If adding support for a new OpenAPI feature, add it somewhere in `end_to_end_tests/openapi.json` - 2. Regenerate the "golden records" with `task regen`. This client is generated from the OpenAPI document used for end-to-end testing. - 3. Check the changes to `end_to_end_tests/golden-record` to confirm only what you intended to change did change and that the changes look correct. -4. **If you added a test above OR modified the templates**: Run the end-to-end tests with `task e2e`. This will generate clients against `end_to_end_tests/openapi.json` and compare them with the golden record. The tests will fail if **anything is different**. The end-to-end tests are not included in `task check` as they take longer to run and don't provide very useful feedback in the event of failure. If an e2e test does fail, the easiest way to check what's wrong is to run `task regen` and check the diffs. You can also use `task re` which will run `regen` and `e2e` in that order. +This project aims to have all "happy paths" (types of code which _can_ be generated) covered by end to end tests (snapshot tests). In order to check code changes against the previous set of snapshots (called a "golden record" here), you can run `poetry run task e2e`. To regenerate the snapshots, run `poetry run task regen`. +There are 4 types of snapshots generated right now, you may have to update only some or all of these depending on the changes you're making. Within the `end_to_end_tets` directory: -### Creating a Pull Request +1. `baseline_openapi_3.0.json` creates `golden-record` for testing OpenAPI 3.0 features +2. `baseline_openapi_3.1.yaml` is checked against `golden-record` for testing OpenAPI 3.1 features (and ensuring consistency with 3.0) +3. `test_custom_templates` are used with `baseline_openapi_3.0.json` to generate `custom-templates-golden-record` for testing custom templates +4. `3.1_specific.openapi.yaml` is used to generate `test-3-1-golden-record` and test 3.1-specific features (things which do not have a 3.0 equivalent) + +#### Unit tests -Once you've written the code and run the checks, the next step is to create a pull request against the `main` branch of this repository. This repository uses [conventional commits] squashed on each PR, then uses [Knope] to auto-generate CHANGELOG.md entries for release. So the title of your PR should be in the format of a conventional commit written in plain english as it will end up in the CHANGELOG. Some example PR titles: +> **NOTE**: Several older-style unit tests using mocks exist in this project. These should be phased out rather than updated, as the tests are brittle and difficult to maintain. Only error cases should be tests with unit tests going forward. -- feat: Support for `allOf` in OpenAPI documents (closes #123). -- refactor!: Removed support for Python 3.5 -- fix: Data can now be passed to multipart bodies along with files. +In some cases, we need to test things which cannot be generated—like validating that errors are caught and handled correctly. These should be tested via unit tests in the `tests` directory, using the `pytest` framework. + +### Creating a Pull Request -Once your PR is created, a series of automated checks should run. If any of them fail, try your best to fix them. +Once you've written the tests and code and run the checks, the next step is to create a pull request against the `main` branch of this repository. This repository uses [Knope] to auto-generate release notes and version numbers. This can either be done by setting the title of the PR to a [conventional commit] (for simple changes) or by adding [changesets]. If the changes are not documented yet, a check will fail on GitHub. The details of this check will have suggestions for documenting the change (including an example change file for changesets). ### Wait for Review As soon as possible, your PR will be reviewed. If there are any changes requested there will likely be a bit of back and forth. Once this process is done, your changes will be merged into main and included in the next release. If you need your changes available on PyPI by a certain time, please mention it in the PR, and we'll do our best to accommodate. -[Conventional Commits]: https://www.conventionalcommits.org/en/v1.0.0/ -[Knope]: https://knope-dev.github.io/knope/ +[Knope]: https://knope.tech +[changesets]: https://knope.tech/reference/concepts/changeset/ +[Conventional Commits]: https://knope.tech/reference/concepts/conventional-commits/ diff --git a/README.md b/README.md index 9a68aee4d..fd3dda92a 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ # openapi-python-client -Generate modern Python clients from OpenAPI 3.0 documents. +Generate modern Python clients from OpenAPI 3.0 and 3.1 documents. _This generator does not support OpenAPI 2.x FKA Swagger. If you need to use an older document, try upgrading it to version 3 first with one of many available converters._ @@ -69,25 +69,16 @@ _Be forewarned, this is a beta-level feature in the sense that the API exposed i ## What You Get 1. A `pyproject.toml` file with some basic metadata intended to be used with [Poetry]. -1. A `README.md` you'll most definitely need to update with your project's details -1. A Python module named just like the auto-generated project name (e.g. "my_api_client") which contains: +2. A `README.md` you'll most definitely need to update with your project's details +3. A Python module named just like the auto-generated project name (e.g. "my_api_client") which contains: 1. A `client` module which will have both a `Client` class and an `AuthenticatedClient` class. You'll need these for calling the functions in the `api` module. - 1. An `api` module which will contain one module for each tag in your OpenAPI spec, as well as a `default` module + 2. An `api` module which will contain one module for each tag in your OpenAPI spec, as well as a `default` module for endpoints without a tag. Each of these modules in turn contains one function for calling each endpoint. - 1. A `models` module which has all the classes defined by the various schemas in your OpenAPI spec + 3. A `models` module which has all the classes defined by the various schemas in your OpenAPI spec -For a full example you can look at the `end_to_end_tests` directory which has an `openapi.json` file. -"golden-record" in that same directory is the generated client from that OpenAPI document. - -## OpenAPI features supported - -1. All HTTP Methods -1. JSON and form bodies, path and query parameters -1. File uploads with multipart/form-data bodies -1. float, string, int, date, datetime, string enums, and custom schemas or lists containing any of those -1. html/text or application/json responses containing any of the previous types -1. Bearer token security +For a full example you can look at the `end_to_end_tests` directory which has `baseline_openapi_3.0.json` and `baseline_openapi_3.1.yaml` files. +The "golden-record" in that same directory is the generated client from either of those OpenAPI documents. ## Configuration @@ -98,7 +89,7 @@ The following parameters are supported: Used to change the name of generated model classes. This param should be a mapping of existing class name (usually a key in the "schemas" section of your OpenAPI document) to class_name and module_name. As an example, if the -name of the a model in OpenAPI (and therefore the generated class name) was something like "\_PrivateInternalLongName" +name of a model in OpenAPI (and therefore the generated class name) was something like "_PrivateInternalLongName" and you want the generated client's model to be called "ShortName" in a module called "short_name" you could do this: Example: @@ -110,7 +101,7 @@ class_overrides: module_name: short_name ``` -The easiest way to find what needs to be overridden is probably to generate your client and go look at everything in the models folder. +The easiest way to find what needs to be overridden is probably to generate your client and go look at everything in the `models` folder. ### project_name_override and package_name_override diff --git a/end_to_end_tests/3.1_specific.openapi.yaml b/end_to_end_tests/3.1_specific.openapi.yaml new file mode 100644 index 000000000..3540d04ac --- /dev/null +++ b/end_to_end_tests/3.1_specific.openapi.yaml @@ -0,0 +1,49 @@ +openapi: "3.1.0" +info: + title: "Test 3.1 Features" + description: "Test new OpenAPI 3.1 features" + version: "0.1.0" +paths: + "/const/{path}": + post: + tags: [ "const" ] + parameters: + - in: "path" + required: true + schema: + const: "this goes in the path" + name: "path" + - in: "query" + required: true + schema: + const: "this always goes in the query" + name: "required query" + - in: "query" + schema: + const: "this sometimes goes in the query" + name: "optional query" + requestBody: + required: true + content: + "application/json": + schema: + type: object + properties: + required: + const: "this always goes in the body" + optional: + const: "this sometimes goes in the body" + nullable: + oneOf: + - type: "null" + - const: "this or null goes in the body" + required: + - required + - nullable + responses: + "200": + description: "Successful Response" + content: + "application/json": + schema: + const: "Why have a fixed response? I dunno" diff --git a/end_to_end_tests/openapi.json b/end_to_end_tests/baseline_openapi_3.0.json similarity index 99% rename from end_to_end_tests/openapi.json rename to end_to_end_tests/baseline_openapi_3.0.json index fb98839b0..14493030f 100644 --- a/end_to_end_tests/openapi.json +++ b/end_to_end_tests/baseline_openapi_3.0.json @@ -1,5 +1,5 @@ { - "openapi": "3.0.2", + "openapi": "3.0.3", "info": { "title": "My Test API", "description": "An API for testing openapi-python-client", @@ -449,10 +449,10 @@ } } }, - "/tests/defaults": { + "/defaults": { "post": { "tags": [ - "tests" + "defaults" ], "summary": "Defaults", "operationId": "defaults_tests_defaults_post", @@ -467,6 +467,16 @@ "name": "string_prop", "in": "query" }, + { + "required": true, + "schema": { + "title": "String with num default", + "type": "string", + "default": 1 + }, + "name": "string with num", + "in": "query" + }, { "required": true, "schema": { @@ -2425,7 +2435,8 @@ "in": "header", "required": false, "schema": { - "type": "string" + "type": "string", + "nullable": true } }, "cookie-param": { diff --git a/end_to_end_tests/baseline_openapi_3.1.yaml b/end_to_end_tests/baseline_openapi_3.1.yaml new file mode 100644 index 000000000..2d1c1f9ac --- /dev/null +++ b/end_to_end_tests/baseline_openapi_3.1.yaml @@ -0,0 +1,2514 @@ +openapi: "3.1.0" +info: + title: "My Test API" + description: "An API for testing openapi-python-client" + version: "0.1.0" +"paths": { + "/tests/": { + "get": { + "tags": [ + "tests" + ], + "summary": "Get List", + "description": "Get a list of things ", + "operationId": "getUserList", + "parameters": [ + { + "required": true, + "schema": { + "title": "An Enum Value", + "type": "array", + "items": { + "$ref": "#/components/schemas/AnEnum" + } + }, + "name": "an_enum_value", + "in": "query" + }, + { + "required": true, + "schema": { + "title": "An Enum Value With Null And String Values", + "type": "array", + "items": { + "$ref": "#/components/schemas/AnEnumWithNull" + } + }, + "name": "an_enum_value_with_null", + "in": "query" + }, + { + "required": true, + "schema": { + "title": "An Enum Value With Only Null Values", + "type": "array", + "items": { + "$ref": "#/components/schemas/AnEnumWithOnlyNull" + } + }, + "name": "an_enum_value_with_only_null", + "in": "query" + }, + { + "required": true, + "schema": { + "title": "Some Date", + "anyOf": [ + { + "type": "string", + "format": "date" + }, + { + "type": "string", + "format": "date-time" + } + ] + }, + "name": "some_date", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response Get List Tests Get", + "type": "array", + "items": { + "$ref": "#/components/schemas/AModel" + } + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + }, + "423": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/tests/basic_lists/strings": { + "get": { + "tags": [ + "tests" + ], + "summary": "Get Basic List Of Strings", + "description": "Get a list of strings ", + "operationId": "getBasicListOfStrings", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response Get Basic List Of Strings Tests Basic Lists Strings Get", + "type": "array", + "items": { + "type": "string" + } + } + } + } + } + } + } + }, + "/tests/basic_lists/integers": { + "get": { + "tags": [ + "tests" + ], + "summary": "Get Basic List Of Integers", + "description": "Get a list of integers ", + "operationId": "getBasicListOfIntegers", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response Get Basic List Of Integers Tests Basic Lists Integers Get", + "type": "array", + "items": { + "type": "integer" + } + } + } + } + } + } + } + }, + "/tests/basic_lists/floats": { + "get": { + "tags": [ + "tests" + ], + "summary": "Get Basic List Of Floats", + "description": "Get a list of floats ", + "operationId": "getBasicListOfFloats", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response Get Basic List Of Floats Tests Basic Lists Floats Get", + "type": "array", + "items": { + "type": "number" + } + } + } + } + } + } + } + }, + "/tests/basic_lists/booleans": { + "get": { + "tags": [ + "tests" + ], + "summary": "Get Basic List Of Booleans", + "description": "Get a list of booleans ", + "operationId": "getBasicListOfBooleans", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "title": "Response Get Basic List Of Booleans Tests Basic Lists Booleans Get", + "type": "array", + "items": { + "type": "boolean" + } + } + } + } + } + } + } + }, + "/tests/post_form_data": { + "post": { + "tags": [ + "tests" + ], + "summary": "Post form data", + "description": "Post form data", + "operationId": "post_form_data", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "$ref": "#/components/schemas/AFormData" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + } + } + } + } + } + }, + "/tests/post_form_data_inline": { + "post": { + "tags": [ + "tests" + ], + "summary": "Post form data (inline schema)", + "description": "Post form data (inline schema)", + "operationId": "post_form_data_inline", + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "an_optional_field": { + "type": "string" + }, + "a_required_field": { + "type": "string" + } + }, + "required": [ + "a_required_field" + ] + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + } + } + } + } + } + }, + "/tests/upload": { + "post": { + "tags": [ + "tests" + ], + "summary": "Upload File", + "description": "Upload a file ", + "operationId": "upload_file_tests_upload_post", + "parameters": [ ], + "requestBody": { + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/Body_upload_file_tests_upload_post" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/tests/upload/multiple": { + "post": { + "tags": [ + "tests" + ], + "summary": "Upload multiple files", + "description": "Upload several files in the same request", + "operationId": "upload_multiple_files_tests_upload_post", + "parameters": [ ], + "requestBody": { + "content": { + "multipart/form-data": { + "schema": { + "type": "array", + "items": { + "type": "string", + "format": "binary" + } + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/tests/json_body": { + "post": { + "tags": [ + "tests" + ], + "summary": "Json Body", + "description": "Try sending a JSON body ", + "operationId": "json_body_tests_json_body_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AModel" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/tests/json_body/string": { + "post": { + "tags": [ + "tests" + ], + "summary": "Json Body Which is String", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "success", + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/defaults": { + "post": { + "tags": [ + "defaults" + ], + "summary": "Defaults", + "operationId": "defaults_tests_defaults_post", + "parameters": [ + { + "required": true, + "schema": { + "title": "String Prop", + "type": "string", + "default": "the default string" + }, + "name": "string_prop", + "in": "query" + }, + { + "required": true, + "schema": { + "title": "String with num default", + "type": "string", + "default": 1 + }, + "name": "string with num", + "in": "query" + }, + { + "required": true, + "schema": { + "title": "Date Prop", + "type": "string", + "format": "date", + "default": "1010-10-10" + }, + "name": "date_prop", + "in": "query" + }, + { + "required": true, + "schema": { + "title": "Float Prop", + "type": "number", + "default": 3.14 + }, + "name": "float_prop", + "in": "query" + }, + { + "required": true, + "schema": { + "title": "Int Prop", + "type": "integer", + "default": 7 + }, + "name": "int_prop", + "in": "query" + }, + { + "required": true, + "schema": { + "title": "Boolean Prop", + "type": "boolean", + "default": false + }, + "name": "boolean_prop", + "in": "query" + }, + { + "required": true, + "schema": { + "title": "List Prop", + "type": "array", + "items": { + "$ref": "#/components/schemas/AnEnum" + }, + "default": [ + "FIRST_VALUE", + "SECOND_VALUE" + ] + }, + "name": "list_prop", + "in": "query" + }, + { + "required": true, + "schema": { + "title": "Union Prop", + "type": [ + "number", + "string" + ], + "default": "not a float" + }, + "name": "union_prop", + "in": "query" + }, + { + "required": false, + "schema": { + "title": "Union Prop With Ref", + "anyOf": [ + { + "type": "number" + }, + { + "$ref": "#/components/schemas/AnEnum" + } + ], + "default": 0.6 + }, + "name": "union_prop_with_ref", + "in": "query" + }, + { + "required": true, + "schema": { + "$ref": "#/components/schemas/AnEnum" + }, + "name": "enum_prop", + "in": "query" + }, + { + "required": true, + "schema": { + "$ref": "#/components/schemas/ModelWithUnionProperty" + }, + "name": "model_prop", + "in": "query" + }, + { + "required": true, + "schema": { + "$ref": "#/components/schemas/ModelWithUnionProperty" + }, + "name": "required_model_prop", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/tests/octet_stream": { + "get": { + "tags": [ + "tests" + ], + "summary": "Octet Stream", + "operationId": "octet_stream_tests_octet_stream_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/octet-stream": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + }, + "post": { + "tags": [ + "tests" + ], + "summary": "Binary (octet stream) request body", + "operationId": "octet_stream_tests_octet_stream_post", + "requestBody": { + "content": { + "application/octet-stream": { + "schema": { + "description": "A file to upload", + "type": "string", + "format": "binary" + } + } + } + }, + "responses": { + "200": { + "description": "success", + "content": { + "application/json": { + "schema": { + "type": "string" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/tests/no_response": { + "get": { + "tags": [ + "tests" + ], + "summary": "No Response", + "operationId": "no_response_tests_no_response_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + } + } + } + } + } + }, + "/tests/unsupported_content": { + "get": { + "tags": [ + "tests" + ], + "summary": "Unsupported Content", + "operationId": "unsupported_content_tests_unsupported_content_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + }, + "not_real/content-type": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + } + }, + "/tests/int_enum": { + "post": { + "tags": [ + "tests" + ], + "summary": "Int Enum", + "operationId": "int_enum_tests_int_enum_post", + "parameters": [ + { + "required": true, + "schema": { + "$ref": "#/components/schemas/AnIntEnum" + }, + "name": "int_enum", + "in": "query" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/tests/inline_objects": { + "post": { + "tags": [ + "tests" + ], + "summary": "Test Inline Objects", + "operationId": "test_inline_objects", + "requestBody": { + "description": "An inline body object", + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "a_property": { + "type": "string" + } + }, + "additionalProperties": false + } + } + } + }, + "responses": { + "200": { + "description": "Inline object response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "a_property": { + "type": "string" + } + }, + "additionalProperties": false + } + } + } + } + } + } + }, + "/responses/unions/simple_before_complex": { + "post": { + "tags": [ + "responses" + ], + "description": "Regression test for #603", + "responses": { + "200": { + "description": "A union with simple types before complex ones.", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "a" + ], + "properties": { + "a": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "object" + } + ] + } + } + } + } + } + } + } + } + }, + "/responses/text": { + "post": { + "tags": [ + "responses" + ], + "summary": "Text Response", + "operationId": "text_response", + "responses": { + "200": { + "description": "Text response", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/auth/token_with_cookie": { + "get": { + "tags": [ + "tests" + ], + "summary": "TOKEN_WITH_COOKIE", + "description": "Test optional cookie parameters", + "operationId": "token_with_cookie_auth_token_with_cookie_get", + "parameters": [ + { + "required": true, + "schema": { + "title": "Token", + "type": "string" + }, + "name": "MyToken", + "in": "cookie" + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + } + } + }, + "401": { + "description": "Unauthorized" + } + } + } + }, + "/common_parameters": { + "parameters": [ + { + "schema": { + "type": "string" + }, + "name": "common", + "in": "query" + } + ], + "get": { + "responses": { + "200": { + "description": "Success" + } + } + }, + "post": { + "responses": { + "200": { + "description": "Success" + } + } + } + }, + "/common_parameters_overriding/{param}": { + "get": { + "description": "Test that if you have an overriding property from `PathItem` in `Operation`, it produces valid code", + "tags": [ + "parameters" + ], + "parameters": [ + { + "name": "param", + "in": "query", + "required": true, + "schema": { + "description": "A parameter with the same name as another.", + "example": "an example string", + "type": "string", + "default": "overridden_in_GET" + } + } + ], + "responses": { + "200": { + "description": "" + } + } + }, + "delete": { + "tags": [ + "parameters" + ], + "responses": { + "200": { + "description": "" + } + } + }, + "parameters": [ + { + "name": "param", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "param", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ] + }, + "/same-name-multiple-locations/{param}": { + "description": "Test that if you have a property of the same name in multiple locations, it produces valid code", + "get": { + "tags": [ + "parameters" + ], + "parameters": [ + { + "name": "param", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "param", + "in": "header", + "schema": { + "type": "string" + } + }, + { + "name": "param", + "in": "cookie", + "schema": { + "type": "string" + } + }, + { + "name": "param", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "" + } + } + } + }, + "/tag_with_number": { + "get": { + "tags": [ + "1" + ], + "responses": { + "200": { + "description": "Success" + } + } + } + }, + "/multiple-path-parameters/{param4}/something/{param2}/{param1}/{param3}": { + "description": "Test that multiple path parameters are ordered by appearance in path", + "get": { + "tags": [ + "parameters" + ], + "operationId": "multiple_path_parameters", + "parameters": [ + { + "name": "param1", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "param2", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Success" + } + } + }, + "parameters": [ + { + "name": "param4", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "param3", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ] + }, + "/location/query/optionality": { + "description": "Test what happens with various combinations of required and nullable in query parameters.", + "get": { + "tags": [ + "location" + ], + "parameters": [ + { + "name": "not_null_required", + "required": true, + "schema": { + "type": "string", + "format": "date-time" + }, + "in": "query" + }, + { + "name": "null_required", + "required": true, + "schema": { + type: [ "string", "null" ], + format: "date-time", + }, + "in": "query" + }, + { + "name": "null_not_required", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string", + "format": "date-time" + }, + { + "type": "null" + } + ] + }, + "in": "query" + }, + { + "name": "not_null_not_required", + "required": false, + "schema": { + "type": "string", + "format": "date-time" + }, + "in": "query" + } + ], + "responses": { + "200": { + "description": "" + } + } + } + }, + "/location/header/types": { + "description": "Test the valid types to send in headers.", + "get": { + "tags": [ + "location" + ], + "parameters": [ + { + "required": false, + "schema": { + "type": "boolean" + }, + "name": "Boolean-Header", + "in": "header" + }, + { + "required": false, + "schema": { + "type": "string" + }, + "name": "String-Header", + "in": "header" + }, + { + "required": false, + "schema": { + "type": "number" + }, + "name": "Number-Header", + "in": "header" + }, + { + "required": false, + "schema": { + "type": "integer" + }, + "name": "Integer-Header", + "in": "header" + }, + { + "in": "header", + "name": "Int-Enum-Header", + "required": false, + "schema": { + "type": "integer", + "enum": [ + 1, + 2, + 3 + ] + } + }, + { + "in": "header", + "name": "String-Enum-Header", + "required": false, + "schema": { + "type": "string", + "enum": [ + "one", + "two", + "three" + ] + } + } + ], + "responses": { + "200": { + "description": "" + } + } + } + }, + "/naming/keywords": { + "description": "Ensure that Python keywords are renamed properly.", + "get": { + "tags": [ + "true" + ], + "operationId": "false", + "parameters": [ + { + "name": "import", + "required": true, + "schema": { + "type": "string" + }, + "in": "query" + } + ], + "responses": { + "200": { + "description": "" + } + } + } + }, + "/naming/reserved-parameters": { + "description": "Ensure that parameters can't be named things that the code generator needs as variables", + "get": { + "operationId": "reserved-parameters", + "parameters": [ + { + "name": "client", + "in": "query", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "url", + "in": "query", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "" + } + } + } + }, + "/naming/property-conflict-with-import": { + "description": "Ensure that property names don't conflict with imports", + "post": { + "tags": [ + "naming" + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "Field": { + "type": "string", + "description": "A python_name of field should not interfere with attrs field" + }, + "Define": { + "type": "string", + "description": "A python_name of define should not interfere with attrs define" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Response that contains conflicting properties", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "Field": { + "type": "string", + "description": "A python_name of field should not interfere with attrs field" + }, + "Define": { + "type": "string", + "description": "A python_name of define should not interfere with attrs define" + } + } + } + } + } + } + } + } + }, + "/parameter-references/{path_param}": { + "get": { + "tags": [ + "parameter-references" + ], + "summary": "Test different types of parameter references", + "parameters": [ + { + "$ref": "#/components/parameters/string-param" + }, + { + "$ref": "#/components/parameters/integer-param" + }, + { + "$ref": "#/components/parameters/header-param" + }, + { + "$ref": "#/components/parameters/cookie-param" + }, + { + "$ref": "#/components/parameters/path-param" + } + ], + "responses": { + "200": { + "description": "Successful response" + } + } + } + }, + "/tests/callback": { + "post": { + "tags": [ + "tests" + ], + "summary": "Path with callback", + "description": "Try sending a request related to a callback", + "operationId": "callback_test", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AModel" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/yang-data+json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + }, + "callbacks": { + "event": { + "callback": { + "post": { + "responses": { + "200": { + "description": "Success" + }, + "503": { + "description": "Unavailable" + } + } + } + } + } + } + } + }, + "/tests/description-with-backslash": { + "get": { + "tags": [ + "tests" + ], + "summary": "Test description with \\", + "description": "Test description with \\", + "operationId": "description_with_backslash", + "responses": { + "200": { + "description": "Successful response" + } + } + } + } +} +"components": { + "schemas": { + "AFormData": { + "type": "object", + "properties": { + "an_optional_field": { + "type": "string" + }, + "an_required_field": { + "type": "string" + } + }, + "required": [ + "an_required_field" + ] + }, + "AModel": { + "title": "AModel", + "required": [ + "an_enum_value", + "an_allof_enum_with_overridden_default", + "aCamelDateTime", + "a_date", + "a_nullable_date", + "required_nullable", + "required_not_nullable", + "model", + "nullable_model", + "one_of_models", + "nullable_one_of_models" + ], + "type": "object", + "properties": { + "any_value": { }, + "an_enum_value": { + "$ref": "#/components/schemas/AnEnum" + }, + "an_allof_enum_with_overridden_default": { + "allOf": [ + { + "$ref": "#/components/schemas/AnAllOfEnum" + } + ], + "default": "overridden_default" + }, + "an_optional_allof_enum": { + "allOf": [ + { + "$ref": "#/components/schemas/AnAllOfEnum" + } + ] + }, + "nested_list_of_enums": { + "title": "Nested List Of Enums", + "type": "array", + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/DifferentEnum" + } + }, + "default": [ ] + }, + "aCamelDateTime": { + "title": "Acameldatetime", + "anyOf": [ + { + "type": "string", + "format": "date-time" + }, + { + "type": "string", + "format": "date" + } + ] + }, + "a_date": { + "title": "A Date", + "type": "string", + "format": "date" + }, + "a_nullable_date": { + "title": "A Nullable Date", + "anyOf": [ + { + "type": "string", + "format": "date" + }, + { + "type": "null" + } + ] + }, + "a_not_required_date": { + "title": "A Nullable Date", + "type": "string", + "format": "date" + }, + "1_leading_digit": { + "title": "Leading Digit", + "type": "string" + }, + "_leading_underscore": { + "title": "Leading Underscore", + "type": "string" + }, + "required_nullable": { + "title": "Required AND Nullable", + "anyOf": [ + { + "type": "null" + }, + { + "type": "string" + } + ] + }, + "required_not_nullable": { + "title": "Required NOT Nullable", + "type": "string" + }, + "not_required_nullable": { + "title": "NOT Required AND nullable", + "anyOf": [ + { + "type": "null" + }, + { + "type": "string" + } + ] + }, + "not_required_not_nullable": { + "title": "NOT Required AND NOT Nullable", + "type": "string" + }, + "one_of_models": { + "oneOf": [ + { + "$ref": "#/components/schemas/FreeFormModel" + }, + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + }, + { } + ] + }, + "nullable_one_of_models": { + "oneOf": [ + { + "$ref": "#/components/schemas/FreeFormModel" + }, + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + }, + { + "type": "null" + } + ] + }, + "not_required_one_of_models": { + "oneOf": [ + { + "$ref": "#/components/schemas/FreeFormModel" + }, + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + } + ] + }, + "not_required_nullable_one_of_models": { + "oneOf": [ + { + "$ref": "#/components/schemas/FreeFormModel" + }, + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + }, + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "model": { + "allOf": [ + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + } + ] + }, + "nullable_model": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + } + ] + }, + "not_required_model": { + "allOf": [ + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + } + ] + }, + "not_required_nullable_model": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + } + ] + } + }, + "description": "A Model for testing all the ways custom objects can be used ", + "additionalProperties": false + }, + "AnEnum": { + "title": "AnEnum", + "enum": [ + "FIRST_VALUE", + "SECOND_VALUE" + ], + "description": "For testing Enums in all the ways they can be used " + }, + "AnEnumWithNull": { + "title": "AnEnumWithNull", + "enum": [ + "FIRST_VALUE", + "SECOND_VALUE", + null + ], + "description": "For testing Enums with mixed string / null values " + }, + "AnEnumWithOnlyNull": { + "title": "AnEnumWithOnlyNull", + "enum": [ + null + ], + "description": "For testing Enums with only null values " + }, + "AnAllOfEnum": { + "title": "AnAllOfEnum", + "enum": [ + "foo", + "bar", + "a_default", + "overridden_default" + ], + "default": "a_default" + }, + "AnIntEnum": { + "title": "AnIntEnum", + "enum": [ + -1, + 1, + 2 + ], + "type": "integer", + "description": "An enumeration." + }, + "Body_upload_file_tests_upload_post": { + "title": "Body_upload_file_tests_upload_post", + "required": [ + "some_file", + "some_object", + "some_nullable_object" + ], + "type": "object", + "properties": { + "some_file": { + "title": "Some File", + "type": "string", + "format": "binary" + }, + "some_optional_file": { + "title": "Some Optional File", + "type": "string", + "format": "binary" + }, + "some_string": { + "title": "Some String", + "type": "string", + "default": "some_default_string" + }, + "a_datetime": { + "title": "A Datetime", + "type": "string", + "format": "date-time" + }, + "a_date": { + "title": "A Date", + "type": "string", + "format": "date" + }, + "some_number": { + "title": "Some Number", + "type": "number" + }, + "some_array": { + "title": "Some Array", + "type": "array", + "items": { + "type": "number" + } + }, + "some_object": { + "title": "Some Object", + "type": "object", + "required": [ + "num", + "text" + ], + "properties": { + "num": { + "type": "number" + }, + "text": { + "type": "string" + } + } + }, + "some_optional_object": { + "title": "Some Optional Object", + "type": "object", + "required": [ + "foo" + ], + "properties": { + "foo": { + "type": "string" + } + } + }, + "some_nullable_object": { + "title": "Some Nullable Object", + "type": [ "object", "null" ], + "properties": { + "bar": { + "type": "string" + } + } + }, + "some_enum": { + "$ref": "#/components/schemas/DifferentEnum" + } + }, + "additionalProperties": { + "type": "object", + "properties": { + "foo": { + "type": "string" + } + } + } + }, + "DifferentEnum": { + "title": "DifferentEnum", + "enum": [ + "DIFFERENT", + "OTHER" + ], + "description": "An enumeration." + }, + "HTTPValidationError": { + "title": "HTTPValidationError", + "type": "object", + "properties": { + "detail": { + "title": "Detail", + "type": "array", + "items": { + "$ref": "#/components/schemas/ValidationError" + } + } + }, + "additionalProperties": false + }, + "ValidationError": { + "title": "ValidationError", + "required": [ + "loc", + "msg", + "type" + ], + "type": "object", + "properties": { + "loc": { + "title": "Location", + "type": "array", + "items": { + "type": "string" + } + }, + "msg": { + "title": "Message", + "type": "string" + }, + "type": { + "title": "Error Type", + "type": "string" + } + }, + "additionalProperties": false + }, + "ModelWithUnionProperty": { + "title": "ModelWithUnionProperty", + "type": "object", + "properties": { + "a_property": { + "oneOf": [ + { + "$ref": "#/components/schemas/AnEnum" + }, + { + "$ref": "#/components/schemas/AnIntEnum" + } + ] + } + }, + "additionalProperties": false + }, + "ModelWithUnionPropertyInlined": { + "title": "ModelWithUnionPropertyInlined", + "type": "object", + "properties": { + "fruit": { + "oneOf": [ + { + "type": "object", + "properties": { + "apples": { + "type": "string" + } + } + }, + { + "type": "object", + "properties": { + "bananas": { + "type": "string" + } + } + } + ] + } + }, + "additionalProperties": false + }, + "FreeFormModel": { + "title": "FreeFormModel", + "type": "object" + }, + "ModelWithAdditionalPropertiesInlined": { + "type": "object", + "properties": { + "a_number": { + "type": "number" + } + }, + "additionalProperties": { + "type": "object", + "properties": { + "extra_props_prop": { + "type": "string" + } + }, + "additionalProperties": { } + } + }, + "ModelWithPrimitiveAdditionalProperties": { + "title": "ModelWithPrimitiveAdditionalProperties", + "type": "object", + "properties": { + "a_date_holder": { + "type": "object", + "additionalProperties": { + "type": "string", + "format": "date-time" + } + } + }, + "additionalProperties": { + "type": "string" + } + }, + "ModelWithAdditionalPropertiesRefed": { + "title": "ModelWithAdditionalPropertiesRefed", + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AnEnum" + } + }, + "ModelWithAnyJsonProperties": { + "title": "ModelWithAnyJsonProperties", + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string" + }, + { + "type": "number" + }, + { + "type": "integer" + }, + { + "type": "boolean" + } + ] + } + }, + "ModelFromAllOf": { + "title": "ModelFromAllOf", + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/AllOfSubModel" + }, + { + "$ref": "#/components/schemas/AnotherAllOfSubModel" + } + ] + }, + "AllOfSubModel": { + "title": "AllOfSubModel", + "type": "object", + "properties": { + "a_sub_property": { + "type": "string" + }, + "type": { + "type": "string" + }, + "type_enum": { + "type": "integer", + "enum": [ + 0, + 1 + ] + } + } + }, + "AnotherAllOfSubModel": { + "title": "AnotherAllOfSubModel", + "type": "object", + "properties": { + "another_sub_property": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "submodel" + ] + }, + "type_enum": { + "type": "integer", + "enum": [ + 0 + ] + } + } + }, + "AllOfHasPropertiesButNoType": { + "title": "AllOfHasPropertiesButNoType", + "properties": { + "a_sub_property": { + "type": "string" + }, + "type": { + "type": "string" + }, + "type_enum": { + "type": "integer", + "enum": [ + 0, + 1 + ] + } + } + }, + "model_reference_doesnt_match": { + "title": "ModelName", + "type": "object" + }, + "ModelWithPropertyRef": { + "type": "object", + "properties": { + "inner": { + "$ref": "#/components/schemas/model_reference_doesnt_match" + } + } + }, + "AModelWithPropertiesReferenceThatAreNotObject": { + "type": "object", + "required": [ + "enum_properties_ref", + "str_properties_ref", + "date_properties_ref", + "datetime_properties_ref", + "int32_properties_ref", + "int64_properties_ref", + "float_properties_ref", + "double_properties_ref", + "file_properties_ref", + "bytestream_properties_ref", + "enum_properties", + "str_properties", + "date_properties", + "datetime_properties", + "int32_properties", + "int64_properties", + "float_properties", + "double_properties", + "file_properties", + "bytestream_properties", + "enum_property_ref", + "str_property_ref", + "date_property_ref", + "datetime_property_ref", + "int32_property_ref", + "int64_property_ref", + "float_property_ref", + "double_property_ref", + "file_property_ref", + "bytestream_property_ref" + ], + "properties": { + "enum_properties_ref": { + "$ref": "#/components/schemas/AnOtherArrayOfEnum" + }, + "str_properties_ref": { + "$ref": "#/components/schemas/AnOtherArrayOfString" + }, + "date_properties_ref": { + "$ref": "#/components/schemas/AnOtherArrayOfDate" + }, + "datetime_properties_ref": { + "$ref": "#/components/schemas/AnOtherArrayOfDateTime" + }, + "int32_properties_ref": { + "$ref": "#/components/schemas/AnOtherArrayOfInt32" + }, + "int64_properties_ref": { + "$ref": "#/components/schemas/AnOtherArrayOfInt64" + }, + "float_properties_ref": { + "$ref": "#/components/schemas/AnOtherArrayOfFloat" + }, + "double_properties_ref": { + "$ref": "#/components/schemas/AnOtherArrayOfDouble" + }, + "file_properties_ref": { + "$ref": "#/components/schemas/AnOtherArrayOfFile" + }, + "bytestream_properties_ref": { + "$ref": "#/components/schemas/AnOtherArrayOfByteStream" + }, + "enum_properties": { + "$ref": "#/components/schemas/AnArrayOfEnum" + }, + "str_properties": { + "$ref": "#/components/schemas/AnArrayOfString" + }, + "date_properties": { + "$ref": "#/components/schemas/AnArrayOfDate" + }, + "datetime_properties": { + "$ref": "#/components/schemas/AnArrayOfDateTime" + }, + "int32_properties": { + "$ref": "#/components/schemas/AnArrayOfInt32" + }, + "int64_properties": { + "$ref": "#/components/schemas/AnArrayOfInt64" + }, + "float_properties": { + "$ref": "#/components/schemas/AnArrayOfFloat" + }, + "double_properties": { + "$ref": "#/components/schemas/AnArrayOfDouble" + }, + "file_properties": { + "$ref": "#/components/schemas/AnArrayOfFile" + }, + "bytestream_properties": { + "$ref": "#/components/schemas/AnArrayOfByteStream" + }, + "enum_property_ref": { + "$ref": "#/components/schemas/AnEnum" + }, + "str_property_ref": { + "$ref": "#/components/schemas/AString" + }, + "date_property_ref": { + "$ref": "#/components/schemas/ADate" + }, + "datetime_property_ref": { + "$ref": "#/components/schemas/ADateTime" + }, + "int32_property_ref": { + "$ref": "#/components/schemas/AnInt32" + }, + "int64_property_ref": { + "$ref": "#/components/schemas/AnInt64" + }, + "float_property_ref": { + "$ref": "#/components/schemas/AFloat" + }, + "double_property_ref": { + "$ref": "#/components/schemas/ADouble" + }, + "file_property_ref": { + "$ref": "#/components/schemas/AFile" + }, + "bytestream_property_ref": { + "$ref": "#/components/schemas/AByteStream" + } + } + }, + "ModelWithDateTimeProperty": { + "type": "object", + "properties": { + "datetime": { + "type": "string", + "format": "date-time" + } + } + }, + "AnArrayOfEnum": { + "type": "array", + "items": { + "title": "AnEnum", + "enum": [ + "FIRST_VALUE", + "SECOND_VALUE" + ], + "description": "For testing Enums in all the ways they can be used " + } + }, + "AnOtherArrayOfEnum": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AnEnum" + } + }, + "AnArrayOfString": { + "type": "array", + "items": { + "type": "string" + } + }, + "AnOtherArrayOfString": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AString" + } + }, + "AString": { + "type": "string", + "pattern": "^helloworld.*" + }, + "AnArrayOfDate": { + "type": "array", + "items": { + "type": "string", + "format": "date" + } + }, + "AnOtherArrayOfDate": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ADate" + } + }, + "ADate": { + "type": "string", + "format": "date" + }, + "AnArrayOfDateTime": { + "type": "array", + "items": { + "type": "string", + "format": "date-time" + } + }, + "AnOtherArrayOfDateTime": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ADateTime" + } + }, + "ADateTime": { + "type": "string", + "format": "date-time" + }, + "AnArrayOfInt32": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + }, + "AnOtherArrayOfInt32": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AnInt32" + } + }, + "AnInt32": { + "type": "integer", + "format": "int32" + }, + "AnArrayOfInt64": { + "type": "array", + "items": { + "type": "integer", + "format": "int64" + } + }, + "AnOtherArrayOfInt64": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AnInt64" + } + }, + "AnInt64": { + "type": "integer", + "format": "int64" + }, + "AnArrayOfFloat": { + "type": "array", + "items": { + "type": "number", + "format": "float" + } + }, + "AnOtherArrayOfFloat": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AFloat" + } + }, + "AFloat": { + "type": "number", + "format": "float" + }, + "AnArrayOfDouble": { + "type": "array", + "items": { + "type": "number", + "format": "float" + } + }, + "AnOtherArrayOfDouble": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ADouble" + } + }, + "ADouble": { + "type": "number", + "format": "double" + }, + "AnArrayOfFile": { + "type": "array", + "items": { + "type": "string", + "format": "binary" + } + }, + "AnOtherArrayOfFile": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AFile" + } + }, + "AFile": { + "type": "string", + "format": "binary" + }, + "AnArrayOfByteStream": { + "type": "array", + "items": { + "type": "string", + "format": "byte" + } + }, + "AnOtherArrayOfByteStream": { + "type": "array", + "items": { + "$ref": "#/components/schemas/AByteStream" + } + }, + "AByteStream": { + "type": "string", + "format": "byte" + }, + "import": { + "type": "object" + }, + "None": { + "type": "object" + }, + "model.reference.with.Periods": { + "type": "object", + "description": "A Model with periods in its reference" + }, + "ModelWithRecursiveRef": { + "type": "object", + "properties": { + "recursive": { + "$ref": "#/components/schemas/ModelWithRecursiveRef" + } + } + }, + "ModelWithCircularRefA": { + "type": "object", + "properties": { + "circular": { + "$ref": "#/components/schemas/ModelWithCircularRefB" + } + } + }, + "ModelWithCircularRefB": { + "type": "object", + "properties": { + "circular": { + "$ref": "#/components/schemas/ModelWithCircularRefA" + } + } + }, + "ModelWithRecursiveRefInAdditionalProperties": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ModelWithRecursiveRefInAdditionalProperties" + } + }, + "ModelWithCircularRefInAdditionalPropertiesA": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ModelWithCircularRefInAdditionalPropertiesB" + } + }, + "ModelWithCircularRefInAdditionalPropertiesB": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ModelWithCircularRefInAdditionalPropertiesA" + } + }, + "AnArrayWithARecursiveRefInItemsObject": { + "type": "array", + "items": { + "type": "object", + "properties": { + "recursive": { + "$ref": "#/components/schemas/AnArrayWithARecursiveRefInItemsObject" + } + } + } + }, + "AnArrayWithACircularRefInItemsObjectA": { + "type": "array", + "items": { + "type": "object", + "properties": { + "circular": { + "$ref": "#/components/schemas/AnArrayWithACircularRefInItemsObjectB" + } + } + } + }, + "AnArrayWithACircularRefInItemsObjectB": { + "type": "array", + "items": { + "type": "object", + "properties": { + "circular": { + "$ref": "#/components/schemas/AnArrayWithACircularRefInItemsObjectA" + } + } + } + }, + "AnArrayWithARecursiveRefInItemsObjectAdditionalProperties": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AnArrayWithARecursiveRefInItemsObjectAdditionalProperties" + } + } + }, + "AnArrayWithACircularRefInItemsObjectAdditionalPropertiesA": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AnArrayWithACircularRefInItemsObjectAdditionalPropertiesB" + } + } + }, + "AnArrayWithACircularRefInItemsObjectAdditionalPropertiesB": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/AnArrayWithACircularRefInItemsObjectAdditionalPropertiesA" + } + } + }, + "ModelWithBackslashInDescription": { + "type": "object", + "description": "Description with special character: \\" + } + }, + "parameters": { + "integer-param": { + "name": "integer param", + "in": "query", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "integer", + "default": 0 + } + }, + "string-param": { + "name": "string param", + "in": "query", + "required": false, + "style": "form", + "explode": true, + "schema": { + "type": "string" + } + }, + "object-param": { + "name": "object param", + "in": "query", + "required": false, + "schema": { + "type": "object", + "properties": { + "date": { + "type": "string", + "format": "date" + }, + "number": { + "type": "number" + } + } + } + }, + "header-param": { + "name": "header param", + "in": "header", + "required": false, + "schema": { + oneOf: [ + type: "string", + type: "null", + ] + } + }, + "cookie-param": { + "name": "cookie param", + "in": "cookie", + "required": false, + "schema": { + "type": "string" + } + }, + "path-param": { + "name": "path_param", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + } +} + diff --git a/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/__init__.py b/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/__init__.py index 969248a72..80575f2aa 100644 --- a/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/__init__.py +++ b/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/__init__.py @@ -3,6 +3,7 @@ from typing import Type from .default import DefaultEndpoints +from .defaults import DefaultsEndpoints from .location import LocationEndpoints from .naming import NamingEndpoints from .parameter_references import ParameterReferencesEndpoints @@ -18,6 +19,10 @@ class MyTestApiClientApi: def tests(cls) -> Type[TestsEndpoints]: return TestsEndpoints + @classmethod + def defaults(cls) -> Type[DefaultsEndpoints]: + return DefaultsEndpoints + @classmethod def responses(cls) -> Type[ResponsesEndpoints]: return ResponsesEndpoints diff --git a/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/defaults/__init__.py b/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/defaults/__init__.py new file mode 100644 index 000000000..cd3d6e786 --- /dev/null +++ b/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/defaults/__init__.py @@ -0,0 +1,14 @@ +""" Contains methods for accessing the API Endpoints """ + +import types + +from . import defaults_tests_defaults_post + + +class DefaultsEndpoints: + @classmethod + def defaults_tests_defaults_post(cls) -> types.ModuleType: + """ + Defaults + """ + return defaults_tests_defaults_post diff --git a/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/tests/__init__.py b/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/tests/__init__.py index c678e9e96..9b687c858 100644 --- a/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/tests/__init__.py +++ b/end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/tests/__init__.py @@ -4,7 +4,6 @@ from . import ( callback_test, - defaults_tests_defaults_post, description_with_backslash, get_basic_list_of_booleans, get_basic_list_of_floats, @@ -105,13 +104,6 @@ def post_tests_json_body_string(cls) -> types.ModuleType: """ return post_tests_json_body_string - @classmethod - def defaults_tests_defaults_post(cls) -> types.ModuleType: - """ - Defaults - """ - return defaults_tests_defaults_post - @classmethod def octet_stream_tests_octet_stream_get(cls) -> types.ModuleType: """ diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/default/get_common_parameters.py b/end_to_end_tests/golden-record/my_test_api_client/api/default/get_common_parameters.py index 3eb7cae13..1c02c81d2 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/default/get_common_parameters.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/default/get_common_parameters.py @@ -10,9 +10,10 @@ def _get_kwargs( *, - common: Union[Unset, None, str] = UNSET, + common: Union[Unset, str] = UNSET, ) -> Dict[str, Any]: params: Dict[str, Any] = {} + params["common"] = common params = {k: v for k, v in params.items() if v is not UNSET and v is not None} @@ -45,11 +46,11 @@ def _build_response(*, client: Union[AuthenticatedClient, Client], response: htt def sync_detailed( *, client: Union[AuthenticatedClient, Client], - common: Union[Unset, None, str] = UNSET, + common: Union[Unset, str] = UNSET, ) -> Response[Any]: """ Args: - common (Union[Unset, None, str]): + common (Union[Unset, str]): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -73,11 +74,11 @@ def sync_detailed( async def asyncio_detailed( *, client: Union[AuthenticatedClient, Client], - common: Union[Unset, None, str] = UNSET, + common: Union[Unset, str] = UNSET, ) -> Response[Any]: """ Args: - common (Union[Unset, None, str]): + common (Union[Unset, str]): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/default/post_common_parameters.py b/end_to_end_tests/golden-record/my_test_api_client/api/default/post_common_parameters.py index 4f82c6f90..0c3b351f3 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/default/post_common_parameters.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/default/post_common_parameters.py @@ -10,9 +10,10 @@ def _get_kwargs( *, - common: Union[Unset, None, str] = UNSET, + common: Union[Unset, str] = UNSET, ) -> Dict[str, Any]: params: Dict[str, Any] = {} + params["common"] = common params = {k: v for k, v in params.items() if v is not UNSET and v is not None} @@ -45,11 +46,11 @@ def _build_response(*, client: Union[AuthenticatedClient, Client], response: htt def sync_detailed( *, client: Union[AuthenticatedClient, Client], - common: Union[Unset, None, str] = UNSET, + common: Union[Unset, str] = UNSET, ) -> Response[Any]: """ Args: - common (Union[Unset, None, str]): + common (Union[Unset, str]): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -73,11 +74,11 @@ def sync_detailed( async def asyncio_detailed( *, client: Union[AuthenticatedClient, Client], - common: Union[Unset, None, str] = UNSET, + common: Union[Unset, str] = UNSET, ) -> Response[Any]: """ Args: - common (Union[Unset, None, str]): + common (Union[Unset, str]): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/default/reserved_parameters.py b/end_to_end_tests/golden-record/my_test_api_client/api/default/reserved_parameters.py index 7fb74c804..8f436901f 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/default/reserved_parameters.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/default/reserved_parameters.py @@ -14,6 +14,7 @@ def _get_kwargs( url_query: str, ) -> Dict[str, Any]: params: Dict[str, Any] = {} + params["client"] = client_query params["url"] = url_query diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/defaults/__init__.py b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/tests/defaults_tests_defaults_post.py b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py similarity index 88% rename from end_to_end_tests/golden-record/my_test_api_client/api/tests/defaults_tests_defaults_post.py rename to end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py index 8d1702b71..529190562 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/tests/defaults_tests_defaults_post.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py @@ -16,20 +16,24 @@ def _get_kwargs( *, string_prop: str = "the default string", + string_with_num: str = "1", date_prop: datetime.date = isoparse("1010-10-10").date(), float_prop: float = 3.14, int_prop: int = 7, boolean_prop: bool = False, list_prop: List[AnEnum], union_prop: Union[float, str] = "not a float", - union_prop_with_ref: Union[AnEnum, None, Unset, float] = 0.6, + union_prop_with_ref: Union[AnEnum, Unset, float] = 0.6, enum_prop: AnEnum, model_prop: "ModelWithUnionProperty", required_model_prop: "ModelWithUnionProperty", ) -> Dict[str, Any]: params: Dict[str, Any] = {} + params["string_prop"] = string_prop + params["string with num"] = string_with_num + json_date_prop = date_prop.isoformat() params["date_prop"] = json_date_prop @@ -42,23 +46,17 @@ def _get_kwargs( json_list_prop = [] for list_prop_item_data in list_prop: list_prop_item = list_prop_item_data.value - json_list_prop.append(list_prop_item) params["list_prop"] = json_list_prop json_union_prop: Union[float, str] - json_union_prop = union_prop - params["union_prop"] = json_union_prop - json_union_prop_with_ref: Union[None, Unset, float, str] + json_union_prop_with_ref: Union[Unset, float, str] if isinstance(union_prop_with_ref, Unset): json_union_prop_with_ref = UNSET - elif union_prop_with_ref is None: - json_union_prop_with_ref = None - elif isinstance(union_prop_with_ref, AnEnum): json_union_prop_with_ref = UNSET if not isinstance(union_prop_with_ref, Unset): @@ -66,26 +64,22 @@ def _get_kwargs( else: json_union_prop_with_ref = union_prop_with_ref - params["union_prop_with_ref"] = json_union_prop_with_ref json_enum_prop = enum_prop.value - params["enum_prop"] = json_enum_prop json_model_prop = model_prop.to_dict() - params.update(json_model_prop) json_required_model_prop = required_model_prop.to_dict() - params.update(json_required_model_prop) params = {k: v for k, v in params.items() if v is not UNSET and v is not None} return { "method": "post", - "url": "/tests/defaults", + "url": "/defaults", "params": params, } @@ -121,13 +115,14 @@ def sync_detailed( *, client: Union[AuthenticatedClient, Client], string_prop: str = "the default string", + string_with_num: str = "1", date_prop: datetime.date = isoparse("1010-10-10").date(), float_prop: float = 3.14, int_prop: int = 7, boolean_prop: bool = False, list_prop: List[AnEnum], union_prop: Union[float, str] = "not a float", - union_prop_with_ref: Union[AnEnum, None, Unset, float] = 0.6, + union_prop_with_ref: Union[AnEnum, Unset, float] = 0.6, enum_prop: AnEnum, model_prop: "ModelWithUnionProperty", required_model_prop: "ModelWithUnionProperty", @@ -136,13 +131,14 @@ def sync_detailed( Args: string_prop (str): Default: 'the default string'. + string_with_num (str): Default: '1'. date_prop (datetime.date): Default: isoparse('1010-10-10').date(). float_prop (float): Default: 3.14. int_prop (int): Default: 7. - boolean_prop (bool): + boolean_prop (bool): Default: False. list_prop (List[AnEnum]): union_prop (Union[float, str]): Default: 'not a float'. - union_prop_with_ref (Union[AnEnum, None, Unset, float]): Default: 0.6. + union_prop_with_ref (Union[AnEnum, Unset, float]): Default: 0.6. enum_prop (AnEnum): For testing Enums in all the ways they can be used model_prop (ModelWithUnionProperty): required_model_prop (ModelWithUnionProperty): @@ -157,6 +153,7 @@ def sync_detailed( kwargs = _get_kwargs( string_prop=string_prop, + string_with_num=string_with_num, date_prop=date_prop, float_prop=float_prop, int_prop=int_prop, @@ -180,13 +177,14 @@ def sync( *, client: Union[AuthenticatedClient, Client], string_prop: str = "the default string", + string_with_num: str = "1", date_prop: datetime.date = isoparse("1010-10-10").date(), float_prop: float = 3.14, int_prop: int = 7, boolean_prop: bool = False, list_prop: List[AnEnum], union_prop: Union[float, str] = "not a float", - union_prop_with_ref: Union[AnEnum, None, Unset, float] = 0.6, + union_prop_with_ref: Union[AnEnum, Unset, float] = 0.6, enum_prop: AnEnum, model_prop: "ModelWithUnionProperty", required_model_prop: "ModelWithUnionProperty", @@ -195,13 +193,14 @@ def sync( Args: string_prop (str): Default: 'the default string'. + string_with_num (str): Default: '1'. date_prop (datetime.date): Default: isoparse('1010-10-10').date(). float_prop (float): Default: 3.14. int_prop (int): Default: 7. - boolean_prop (bool): + boolean_prop (bool): Default: False. list_prop (List[AnEnum]): union_prop (Union[float, str]): Default: 'not a float'. - union_prop_with_ref (Union[AnEnum, None, Unset, float]): Default: 0.6. + union_prop_with_ref (Union[AnEnum, Unset, float]): Default: 0.6. enum_prop (AnEnum): For testing Enums in all the ways they can be used model_prop (ModelWithUnionProperty): required_model_prop (ModelWithUnionProperty): @@ -217,6 +216,7 @@ def sync( return sync_detailed( client=client, string_prop=string_prop, + string_with_num=string_with_num, date_prop=date_prop, float_prop=float_prop, int_prop=int_prop, @@ -234,13 +234,14 @@ async def asyncio_detailed( *, client: Union[AuthenticatedClient, Client], string_prop: str = "the default string", + string_with_num: str = "1", date_prop: datetime.date = isoparse("1010-10-10").date(), float_prop: float = 3.14, int_prop: int = 7, boolean_prop: bool = False, list_prop: List[AnEnum], union_prop: Union[float, str] = "not a float", - union_prop_with_ref: Union[AnEnum, None, Unset, float] = 0.6, + union_prop_with_ref: Union[AnEnum, Unset, float] = 0.6, enum_prop: AnEnum, model_prop: "ModelWithUnionProperty", required_model_prop: "ModelWithUnionProperty", @@ -249,13 +250,14 @@ async def asyncio_detailed( Args: string_prop (str): Default: 'the default string'. + string_with_num (str): Default: '1'. date_prop (datetime.date): Default: isoparse('1010-10-10').date(). float_prop (float): Default: 3.14. int_prop (int): Default: 7. - boolean_prop (bool): + boolean_prop (bool): Default: False. list_prop (List[AnEnum]): union_prop (Union[float, str]): Default: 'not a float'. - union_prop_with_ref (Union[AnEnum, None, Unset, float]): Default: 0.6. + union_prop_with_ref (Union[AnEnum, Unset, float]): Default: 0.6. enum_prop (AnEnum): For testing Enums in all the ways they can be used model_prop (ModelWithUnionProperty): required_model_prop (ModelWithUnionProperty): @@ -270,6 +272,7 @@ async def asyncio_detailed( kwargs = _get_kwargs( string_prop=string_prop, + string_with_num=string_with_num, date_prop=date_prop, float_prop=float_prop, int_prop=int_prop, @@ -291,13 +294,14 @@ async def asyncio( *, client: Union[AuthenticatedClient, Client], string_prop: str = "the default string", + string_with_num: str = "1", date_prop: datetime.date = isoparse("1010-10-10").date(), float_prop: float = 3.14, int_prop: int = 7, boolean_prop: bool = False, list_prop: List[AnEnum], union_prop: Union[float, str] = "not a float", - union_prop_with_ref: Union[AnEnum, None, Unset, float] = 0.6, + union_prop_with_ref: Union[AnEnum, Unset, float] = 0.6, enum_prop: AnEnum, model_prop: "ModelWithUnionProperty", required_model_prop: "ModelWithUnionProperty", @@ -306,13 +310,14 @@ async def asyncio( Args: string_prop (str): Default: 'the default string'. + string_with_num (str): Default: '1'. date_prop (datetime.date): Default: isoparse('1010-10-10').date(). float_prop (float): Default: 3.14. int_prop (int): Default: 7. - boolean_prop (bool): + boolean_prop (bool): Default: False. list_prop (List[AnEnum]): union_prop (Union[float, str]): Default: 'not a float'. - union_prop_with_ref (Union[AnEnum, None, Unset, float]): Default: 0.6. + union_prop_with_ref (Union[AnEnum, Unset, float]): Default: 0.6. enum_prop (AnEnum): For testing Enums in all the ways they can be used model_prop (ModelWithUnionProperty): required_model_prop (ModelWithUnionProperty): @@ -329,6 +334,7 @@ async def asyncio( await asyncio_detailed( client=client, string_prop=string_prop, + string_with_num=string_with_num, date_prop=date_prop, float_prop=float_prop, int_prop=int_prop, diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/location/get_location_query_optionality.py b/end_to_end_tests/golden-record/my_test_api_client/api/location/get_location_query_optionality.py index 7daa34252..9bacd49e5 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/location/get_location_query_optionality.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/location/get_location_query_optionality.py @@ -12,31 +12,36 @@ def _get_kwargs( *, not_null_required: datetime.datetime, - null_required: Union[Unset, None, datetime.datetime] = UNSET, - null_not_required: Union[Unset, None, datetime.datetime] = UNSET, - not_null_not_required: Union[Unset, None, datetime.datetime] = UNSET, + null_required: Union[None, datetime.datetime], + null_not_required: Union[None, Unset, datetime.datetime] = UNSET, + not_null_not_required: Union[Unset, datetime.datetime] = UNSET, ) -> Dict[str, Any]: params: Dict[str, Any] = {} - json_not_null_required = not_null_required.isoformat() + json_not_null_required = not_null_required.isoformat() params["not_null_required"] = json_not_null_required - json_null_required: Union[Unset, None, str] = UNSET - if not isinstance(null_required, Unset): - json_null_required = null_required.isoformat() if null_required else None - + json_null_required: Union[None, str] + if isinstance(null_required, datetime.datetime): + json_null_required = null_required.isoformat() + else: + json_null_required = null_required params["null_required"] = json_null_required - json_null_not_required: Union[Unset, None, str] = UNSET - if not isinstance(null_not_required, Unset): - json_null_not_required = null_not_required.isoformat() if null_not_required else None - + json_null_not_required: Union[None, Unset, str] + if isinstance(null_not_required, Unset): + json_null_not_required = UNSET + elif isinstance(null_not_required, datetime.datetime): + json_null_not_required = UNSET + if not isinstance(null_not_required, Unset): + json_null_not_required = null_not_required.isoformat() + else: + json_null_not_required = null_not_required params["null_not_required"] = json_null_not_required - json_not_null_not_required: Union[Unset, None, str] = UNSET + json_not_null_not_required: Union[Unset, str] = UNSET if not isinstance(not_null_not_required, Unset): - json_not_null_not_required = not_null_not_required.isoformat() if not_null_not_required else None - + json_not_null_not_required = not_null_not_required.isoformat() params["not_null_not_required"] = json_not_null_not_required params = {k: v for k, v in params.items() if v is not UNSET and v is not None} @@ -70,16 +75,16 @@ def sync_detailed( *, client: Union[AuthenticatedClient, Client], not_null_required: datetime.datetime, - null_required: Union[Unset, None, datetime.datetime] = UNSET, - null_not_required: Union[Unset, None, datetime.datetime] = UNSET, - not_null_not_required: Union[Unset, None, datetime.datetime] = UNSET, + null_required: Union[None, datetime.datetime], + null_not_required: Union[None, Unset, datetime.datetime] = UNSET, + not_null_not_required: Union[Unset, datetime.datetime] = UNSET, ) -> Response[Any]: """ Args: not_null_required (datetime.datetime): - null_required (Union[Unset, None, datetime.datetime]): - null_not_required (Union[Unset, None, datetime.datetime]): - not_null_not_required (Union[Unset, None, datetime.datetime]): + null_required (Union[None, datetime.datetime]): + null_not_required (Union[None, Unset, datetime.datetime]): + not_null_not_required (Union[Unset, datetime.datetime]): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -107,16 +112,16 @@ async def asyncio_detailed( *, client: Union[AuthenticatedClient, Client], not_null_required: datetime.datetime, - null_required: Union[Unset, None, datetime.datetime] = UNSET, - null_not_required: Union[Unset, None, datetime.datetime] = UNSET, - not_null_not_required: Union[Unset, None, datetime.datetime] = UNSET, + null_required: Union[None, datetime.datetime], + null_not_required: Union[None, Unset, datetime.datetime] = UNSET, + not_null_not_required: Union[Unset, datetime.datetime] = UNSET, ) -> Response[Any]: """ Args: not_null_required (datetime.datetime): - null_required (Union[Unset, None, datetime.datetime]): - null_not_required (Union[Unset, None, datetime.datetime]): - not_null_not_required (Union[Unset, None, datetime.datetime]): + null_required (Union[None, datetime.datetime]): + null_not_required (Union[None, Unset, datetime.datetime]): + not_null_not_required (Union[Unset, datetime.datetime]): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/parameter_references/get_parameter_references_path_param.py b/end_to_end_tests/golden-record/my_test_api_client/api/parameter_references/get_parameter_references_path_param.py index 0f9c603f2..aca8f6858 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/parameter_references/get_parameter_references_path_param.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/parameter_references/get_parameter_references_path_param.py @@ -11,9 +11,9 @@ def _get_kwargs( path_param: str, *, - string_param: Union[Unset, None, str] = UNSET, - integer_param: Union[Unset, None, int] = 0, - header_param: Union[Unset, str] = UNSET, + string_param: Union[Unset, str] = UNSET, + integer_param: Union[Unset, int] = 0, + header_param: Union[None, Unset, str] = UNSET, cookie_param: Union[Unset, str] = UNSET, ) -> Dict[str, Any]: headers = {} @@ -25,6 +25,7 @@ def _get_kwargs( cookies["cookie param"] = cookie_param params: Dict[str, Any] = {} + params["string param"] = string_param params["integer param"] = integer_param @@ -64,18 +65,18 @@ def sync_detailed( path_param: str, *, client: Union[AuthenticatedClient, Client], - string_param: Union[Unset, None, str] = UNSET, - integer_param: Union[Unset, None, int] = 0, - header_param: Union[Unset, str] = UNSET, + string_param: Union[Unset, str] = UNSET, + integer_param: Union[Unset, int] = 0, + header_param: Union[None, Unset, str] = UNSET, cookie_param: Union[Unset, str] = UNSET, ) -> Response[Any]: """Test different types of parameter references Args: path_param (str): - string_param (Union[Unset, None, str]): - integer_param (Union[Unset, None, int]): - header_param (Union[Unset, str]): + string_param (Union[Unset, str]): + integer_param (Union[Unset, int]): Default: 0. + header_param (Union[None, Unset, str]): cookie_param (Union[Unset, str]): Raises: @@ -105,18 +106,18 @@ async def asyncio_detailed( path_param: str, *, client: Union[AuthenticatedClient, Client], - string_param: Union[Unset, None, str] = UNSET, - integer_param: Union[Unset, None, int] = 0, - header_param: Union[Unset, str] = UNSET, + string_param: Union[Unset, str] = UNSET, + integer_param: Union[Unset, int] = 0, + header_param: Union[None, Unset, str] = UNSET, cookie_param: Union[Unset, str] = UNSET, ) -> Response[Any]: """Test different types of parameter references Args: path_param (str): - string_param (Union[Unset, None, str]): - integer_param (Union[Unset, None, int]): - header_param (Union[Unset, str]): + string_param (Union[Unset, str]): + integer_param (Union[Unset, int]): Default: 0. + header_param (Union[None, Unset, str]): cookie_param (Union[Unset, str]): Raises: diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/parameters/delete_common_parameters_overriding_param.py b/end_to_end_tests/golden-record/my_test_api_client/api/parameters/delete_common_parameters_overriding_param.py index bf33c3206..c0ea3b0cb 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/parameters/delete_common_parameters_overriding_param.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/parameters/delete_common_parameters_overriding_param.py @@ -11,9 +11,10 @@ def _get_kwargs( param_path: str, *, - param_query: Union[Unset, None, str] = UNSET, + param_query: Union[Unset, str] = UNSET, ) -> Dict[str, Any]: params: Dict[str, Any] = {} + params["param"] = param_query params = {k: v for k, v in params.items() if v is not UNSET and v is not None} @@ -49,12 +50,12 @@ def sync_detailed( param_path: str, *, client: Union[AuthenticatedClient, Client], - param_query: Union[Unset, None, str] = UNSET, + param_query: Union[Unset, str] = UNSET, ) -> Response[Any]: """ Args: param_path (str): - param_query (Union[Unset, None, str]): + param_query (Union[Unset, str]): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. @@ -80,12 +81,12 @@ async def asyncio_detailed( param_path: str, *, client: Union[AuthenticatedClient, Client], - param_query: Union[Unset, None, str] = UNSET, + param_query: Union[Unset, str] = UNSET, ) -> Response[Any]: """ Args: param_path (str): - param_query (Union[Unset, None, str]): + param_query (Union[Unset, str]): Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/parameters/get_common_parameters_overriding_param.py b/end_to_end_tests/golden-record/my_test_api_client/api/parameters/get_common_parameters_overriding_param.py index 73d4dcfd7..c3074476a 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/parameters/get_common_parameters_overriding_param.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/parameters/get_common_parameters_overriding_param.py @@ -14,6 +14,7 @@ def _get_kwargs( param_query: str = "overridden_in_GET", ) -> Dict[str, Any]: params: Dict[str, Any] = {} + params["param"] = param_query params = {k: v for k, v in params.items() if v is not UNSET and v is not None} diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/parameters/get_same_name_multiple_locations_param.py b/end_to_end_tests/golden-record/my_test_api_client/api/parameters/get_same_name_multiple_locations_param.py index 6aa991293..aad28a5f2 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/parameters/get_same_name_multiple_locations_param.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/parameters/get_same_name_multiple_locations_param.py @@ -11,7 +11,7 @@ def _get_kwargs( param_path: str, *, - param_query: Union[Unset, None, str] = UNSET, + param_query: Union[Unset, str] = UNSET, param_header: Union[Unset, str] = UNSET, param_cookie: Union[Unset, str] = UNSET, ) -> Dict[str, Any]: @@ -24,6 +24,7 @@ def _get_kwargs( cookies["param"] = param_cookie params: Dict[str, Any] = {} + params["param"] = param_query params = {k: v for k, v in params.items() if v is not UNSET and v is not None} @@ -61,14 +62,14 @@ def sync_detailed( param_path: str, *, client: Union[AuthenticatedClient, Client], - param_query: Union[Unset, None, str] = UNSET, + param_query: Union[Unset, str] = UNSET, param_header: Union[Unset, str] = UNSET, param_cookie: Union[Unset, str] = UNSET, ) -> Response[Any]: """ Args: param_path (str): - param_query (Union[Unset, None, str]): + param_query (Union[Unset, str]): param_header (Union[Unset, str]): param_cookie (Union[Unset, str]): @@ -98,14 +99,14 @@ async def asyncio_detailed( param_path: str, *, client: Union[AuthenticatedClient, Client], - param_query: Union[Unset, None, str] = UNSET, + param_query: Union[Unset, str] = UNSET, param_header: Union[Unset, str] = UNSET, param_cookie: Union[Unset, str] = UNSET, ) -> Response[Any]: """ Args: param_path (str): - param_query (Union[Unset, None, str]): + param_query (Union[Unset, str]): param_header (Union[Unset, str]): param_cookie (Union[Unset, str]): diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/tests/get_user_list.py b/end_to_end_tests/golden-record/my_test_api_client/api/tests/get_user_list.py index c03b67369..0c1084cf6 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/tests/get_user_list.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/tests/get_user_list.py @@ -16,25 +16,26 @@ def _get_kwargs( *, an_enum_value: List[AnEnum], - an_enum_value_with_null: List[Optional[AnEnumWithNull]], + an_enum_value_with_null: List[Union[AnEnumWithNull, None]], an_enum_value_with_only_null: List[None], some_date: Union[datetime.date, datetime.datetime], ) -> Dict[str, Any]: params: Dict[str, Any] = {} + json_an_enum_value = [] for an_enum_value_item_data in an_enum_value: an_enum_value_item = an_enum_value_item_data.value - json_an_enum_value.append(an_enum_value_item) params["an_enum_value"] = json_an_enum_value json_an_enum_value_with_null = [] for an_enum_value_with_null_item_data in an_enum_value_with_null: - an_enum_value_with_null_item = ( - an_enum_value_with_null_item_data.value if an_enum_value_with_null_item_data else None - ) - + an_enum_value_with_null_item: Union[None, str] + if isinstance(an_enum_value_with_null_item_data, AnEnumWithNull): + an_enum_value_with_null_item = an_enum_value_with_null_item_data.value + else: + an_enum_value_with_null_item = an_enum_value_with_null_item_data json_an_enum_value_with_null.append(an_enum_value_with_null_item) params["an_enum_value_with_null"] = json_an_enum_value_with_null @@ -44,7 +45,6 @@ def _get_kwargs( params["an_enum_value_with_only_null"] = json_an_enum_value_with_only_null json_some_date: str - if isinstance(some_date, datetime.date): json_some_date = some_date.isoformat() else: @@ -102,7 +102,7 @@ def sync_detailed( *, client: Union[AuthenticatedClient, Client], an_enum_value: List[AnEnum], - an_enum_value_with_null: List[Optional[AnEnumWithNull]], + an_enum_value_with_null: List[Union[AnEnumWithNull, None]], an_enum_value_with_only_null: List[None], some_date: Union[datetime.date, datetime.datetime], ) -> Response[Union[HTTPValidationError, List["AModel"]]]: @@ -112,7 +112,7 @@ def sync_detailed( Args: an_enum_value (List[AnEnum]): - an_enum_value_with_null (List[Optional[AnEnumWithNull]]): + an_enum_value_with_null (List[Union[AnEnumWithNull, None]]): an_enum_value_with_only_null (List[None]): some_date (Union[datetime.date, datetime.datetime]): @@ -142,7 +142,7 @@ def sync( *, client: Union[AuthenticatedClient, Client], an_enum_value: List[AnEnum], - an_enum_value_with_null: List[Optional[AnEnumWithNull]], + an_enum_value_with_null: List[Union[AnEnumWithNull, None]], an_enum_value_with_only_null: List[None], some_date: Union[datetime.date, datetime.datetime], ) -> Optional[Union[HTTPValidationError, List["AModel"]]]: @@ -152,7 +152,7 @@ def sync( Args: an_enum_value (List[AnEnum]): - an_enum_value_with_null (List[Optional[AnEnumWithNull]]): + an_enum_value_with_null (List[Union[AnEnumWithNull, None]]): an_enum_value_with_only_null (List[None]): some_date (Union[datetime.date, datetime.datetime]): @@ -177,7 +177,7 @@ async def asyncio_detailed( *, client: Union[AuthenticatedClient, Client], an_enum_value: List[AnEnum], - an_enum_value_with_null: List[Optional[AnEnumWithNull]], + an_enum_value_with_null: List[Union[AnEnumWithNull, None]], an_enum_value_with_only_null: List[None], some_date: Union[datetime.date, datetime.datetime], ) -> Response[Union[HTTPValidationError, List["AModel"]]]: @@ -187,7 +187,7 @@ async def asyncio_detailed( Args: an_enum_value (List[AnEnum]): - an_enum_value_with_null (List[Optional[AnEnumWithNull]]): + an_enum_value_with_null (List[Union[AnEnumWithNull, None]]): an_enum_value_with_only_null (List[None]): some_date (Union[datetime.date, datetime.datetime]): @@ -215,7 +215,7 @@ async def asyncio( *, client: Union[AuthenticatedClient, Client], an_enum_value: List[AnEnum], - an_enum_value_with_null: List[Optional[AnEnumWithNull]], + an_enum_value_with_null: List[Union[AnEnumWithNull, None]], an_enum_value_with_only_null: List[None], some_date: Union[datetime.date, datetime.datetime], ) -> Optional[Union[HTTPValidationError, List["AModel"]]]: @@ -225,7 +225,7 @@ async def asyncio( Args: an_enum_value (List[AnEnum]): - an_enum_value_with_null (List[Optional[AnEnumWithNull]]): + an_enum_value_with_null (List[Union[AnEnumWithNull, None]]): an_enum_value_with_only_null (List[None]): some_date (Union[datetime.date, datetime.datetime]): diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/tests/int_enum_tests_int_enum_post.py b/end_to_end_tests/golden-record/my_test_api_client/api/tests/int_enum_tests_int_enum_post.py index bbfa1b885..dfedf685f 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/tests/int_enum_tests_int_enum_post.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/tests/int_enum_tests_int_enum_post.py @@ -15,8 +15,8 @@ def _get_kwargs( int_enum: AnIntEnum, ) -> Dict[str, Any]: params: Dict[str, Any] = {} - json_int_enum = int_enum.value + json_int_enum = int_enum.value params["int_enum"] = json_int_enum params = {k: v for k, v in params.items() if v is not UNSET and v is not None} diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/true_/false_.py b/end_to_end_tests/golden-record/my_test_api_client/api/true_/false_.py index 586a1ecdd..b747a3aa0 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/true_/false_.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/true_/false_.py @@ -13,6 +13,7 @@ def _get_kwargs( import_: str, ) -> Dict[str, Any]: params: Dict[str, Any] = {} + params["import"] = import_ params = {k: v for k, v in params.items() if v is not UNSET and v is not None} diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/a_form_data.py b/end_to_end_tests/golden-record/my_test_api_client/models/a_form_data.py index cbc06dded..a4c5cd8a7 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/a_form_data.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/a_form_data.py @@ -22,6 +22,7 @@ class AFormData: def to_dict(self) -> Dict[str, Any]: an_required_field = self.an_required_field + an_optional_field = self.an_optional_field field_dict: Dict[str, Any] = {} diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/a_model.py b/end_to_end_tests/golden-record/my_test_api_client/models/a_model.py index 6ac9c21b2..f1bd543ce 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/a_model.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/a_model.py @@ -1,5 +1,5 @@ import datetime -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type, TypeVar, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union, cast from attrs import define as _attrs_define from dateutil.parser import isoparse @@ -26,37 +26,37 @@ class AModel: an_allof_enum_with_overridden_default (AnAllOfEnum): Default: AnAllOfEnum.OVERRIDDEN_DEFAULT. a_camel_date_time (Union[datetime.date, datetime.datetime]): a_date (datetime.date): + a_nullable_date (Union[None, datetime.date]): + required_nullable (Union[None, str]): required_not_nullable (str): one_of_models (Union['FreeFormModel', 'ModelWithUnionProperty', Any]): + nullable_one_of_models (Union['FreeFormModel', 'ModelWithUnionProperty', None]): model (ModelWithUnionProperty): + nullable_model (Union['ModelWithUnionProperty', None]): any_value (Union[Unset, Any]): an_optional_allof_enum (Union[Unset, AnAllOfEnum]): nested_list_of_enums (Union[Unset, List[List[DifferentEnum]]]): - a_nullable_date (Optional[datetime.date]): a_not_required_date (Union[Unset, datetime.date]): attr_1_leading_digit (Union[Unset, str]): attr_leading_underscore (Union[Unset, str]): - required_nullable (Optional[str]): - not_required_nullable (Union[Unset, None, str]): + not_required_nullable (Union[None, Unset, str]): not_required_not_nullable (Union[Unset, str]): - nullable_one_of_models (Union['FreeFormModel', 'ModelWithUnionProperty', None]): not_required_one_of_models (Union['FreeFormModel', 'ModelWithUnionProperty', Unset]): not_required_nullable_one_of_models (Union['FreeFormModel', 'ModelWithUnionProperty', None, Unset, str]): - nullable_model (Optional[ModelWithUnionProperty]): not_required_model (Union[Unset, ModelWithUnionProperty]): - not_required_nullable_model (Union[Unset, None, ModelWithUnionProperty]): + not_required_nullable_model (Union['ModelWithUnionProperty', None, Unset]): """ an_enum_value: AnEnum a_camel_date_time: Union[datetime.date, datetime.datetime] a_date: datetime.date + a_nullable_date: Union[None, datetime.date] + required_nullable: Union[None, str] required_not_nullable: str one_of_models: Union["FreeFormModel", "ModelWithUnionProperty", Any] - model: "ModelWithUnionProperty" - a_nullable_date: Optional[datetime.date] - required_nullable: Optional[str] nullable_one_of_models: Union["FreeFormModel", "ModelWithUnionProperty", None] - nullable_model: Optional["ModelWithUnionProperty"] + model: "ModelWithUnionProperty" + nullable_model: Union["ModelWithUnionProperty", None] an_allof_enum_with_overridden_default: AnAllOfEnum = AnAllOfEnum.OVERRIDDEN_DEFAULT any_value: Union[Unset, Any] = UNSET an_optional_allof_enum: Union[Unset, AnAllOfEnum] = UNSET @@ -64,12 +64,12 @@ class AModel: a_not_required_date: Union[Unset, datetime.date] = UNSET attr_1_leading_digit: Union[Unset, str] = UNSET attr_leading_underscore: Union[Unset, str] = UNSET - not_required_nullable: Union[Unset, None, str] = UNSET + not_required_nullable: Union[None, Unset, str] = UNSET not_required_not_nullable: Union[Unset, str] = UNSET not_required_one_of_models: Union["FreeFormModel", "ModelWithUnionProperty", Unset] = UNSET not_required_nullable_one_of_models: Union["FreeFormModel", "ModelWithUnionProperty", None, Unset, str] = UNSET not_required_model: Union[Unset, "ModelWithUnionProperty"] = UNSET - not_required_nullable_model: Union[Unset, None, "ModelWithUnionProperty"] = UNSET + not_required_nullable_model: Union["ModelWithUnionProperty", None, Unset] = UNSET def to_dict(self) -> Dict[str, Any]: from ..models.free_form_model import FreeFormModel @@ -80,29 +80,50 @@ def to_dict(self) -> Dict[str, Any]: an_allof_enum_with_overridden_default = self.an_allof_enum_with_overridden_default.value a_camel_date_time: str - if isinstance(self.a_camel_date_time, datetime.datetime): a_camel_date_time = self.a_camel_date_time.isoformat() - else: a_camel_date_time = self.a_camel_date_time.isoformat() a_date = self.a_date.isoformat() + + a_nullable_date: Union[None, str] + if isinstance(self.a_nullable_date, datetime.date): + a_nullable_date = self.a_nullable_date.isoformat() + else: + a_nullable_date = self.a_nullable_date + + required_nullable: Union[None, str] + required_nullable = self.required_nullable + required_not_nullable = self.required_not_nullable - one_of_models: Union[Any, Dict[str, Any]] + one_of_models: Union[Any, Dict[str, Any]] if isinstance(self.one_of_models, FreeFormModel): one_of_models = self.one_of_models.to_dict() - elif isinstance(self.one_of_models, ModelWithUnionProperty): one_of_models = self.one_of_models.to_dict() - else: one_of_models = self.one_of_models + nullable_one_of_models: Union[Dict[str, Any], None] + if isinstance(self.nullable_one_of_models, FreeFormModel): + nullable_one_of_models = self.nullable_one_of_models.to_dict() + elif isinstance(self.nullable_one_of_models, ModelWithUnionProperty): + nullable_one_of_models = self.nullable_one_of_models.to_dict() + else: + nullable_one_of_models = self.nullable_one_of_models + model = self.model.to_dict() + nullable_model: Union[Dict[str, Any], None] + if isinstance(self.nullable_model, ModelWithUnionProperty): + nullable_model = self.nullable_model.to_dict() + else: + nullable_model = self.nullable_model + any_value = self.any_value + an_optional_allof_enum: Union[Unset, str] = UNSET if not isinstance(self.an_optional_allof_enum, Unset): an_optional_allof_enum = self.an_optional_allof_enum.value @@ -114,40 +135,33 @@ def to_dict(self) -> Dict[str, Any]: nested_list_of_enums_item = [] for nested_list_of_enums_item_item_data in nested_list_of_enums_item_data: nested_list_of_enums_item_item = nested_list_of_enums_item_item_data.value - nested_list_of_enums_item.append(nested_list_of_enums_item_item) nested_list_of_enums.append(nested_list_of_enums_item) - a_nullable_date = self.a_nullable_date.isoformat() if self.a_nullable_date else None a_not_required_date: Union[Unset, str] = UNSET if not isinstance(self.a_not_required_date, Unset): a_not_required_date = self.a_not_required_date.isoformat() attr_1_leading_digit = self.attr_1_leading_digit - attr_leading_underscore = self.attr_leading_underscore - required_nullable = self.required_nullable - not_required_nullable = self.not_required_nullable - not_required_not_nullable = self.not_required_not_nullable - nullable_one_of_models: Union[Dict[str, Any], None] - if self.nullable_one_of_models is None: - nullable_one_of_models = None - elif isinstance(self.nullable_one_of_models, FreeFormModel): - nullable_one_of_models = self.nullable_one_of_models.to_dict() + attr_leading_underscore = self.attr_leading_underscore + not_required_nullable: Union[None, Unset, str] + if isinstance(self.not_required_nullable, Unset): + not_required_nullable = UNSET else: - nullable_one_of_models = self.nullable_one_of_models.to_dict() + not_required_nullable = self.not_required_nullable + + not_required_not_nullable = self.not_required_not_nullable not_required_one_of_models: Union[Dict[str, Any], Unset] if isinstance(self.not_required_one_of_models, Unset): not_required_one_of_models = UNSET - elif isinstance(self.not_required_one_of_models, FreeFormModel): not_required_one_of_models = UNSET if not isinstance(self.not_required_one_of_models, Unset): not_required_one_of_models = self.not_required_one_of_models.to_dict() - else: not_required_one_of_models = UNSET if not isinstance(self.not_required_one_of_models, Unset): @@ -156,33 +170,30 @@ def to_dict(self) -> Dict[str, Any]: not_required_nullable_one_of_models: Union[Dict[str, Any], None, Unset, str] if isinstance(self.not_required_nullable_one_of_models, Unset): not_required_nullable_one_of_models = UNSET - elif self.not_required_nullable_one_of_models is None: - not_required_nullable_one_of_models = None - elif isinstance(self.not_required_nullable_one_of_models, FreeFormModel): not_required_nullable_one_of_models = UNSET if not isinstance(self.not_required_nullable_one_of_models, Unset): not_required_nullable_one_of_models = self.not_required_nullable_one_of_models.to_dict() - elif isinstance(self.not_required_nullable_one_of_models, ModelWithUnionProperty): not_required_nullable_one_of_models = UNSET if not isinstance(self.not_required_nullable_one_of_models, Unset): not_required_nullable_one_of_models = self.not_required_nullable_one_of_models.to_dict() - else: not_required_nullable_one_of_models = self.not_required_nullable_one_of_models - nullable_model = self.nullable_model.to_dict() if self.nullable_model else None - not_required_model: Union[Unset, Dict[str, Any]] = UNSET if not isinstance(self.not_required_model, Unset): not_required_model = self.not_required_model.to_dict() - not_required_nullable_model: Union[Unset, None, Dict[str, Any]] = UNSET - if not isinstance(self.not_required_nullable_model, Unset): - not_required_nullable_model = ( - self.not_required_nullable_model.to_dict() if self.not_required_nullable_model else None - ) + not_required_nullable_model: Union[Dict[str, Any], None, Unset] + if isinstance(self.not_required_nullable_model, Unset): + not_required_nullable_model = UNSET + elif isinstance(self.not_required_nullable_model, ModelWithUnionProperty): + not_required_nullable_model = UNSET + if not isinstance(self.not_required_nullable_model, Unset): + not_required_nullable_model = self.not_required_nullable_model.to_dict() + else: + not_required_nullable_model = self.not_required_nullable_model field_dict: Dict[str, Any] = {} field_dict.update( @@ -191,12 +202,12 @@ def to_dict(self) -> Dict[str, Any]: "an_allof_enum_with_overridden_default": an_allof_enum_with_overridden_default, "aCamelDateTime": a_camel_date_time, "a_date": a_date, - "required_not_nullable": required_not_nullable, - "one_of_models": one_of_models, - "model": model, "a_nullable_date": a_nullable_date, "required_nullable": required_nullable, + "required_not_nullable": required_not_nullable, + "one_of_models": one_of_models, "nullable_one_of_models": nullable_one_of_models, + "model": model, "nullable_model": nullable_model, } ) @@ -256,6 +267,28 @@ def _parse_a_camel_date_time(data: object) -> Union[datetime.date, datetime.date a_date = isoparse(d.pop("a_date")).date() + def _parse_a_nullable_date(data: object) -> Union[None, datetime.date]: + if data is None: + return data + try: + if not isinstance(data, str): + raise TypeError() + a_nullable_date_type_0 = isoparse(data).date() + + return a_nullable_date_type_0 + except: # noqa: E722 + pass + return cast(Union[None, datetime.date], data) + + a_nullable_date = _parse_a_nullable_date(d.pop("a_nullable_date")) + + def _parse_required_nullable(data: object) -> Union[None, str]: + if data is None: + return data + return cast(Union[None, str], data) + + required_nullable = _parse_required_nullable(d.pop("required_nullable")) + required_not_nullable = d.pop("required_not_nullable") def _parse_one_of_models(data: object) -> Union["FreeFormModel", "ModelWithUnionProperty", Any]: @@ -279,8 +312,46 @@ def _parse_one_of_models(data: object) -> Union["FreeFormModel", "ModelWithUnion one_of_models = _parse_one_of_models(d.pop("one_of_models")) + def _parse_nullable_one_of_models(data: object) -> Union["FreeFormModel", "ModelWithUnionProperty", None]: + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + nullable_one_of_models_type_0 = FreeFormModel.from_dict(data) + + return nullable_one_of_models_type_0 + except: # noqa: E722 + pass + try: + if not isinstance(data, dict): + raise TypeError() + nullable_one_of_models_type_1 = ModelWithUnionProperty.from_dict(data) + + return nullable_one_of_models_type_1 + except: # noqa: E722 + pass + return cast(Union["FreeFormModel", "ModelWithUnionProperty", None], data) + + nullable_one_of_models = _parse_nullable_one_of_models(d.pop("nullable_one_of_models")) + model = ModelWithUnionProperty.from_dict(d.pop("model")) + def _parse_nullable_model(data: object) -> Union["ModelWithUnionProperty", None]: + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + nullable_model_type_1 = ModelWithUnionProperty.from_dict(data) + + return nullable_model_type_1 + except: # noqa: E722 + pass + return cast(Union["ModelWithUnionProperty", None], data) + + nullable_model = _parse_nullable_model(d.pop("nullable_model")) + any_value = d.pop("any_value", UNSET) _an_optional_allof_enum = d.pop("an_optional_allof_enum", UNSET) @@ -302,13 +373,6 @@ def _parse_one_of_models(data: object) -> Union["FreeFormModel", "ModelWithUnion nested_list_of_enums.append(nested_list_of_enums_item) - _a_nullable_date = d.pop("a_nullable_date") - a_nullable_date: Optional[datetime.date] - if _a_nullable_date is None: - a_nullable_date = None - else: - a_nullable_date = isoparse(_a_nullable_date).date() - _a_not_required_date = d.pop("a_not_required_date", UNSET) a_not_required_date: Union[Unset, datetime.date] if isinstance(_a_not_required_date, Unset): @@ -320,30 +384,16 @@ def _parse_one_of_models(data: object) -> Union["FreeFormModel", "ModelWithUnion attr_leading_underscore = d.pop("_leading_underscore", UNSET) - required_nullable = d.pop("required_nullable") - - not_required_nullable = d.pop("not_required_nullable", UNSET) - - not_required_not_nullable = d.pop("not_required_not_nullable", UNSET) - - def _parse_nullable_one_of_models(data: object) -> Union["FreeFormModel", "ModelWithUnionProperty", None]: + def _parse_not_required_nullable(data: object) -> Union[None, Unset, str]: if data is None: return data - try: - if not isinstance(data, dict): - raise TypeError() - nullable_one_of_models_type_0 = FreeFormModel.from_dict(data) - - return nullable_one_of_models_type_0 - except: # noqa: E722 - pass - if not isinstance(data, dict): - raise TypeError() - nullable_one_of_models_type_1 = ModelWithUnionProperty.from_dict(data) + if isinstance(data, Unset): + return data + return cast(Union[None, Unset, str], data) - return nullable_one_of_models_type_1 + not_required_nullable = _parse_not_required_nullable(d.pop("not_required_nullable", UNSET)) - nullable_one_of_models = _parse_nullable_one_of_models(d.pop("nullable_one_of_models")) + not_required_not_nullable = d.pop("not_required_not_nullable", UNSET) def _parse_not_required_one_of_models(data: object) -> Union["FreeFormModel", "ModelWithUnionProperty", Unset]: if isinstance(data, Unset): @@ -417,13 +467,6 @@ def _parse_not_required_nullable_one_of_models( d.pop("not_required_nullable_one_of_models", UNSET) ) - _nullable_model = d.pop("nullable_model") - nullable_model: Optional[ModelWithUnionProperty] - if _nullable_model is None: - nullable_model = None - else: - nullable_model = ModelWithUnionProperty.from_dict(_nullable_model) - _not_required_model = d.pop("not_required_model", UNSET) not_required_model: Union[Unset, ModelWithUnionProperty] if isinstance(_not_required_model, Unset): @@ -431,37 +474,52 @@ def _parse_not_required_nullable_one_of_models( else: not_required_model = ModelWithUnionProperty.from_dict(_not_required_model) - _not_required_nullable_model = d.pop("not_required_nullable_model", UNSET) - not_required_nullable_model: Union[Unset, None, ModelWithUnionProperty] - if _not_required_nullable_model is None: - not_required_nullable_model = None - elif isinstance(_not_required_nullable_model, Unset): - not_required_nullable_model = UNSET - else: - not_required_nullable_model = ModelWithUnionProperty.from_dict(_not_required_nullable_model) + def _parse_not_required_nullable_model(data: object) -> Union["ModelWithUnionProperty", None, Unset]: + if data is None: + return data + if isinstance(data, Unset): + return data + try: + if not isinstance(data, dict): + raise TypeError() + _not_required_nullable_model_type_1 = data + not_required_nullable_model_type_1: Union[Unset, ModelWithUnionProperty] + if isinstance(_not_required_nullable_model_type_1, Unset): + not_required_nullable_model_type_1 = UNSET + else: + not_required_nullable_model_type_1 = ModelWithUnionProperty.from_dict( + _not_required_nullable_model_type_1 + ) + + return not_required_nullable_model_type_1 + except: # noqa: E722 + pass + return cast(Union["ModelWithUnionProperty", None, Unset], data) + + not_required_nullable_model = _parse_not_required_nullable_model(d.pop("not_required_nullable_model", UNSET)) a_model = cls( an_enum_value=an_enum_value, an_allof_enum_with_overridden_default=an_allof_enum_with_overridden_default, a_camel_date_time=a_camel_date_time, a_date=a_date, + a_nullable_date=a_nullable_date, + required_nullable=required_nullable, required_not_nullable=required_not_nullable, one_of_models=one_of_models, + nullable_one_of_models=nullable_one_of_models, model=model, + nullable_model=nullable_model, any_value=any_value, an_optional_allof_enum=an_optional_allof_enum, nested_list_of_enums=nested_list_of_enums, - a_nullable_date=a_nullable_date, a_not_required_date=a_not_required_date, attr_1_leading_digit=attr_1_leading_digit, attr_leading_underscore=attr_leading_underscore, - required_nullable=required_nullable, not_required_nullable=not_required_nullable, not_required_not_nullable=not_required_not_nullable, - nullable_one_of_models=nullable_one_of_models, not_required_one_of_models=not_required_one_of_models, not_required_nullable_one_of_models=not_required_nullable_one_of_models, - nullable_model=nullable_model, not_required_model=not_required_model, not_required_nullable_model=not_required_nullable_model, ) diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/a_model_with_properties_reference_that_are_not_object.py b/end_to_end_tests/golden-record/my_test_api_client/models/a_model_with_properties_reference_that_are_not_object.py index 5dd1c1d9b..88ffd349f 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/a_model_with_properties_reference_that_are_not_object.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/a_model_with_properties_reference_that_are_not_object.py @@ -84,7 +84,6 @@ def to_dict(self) -> Dict[str, Any]: enum_properties_ref = [] for componentsschemas_an_other_array_of_enum_item_data in self.enum_properties_ref: componentsschemas_an_other_array_of_enum_item = componentsschemas_an_other_array_of_enum_item_data.value - enum_properties_ref.append(componentsschemas_an_other_array_of_enum_item) str_properties_ref = self.str_properties_ref @@ -101,7 +100,6 @@ def to_dict(self) -> Dict[str, Any]: componentsschemas_an_other_array_of_date_time_item = ( componentsschemas_an_other_array_of_date_time_item_data.isoformat() ) - datetime_properties_ref.append(componentsschemas_an_other_array_of_date_time_item) int32_properties_ref = self.int32_properties_ref @@ -125,7 +123,6 @@ def to_dict(self) -> Dict[str, Any]: enum_properties = [] for componentsschemas_an_array_of_enum_item_data in self.enum_properties: componentsschemas_an_array_of_enum_item = componentsschemas_an_array_of_enum_item_data.value - enum_properties.append(componentsschemas_an_array_of_enum_item) str_properties = self.str_properties @@ -138,7 +135,6 @@ def to_dict(self) -> Dict[str, Any]: datetime_properties = [] for componentsschemas_an_array_of_date_time_item_data in self.datetime_properties: componentsschemas_an_array_of_date_time_item = componentsschemas_an_array_of_date_time_item_data.isoformat() - datetime_properties.append(componentsschemas_an_array_of_date_time_item) int32_properties = self.int32_properties @@ -160,13 +156,19 @@ def to_dict(self) -> Dict[str, Any]: enum_property_ref = self.enum_property_ref.value str_property_ref = self.str_property_ref + date_property_ref = self.date_property_ref.isoformat() + datetime_property_ref = self.datetime_property_ref.isoformat() int32_property_ref = self.int32_property_ref + int64_property_ref = self.int64_property_ref + float_property_ref = self.float_property_ref + double_property_ref = self.double_property_ref + file_property_ref = self.file_property_ref.to_tuple() bytestream_property_ref = self.bytestream_property_ref diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/all_of_has_properties_but_no_type.py b/end_to_end_tests/golden-record/my_test_api_client/models/all_of_has_properties_but_no_type.py index 2fb61da98..245a1b04a 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/all_of_has_properties_but_no_type.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/all_of_has_properties_but_no_type.py @@ -25,7 +25,9 @@ class AllOfHasPropertiesButNoType: def to_dict(self) -> Dict[str, Any]: a_sub_property = self.a_sub_property + type = self.type + type_enum: Union[Unset, int] = UNSET if not isinstance(self.type_enum, Unset): type_enum = self.type_enum.value diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/all_of_sub_model.py b/end_to_end_tests/golden-record/my_test_api_client/models/all_of_sub_model.py index f7e8dc4c2..550b9b9c4 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/all_of_sub_model.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/all_of_sub_model.py @@ -25,7 +25,9 @@ class AllOfSubModel: def to_dict(self) -> Dict[str, Any]: a_sub_property = self.a_sub_property + type = self.type + type_enum: Union[Unset, int] = UNSET if not isinstance(self.type_enum, Unset): type_enum = self.type_enum.value diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_a_item.py b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_a_item.py index 90a7c75a2..b7792fefc 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_a_item.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_a_item.py @@ -30,7 +30,6 @@ def to_dict(self) -> Dict[str, Any]: componentsschemas_an_array_with_a_circular_ref_in_items_object_b_item = ( componentsschemas_an_array_with_a_circular_ref_in_items_object_b_item_data.to_dict() ) - circular.append(componentsschemas_an_array_with_a_circular_ref_in_items_object_b_item) field_dict: Dict[str, Any] = {} diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_additional_properties_a_item.py b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_additional_properties_a_item.py index 80118f3ac..c90579e7e 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_additional_properties_a_item.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_additional_properties_a_item.py @@ -28,7 +28,6 @@ def to_dict(self) -> Dict[str, Any]: componentsschemas_an_array_with_a_circular_ref_in_items_object_additional_properties_b_item_data ) in prop: componentsschemas_an_array_with_a_circular_ref_in_items_object_additional_properties_b_item = componentsschemas_an_array_with_a_circular_ref_in_items_object_additional_properties_b_item_data.to_dict() - field_dict[prop_name].append( componentsschemas_an_array_with_a_circular_ref_in_items_object_additional_properties_b_item ) diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_additional_properties_b_item.py b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_additional_properties_b_item.py index 08855eb6e..732e8ea4c 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_additional_properties_b_item.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_additional_properties_b_item.py @@ -28,7 +28,6 @@ def to_dict(self) -> Dict[str, Any]: componentsschemas_an_array_with_a_circular_ref_in_items_object_additional_properties_a_item_data ) in prop: componentsschemas_an_array_with_a_circular_ref_in_items_object_additional_properties_a_item = componentsschemas_an_array_with_a_circular_ref_in_items_object_additional_properties_a_item_data.to_dict() - field_dict[prop_name].append( componentsschemas_an_array_with_a_circular_ref_in_items_object_additional_properties_a_item ) diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_b_item.py b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_b_item.py index c1fb4a307..622d5d999 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_b_item.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_circular_ref_in_items_object_b_item.py @@ -30,7 +30,6 @@ def to_dict(self) -> Dict[str, Any]: componentsschemas_an_array_with_a_circular_ref_in_items_object_a_item = ( componentsschemas_an_array_with_a_circular_ref_in_items_object_a_item_data.to_dict() ) - circular.append(componentsschemas_an_array_with_a_circular_ref_in_items_object_a_item) field_dict: Dict[str, Any] = {} diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_recursive_ref_in_items_object_additional_properties_item.py b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_recursive_ref_in_items_object_additional_properties_item.py index 4ac20dd35..bd0472e21 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_recursive_ref_in_items_object_additional_properties_item.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_recursive_ref_in_items_object_additional_properties_item.py @@ -20,7 +20,6 @@ def to_dict(self) -> Dict[str, Any]: field_dict[prop_name] = [] for componentsschemas_an_array_with_a_recursive_ref_in_items_object_additional_properties_item_data in prop: componentsschemas_an_array_with_a_recursive_ref_in_items_object_additional_properties_item = componentsschemas_an_array_with_a_recursive_ref_in_items_object_additional_properties_item_data.to_dict() - field_dict[prop_name].append( componentsschemas_an_array_with_a_recursive_ref_in_items_object_additional_properties_item ) diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_recursive_ref_in_items_object_item.py b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_recursive_ref_in_items_object_item.py index f0ba27860..6b12b9b5d 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_recursive_ref_in_items_object_item.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/an_array_with_a_recursive_ref_in_items_object_item.py @@ -26,7 +26,6 @@ def to_dict(self) -> Dict[str, Any]: componentsschemas_an_array_with_a_recursive_ref_in_items_object_item = ( componentsschemas_an_array_with_a_recursive_ref_in_items_object_item_data.to_dict() ) - recursive.append(componentsschemas_an_array_with_a_recursive_ref_in_items_object_item) field_dict: Dict[str, Any] = {} diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/another_all_of_sub_model.py b/end_to_end_tests/golden-record/my_test_api_client/models/another_all_of_sub_model.py index 73d7cbb94..fde2bb6f8 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/another_all_of_sub_model.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/another_all_of_sub_model.py @@ -26,6 +26,7 @@ class AnotherAllOfSubModel: def to_dict(self) -> Dict[str, Any]: another_sub_property = self.another_sub_property + type: Union[Unset, str] = UNSET if not isinstance(self.type, Unset): type = self.type.value diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/body_upload_file_tests_upload_post.py b/end_to_end_tests/golden-record/my_test_api_client/models/body_upload_file_tests_upload_post.py index 5217c4929..bdd28ab40 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/body_upload_file_tests_upload_post.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/body_upload_file_tests_upload_post.py @@ -1,7 +1,7 @@ import datetime import json from io import BytesIO -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, TypeVar, Union, cast +from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Type, TypeVar, Union, cast from attrs import define as _attrs_define from attrs import field as _attrs_field @@ -32,6 +32,7 @@ class BodyUploadFileTestsUploadPost: Attributes: some_file (File): some_object (BodyUploadFileTestsUploadPostSomeObject): + some_nullable_object (Union['BodyUploadFileTestsUploadPostSomeNullableObject', None]): some_optional_file (Union[Unset, File]): some_string (Union[Unset, str]): Default: 'some_default_string'. a_datetime (Union[Unset, datetime.datetime]): @@ -39,13 +40,12 @@ class BodyUploadFileTestsUploadPost: some_number (Union[Unset, float]): some_array (Union[Unset, List[float]]): some_optional_object (Union[Unset, BodyUploadFileTestsUploadPostSomeOptionalObject]): - some_nullable_object (Optional[BodyUploadFileTestsUploadPostSomeNullableObject]): some_enum (Union[Unset, DifferentEnum]): An enumeration. """ some_file: File some_object: "BodyUploadFileTestsUploadPostSomeObject" - some_nullable_object: Optional["BodyUploadFileTestsUploadPostSomeNullableObject"] + some_nullable_object: Union["BodyUploadFileTestsUploadPostSomeNullableObject", None] some_optional_file: Union[Unset, File] = UNSET some_string: Union[Unset, str] = "some_default_string" a_datetime: Union[Unset, datetime.datetime] = UNSET @@ -59,15 +59,26 @@ class BodyUploadFileTestsUploadPost: ) def to_dict(self) -> Dict[str, Any]: + from ..models.body_upload_file_tests_upload_post_some_nullable_object import ( + BodyUploadFileTestsUploadPostSomeNullableObject, + ) + some_file = self.some_file.to_tuple() some_object = self.some_object.to_dict() + some_nullable_object: Union[Dict[str, Any], None] + if isinstance(self.some_nullable_object, BodyUploadFileTestsUploadPostSomeNullableObject): + some_nullable_object = self.some_nullable_object.to_dict() + else: + some_nullable_object = self.some_nullable_object + some_optional_file: Union[Unset, FileJsonType] = UNSET if not isinstance(self.some_optional_file, Unset): some_optional_file = self.some_optional_file.to_tuple() some_string = self.some_string + a_datetime: Union[Unset, str] = UNSET if not isinstance(self.a_datetime, Unset): a_datetime = self.a_datetime.isoformat() @@ -77,6 +88,7 @@ def to_dict(self) -> Dict[str, Any]: a_date = self.a_date.isoformat() some_number = self.some_number + some_array: Union[Unset, List[float]] = UNSET if not isinstance(self.some_array, Unset): some_array = self.some_array @@ -85,8 +97,6 @@ def to_dict(self) -> Dict[str, Any]: if not isinstance(self.some_optional_object, Unset): some_optional_object = self.some_optional_object.to_dict() - some_nullable_object = self.some_nullable_object.to_dict() if self.some_nullable_object else None - some_enum: Union[Unset, str] = UNSET if not isinstance(self.some_enum, Unset): some_enum = self.some_enum.value @@ -94,7 +104,6 @@ def to_dict(self) -> Dict[str, Any]: field_dict: Dict[str, Any] = {} for prop_name, prop in self.additional_properties.items(): field_dict[prop_name] = prop.to_dict() - field_dict.update( { "some_file": some_file, @@ -126,6 +135,12 @@ def to_multipart(self) -> Dict[str, Any]: some_object = (None, json.dumps(self.some_object.to_dict()).encode(), "application/json") + some_nullable_object: Union[None, Tuple[None, bytes, str]] + if isinstance(self.some_nullable_object, BodyUploadFileTestsUploadPostSomeNullableObject): + some_nullable_object = (None, json.dumps(self.some_nullable_object.to_dict()).encode(), "application/json") + else: + some_nullable_object = self.some_nullable_object + some_optional_file: Union[Unset, FileJsonType] = UNSET if not isinstance(self.some_optional_file, Unset): some_optional_file = self.some_optional_file.to_tuple() @@ -135,6 +150,7 @@ def to_multipart(self) -> Dict[str, Any]: if isinstance(self.some_string, Unset) else (None, str(self.some_string).encode(), "text/plain") ) + a_datetime: Union[Unset, bytes] = UNSET if not isinstance(self.a_datetime, Unset): a_datetime = self.a_datetime.isoformat().encode() @@ -148,6 +164,7 @@ def to_multipart(self) -> Dict[str, Any]: if isinstance(self.some_number, Unset) else (None, str(self.some_number).encode(), "text/plain") ) + some_array: Union[Unset, Tuple[None, bytes, str]] = UNSET if not isinstance(self.some_array, Unset): _temp_some_array = self.some_array @@ -157,12 +174,6 @@ def to_multipart(self) -> Dict[str, Any]: if not isinstance(self.some_optional_object, Unset): some_optional_object = (None, json.dumps(self.some_optional_object.to_dict()).encode(), "application/json") - some_nullable_object = ( - (None, json.dumps(self.some_nullable_object.to_dict()).encode(), "application/json") - if self.some_nullable_object - else None - ) - some_enum: Union[Unset, Tuple[None, bytes, str]] = UNSET if not isinstance(self.some_enum, Unset): some_enum = (None, str(self.some_enum.value).encode(), "text/plain") @@ -170,7 +181,6 @@ def to_multipart(self) -> Dict[str, Any]: field_dict: Dict[str, Any] = {} for prop_name, prop in self.additional_properties.items(): field_dict[prop_name] = (None, json.dumps(prop.to_dict()).encode(), "application/json") - field_dict.update( { "some_file": some_file, @@ -215,6 +225,21 @@ def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: some_object = BodyUploadFileTestsUploadPostSomeObject.from_dict(d.pop("some_object")) + def _parse_some_nullable_object(data: object) -> Union["BodyUploadFileTestsUploadPostSomeNullableObject", None]: + if data is None: + return data + try: + if not isinstance(data, dict): + raise TypeError() + some_nullable_object_type_0 = BodyUploadFileTestsUploadPostSomeNullableObject.from_dict(data) + + return some_nullable_object_type_0 + except: # noqa: E722 + pass + return cast(Union["BodyUploadFileTestsUploadPostSomeNullableObject", None], data) + + some_nullable_object = _parse_some_nullable_object(d.pop("some_nullable_object")) + _some_optional_file = d.pop("some_optional_file", UNSET) some_optional_file: Union[Unset, File] if isinstance(_some_optional_file, Unset): @@ -249,13 +274,6 @@ def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: else: some_optional_object = BodyUploadFileTestsUploadPostSomeOptionalObject.from_dict(_some_optional_object) - _some_nullable_object = d.pop("some_nullable_object") - some_nullable_object: Optional[BodyUploadFileTestsUploadPostSomeNullableObject] - if _some_nullable_object is None: - some_nullable_object = None - else: - some_nullable_object = BodyUploadFileTestsUploadPostSomeNullableObject.from_dict(_some_nullable_object) - _some_enum = d.pop("some_enum", UNSET) some_enum: Union[Unset, DifferentEnum] if isinstance(_some_enum, Unset): @@ -266,6 +284,7 @@ def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: body_upload_file_tests_upload_post = cls( some_file=some_file, some_object=some_object, + some_nullable_object=some_nullable_object, some_optional_file=some_optional_file, some_string=some_string, a_datetime=a_datetime, @@ -273,7 +292,6 @@ def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: some_number=some_number, some_array=some_array, some_optional_object=some_optional_object, - some_nullable_object=some_nullable_object, some_enum=some_enum, ) diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/body_upload_file_tests_upload_post_some_object.py b/end_to_end_tests/golden-record/my_test_api_client/models/body_upload_file_tests_upload_post_some_object.py index c59c287c9..25c2c0a6a 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/body_upload_file_tests_upload_post_some_object.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/body_upload_file_tests_upload_post_some_object.py @@ -20,6 +20,7 @@ class BodyUploadFileTestsUploadPostSomeObject: def to_dict(self) -> Dict[str, Any]: num = self.num + text = self.text field_dict: Dict[str, Any] = {} diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/http_validation_error.py b/end_to_end_tests/golden-record/my_test_api_client/models/http_validation_error.py index e89e3d212..1f04c29d0 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/http_validation_error.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/http_validation_error.py @@ -26,7 +26,6 @@ def to_dict(self) -> Dict[str, Any]: detail = [] for detail_item_data in self.detail: detail_item = detail_item_data.to_dict() - detail.append(detail_item) field_dict: Dict[str, Any] = {} diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/model_from_all_of.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_from_all_of.py index d03595a4b..6414b790d 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/model_from_all_of.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/model_from_all_of.py @@ -28,6 +28,7 @@ class ModelFromAllOf: def to_dict(self) -> Dict[str, Any]: a_sub_property = self.a_sub_property + type: Union[Unset, str] = UNSET if not isinstance(self.type, Unset): type = self.type.value diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_additional_properties_inlined.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_additional_properties_inlined.py index 048856548..761a43e54 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_additional_properties_inlined.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_additional_properties_inlined.py @@ -32,7 +32,6 @@ def to_dict(self) -> Dict[str, Any]: field_dict: Dict[str, Any] = {} for prop_name, prop in self.additional_properties.items(): field_dict[prop_name] = prop.to_dict() - field_dict.update({}) if a_number is not UNSET: field_dict["a_number"] = a_number diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_additional_properties_refed.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_additional_properties_refed.py index 181829a2c..4605b8801 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_additional_properties_refed.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_additional_properties_refed.py @@ -18,7 +18,6 @@ def to_dict(self) -> Dict[str, Any]: field_dict: Dict[str, Any] = {} for prop_name, prop in self.additional_properties.items(): field_dict[prop_name] = prop.value - field_dict.update({}) return field_dict diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_any_json_properties.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_any_json_properties.py index d9c4561a4..49a66f7a5 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_any_json_properties.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_any_json_properties.py @@ -29,13 +29,11 @@ def to_dict(self) -> Dict[str, Any]: for prop_name, prop in self.additional_properties.items(): if isinstance(prop, ModelWithAnyJsonPropertiesAdditionalPropertyType0): field_dict[prop_name] = prop.to_dict() - elif isinstance(prop, list): field_dict[prop_name] = prop else: field_dict[prop_name] = prop - field_dict.update({}) return field_dict diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_circular_ref_in_additional_properties_a.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_circular_ref_in_additional_properties_a.py index 4ab44178f..9e3f6c12c 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_circular_ref_in_additional_properties_a.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_circular_ref_in_additional_properties_a.py @@ -22,7 +22,6 @@ def to_dict(self) -> Dict[str, Any]: field_dict: Dict[str, Any] = {} for prop_name, prop in self.additional_properties.items(): field_dict[prop_name] = prop.to_dict() - field_dict.update({}) return field_dict diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_circular_ref_in_additional_properties_b.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_circular_ref_in_additional_properties_b.py index d324cbe2b..5b4f0c268 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_circular_ref_in_additional_properties_b.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_circular_ref_in_additional_properties_b.py @@ -22,7 +22,6 @@ def to_dict(self) -> Dict[str, Any]: field_dict: Dict[str, Any] = {} for prop_name, prop in self.additional_properties.items(): field_dict[prop_name] = prop.to_dict() - field_dict.update({}) return field_dict diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_primitive_additional_properties_a_date_holder.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_primitive_additional_properties_a_date_holder.py index 20afb41d6..4693be0a1 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_primitive_additional_properties_a_date_holder.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_primitive_additional_properties_a_date_holder.py @@ -18,7 +18,6 @@ def to_dict(self) -> Dict[str, Any]: field_dict: Dict[str, Any] = {} for prop_name, prop in self.additional_properties.items(): field_dict[prop_name] = prop.isoformat() - field_dict.update({}) return field_dict diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_recursive_ref_in_additional_properties.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_recursive_ref_in_additional_properties.py index ebaca3f31..ea5b1211f 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_recursive_ref_in_additional_properties.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_recursive_ref_in_additional_properties.py @@ -18,7 +18,6 @@ def to_dict(self) -> Dict[str, Any]: field_dict: Dict[str, Any] = {} for prop_name, prop in self.additional_properties.items(): field_dict[prop_name] = prop.to_dict() - field_dict.update({}) return field_dict diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_union_property.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_union_property.py index fcaf135b1..916de9079 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_union_property.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_union_property.py @@ -22,7 +22,6 @@ def to_dict(self) -> Dict[str, Any]: a_property: Union[Unset, int, str] if isinstance(self.a_property, Unset): a_property = UNSET - elif isinstance(self.a_property, AnEnum): a_property = UNSET if not isinstance(self.a_property, Unset): diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_union_property_inlined.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_union_property_inlined.py index d5078ed0d..2ccfe5e1b 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/model_with_union_property_inlined.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_union_property_inlined.py @@ -27,12 +27,10 @@ def to_dict(self) -> Dict[str, Any]: fruit: Union[Dict[str, Any], Unset] if isinstance(self.fruit, Unset): fruit = UNSET - elif isinstance(self.fruit, ModelWithUnionPropertyInlinedFruitType0): fruit = UNSET if not isinstance(self.fruit, Unset): fruit = self.fruit.to_dict() - else: fruit = UNSET if not isinstance(self.fruit, Unset): diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/post_form_data_inline_data.py b/end_to_end_tests/golden-record/my_test_api_client/models/post_form_data_inline_data.py index 6ecd3055b..9e9007567 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/post_form_data_inline_data.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/post_form_data_inline_data.py @@ -22,6 +22,7 @@ class PostFormDataInlineData: def to_dict(self) -> Dict[str, Any]: a_required_field = self.a_required_field + an_optional_field = self.an_optional_field field_dict: Dict[str, Any] = {} diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/post_naming_property_conflict_with_import_json_body.py b/end_to_end_tests/golden-record/my_test_api_client/models/post_naming_property_conflict_with_import_json_body.py index fd4aa2de7..d6b280c6e 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/post_naming_property_conflict_with_import_json_body.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/post_naming_property_conflict_with_import_json_body.py @@ -22,6 +22,7 @@ class PostNamingPropertyConflictWithImportJsonBody: def to_dict(self) -> Dict[str, Any]: field = self.field + define = self.define field_dict: Dict[str, Any] = {} diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/post_naming_property_conflict_with_import_response_200.py b/end_to_end_tests/golden-record/my_test_api_client/models/post_naming_property_conflict_with_import_response_200.py index d90bb80c7..9bdd79a02 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/post_naming_property_conflict_with_import_response_200.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/post_naming_property_conflict_with_import_response_200.py @@ -22,6 +22,7 @@ class PostNamingPropertyConflictWithImportResponse200: def to_dict(self) -> Dict[str, Any]: field = self.field + define = self.define field_dict: Dict[str, Any] = {} diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/post_responses_unions_simple_before_complex_response_200.py b/end_to_end_tests/golden-record/my_test_api_client/models/post_responses_unions_simple_before_complex_response_200.py index 281906c31..0b6a29243 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/post_responses_unions_simple_before_complex_response_200.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/post_responses_unions_simple_before_complex_response_200.py @@ -28,10 +28,8 @@ def to_dict(self) -> Dict[str, Any]: ) a: Union[Dict[str, Any], str] - if isinstance(self.a, PostResponsesUnionsSimpleBeforeComplexResponse200AType1): a = self.a.to_dict() - else: a = self.a diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/validation_error.py b/end_to_end_tests/golden-record/my_test_api_client/models/validation_error.py index 290d84bbb..6ff5d4790 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/validation_error.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/validation_error.py @@ -22,6 +22,7 @@ def to_dict(self) -> Dict[str, Any]: loc = self.loc msg = self.msg + type = self.type field_dict: Dict[str, Any] = {} diff --git a/end_to_end_tests/regen_golden_record.py b/end_to_end_tests/regen_golden_record.py index 1d4dc943d..7391ed093 100644 --- a/end_to_end_tests/regen_golden_record.py +++ b/end_to_end_tests/regen_golden_record.py @@ -12,7 +12,7 @@ def regen_golden_record(): runner = CliRunner() - openapi_path = Path(__file__).parent / "openapi.json" + openapi_path = Path(__file__).parent / "baseline_openapi_3.0.json" gr_path = Path(__file__).parent / "golden-record" output_path = Path.cwd() / "my-test-api-client" @@ -21,7 +21,28 @@ def regen_golden_record(): shutil.rmtree(gr_path, ignore_errors=True) shutil.rmtree(output_path, ignore_errors=True) - result = runner.invoke(app, ["generate", f"--config={config_path}", f"--path={openapi_path}"]) + result = runner.invoke( + app, ["generate", f"--config={config_path}", f"--path={openapi_path}"] + ) + + if result.stdout: + print(result.stdout) + if result.exception: + raise result.exception + output_path.rename(gr_path) + + +def regen_golden_record_3_1_features(): + runner = CliRunner() + openapi_path = Path(__file__).parent / "3.1_specific.openapi.yaml" + + gr_path = Path(__file__).parent / "test-3-1-golden-record" + output_path = Path.cwd() / "test-3-1-features-client" + + shutil.rmtree(gr_path, ignore_errors=True) + shutil.rmtree(output_path, ignore_errors=True) + + result = runner.invoke(app, ["generate", f"--path={openapi_path}"]) if result.stdout: print(result.stdout) @@ -32,7 +53,7 @@ def regen_golden_record(): def regen_custom_template_golden_record(): runner = CliRunner() - openapi_path = Path(__file__).parent / "openapi.json" + openapi_path = Path(__file__).parent / "baseline_openapi_3.0.json" tpl_dir = Path(__file__).parent / "test_custom_templates" gr_path = Path(__file__).parent / "golden-record" @@ -45,7 +66,13 @@ def regen_custom_template_golden_record(): os.chdir(str(output_path.absolute())) result = runner.invoke( - app, ["generate", f"--config={config_path}", f"--path={openapi_path}", f"--custom-template-path={tpl_dir}"] + app, + [ + "generate", + f"--config={config_path}", + f"--path={openapi_path}", + f"--custom-template-path={tpl_dir}", + ], ) if result.stdout: @@ -76,4 +103,5 @@ def regen_custom_template_golden_record(): if __name__ == "__main__": regen_golden_record() + regen_golden_record_3_1_features() regen_custom_template_golden_record() diff --git a/end_to_end_tests/test-3-1-golden-record/.gitignore b/end_to_end_tests/test-3-1-golden-record/.gitignore new file mode 100644 index 000000000..79a2c3d73 --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/.gitignore @@ -0,0 +1,23 @@ +__pycache__/ +build/ +dist/ +*.egg-info/ +.pytest_cache/ + +# pyenv +.python-version + +# Environments +.env +.venv + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# JetBrains +.idea/ + +/coverage.xml +/.coverage diff --git a/end_to_end_tests/test-3-1-golden-record/README.md b/end_to_end_tests/test-3-1-golden-record/README.md new file mode 100644 index 000000000..dbe8a5c1e --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/README.md @@ -0,0 +1,124 @@ +# test-3-1-features-client +A client library for accessing Test 3.1 Features + +## Usage +First, create a client: + +```python +from test_3_1_features_client import Client + +client = Client(base_url="https://api.example.com") +``` + +If the endpoints you're going to hit require authentication, use `AuthenticatedClient` instead: + +```python +from test_3_1_features_client import AuthenticatedClient + +client = AuthenticatedClient(base_url="https://api.example.com", token="SuperSecretToken") +``` + +Now call your endpoint and use your models: + +```python +from test_3_1_features_client.models import MyDataModel +from test_3_1_features_client.api.my_tag import get_my_data_model +from test_3_1_features_client.types import Response + +with client as client: + my_data: MyDataModel = get_my_data_model.sync(client=client) + # or if you need more info (e.g. status_code) + response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client) +``` + +Or do the same thing with an async version: + +```python +from test_3_1_features_client.models import MyDataModel +from test_3_1_features_client.api.my_tag import get_my_data_model +from test_3_1_features_client.types import Response + +async with client as client: + my_data: MyDataModel = await get_my_data_model.asyncio(client=client) + response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client) +``` + +By default, when you're calling an HTTPS API it will attempt to verify that SSL is working correctly. Using certificate verification is highly recommended most of the time, but sometimes you may need to authenticate to a server (especially an internal server) using a custom certificate bundle. + +```python +client = AuthenticatedClient( + base_url="https://internal_api.example.com", + token="SuperSecretToken", + verify_ssl="/path/to/certificate_bundle.pem", +) +``` + +You can also disable certificate validation altogether, but beware that **this is a security risk**. + +```python +client = AuthenticatedClient( + base_url="https://internal_api.example.com", + token="SuperSecretToken", + verify_ssl=False +) +``` + +Things to know: +1. Every path/method combo becomes a Python module with four functions: + 1. `sync`: Blocking request that returns parsed data (if successful) or `None` + 1. `sync_detailed`: Blocking request that always returns a `Request`, optionally with `parsed` set if the request was successful. + 1. `asyncio`: Like `sync` but async instead of blocking + 1. `asyncio_detailed`: Like `sync_detailed` but async instead of blocking + +1. All path/query params, and bodies become method arguments. +1. If your endpoint had any tags on it, the first tag will be used as a module name for the function (my_tag above) +1. Any endpoint which did not have a tag will be in `test_3_1_features_client.api.default` + +## Advanced customizations + +There are more settings on the generated `Client` class which let you control more runtime behavior, check out the docstring on that class for more info. You can also customize the underlying `httpx.Client` or `httpx.AsyncClient` (depending on your use-case): + +```python +from test_3_1_features_client import Client + +def log_request(request): + print(f"Request event hook: {request.method} {request.url} - Waiting for response") + +def log_response(response): + request = response.request + print(f"Response event hook: {request.method} {request.url} - Status {response.status_code}") + +client = Client( + base_url="https://api.example.com", + httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}}, +) + +# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client() +``` + +You can even set the httpx client directly, but beware that this will override any existing settings (e.g., base_url): + +```python +import httpx +from test_3_1_features_client import Client + +client = Client( + base_url="https://api.example.com", +) +# Note that base_url needs to be re-set, as would any shared cookies, headers, etc. +client.set_httpx_client(httpx.Client(base_url="https://api.example.com", proxies="http://localhost:8030")) +``` + +## Building / publishing this package +This project uses [Poetry](https://python-poetry.org/) to manage dependencies and packaging. Here are the basics: +1. Update the metadata in pyproject.toml (e.g. authors, version) +1. If you're using a private repository, configure it with Poetry + 1. `poetry config repositories. ` + 1. `poetry config http-basic. ` +1. Publish the client with `poetry publish --build -r ` or, if for public PyPI, just `poetry publish --build` + +If you want to install this client into another project without publishing it (e.g. for development) then: +1. If that project **is using Poetry**, you can simply do `poetry add ` from that project +1. If that project is not using Poetry: + 1. Build a wheel with `poetry build -f wheel` + 1. Install that wheel from the other project `pip install ` diff --git a/end_to_end_tests/test-3-1-golden-record/pyproject.toml b/end_to_end_tests/test-3-1-golden-record/pyproject.toml new file mode 100644 index 000000000..2f9d177f0 --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/pyproject.toml @@ -0,0 +1,26 @@ +[tool.poetry] +name = "test-3-1-features-client" +version = "0.1.0" +description = "A client library for accessing Test 3.1 Features" + +authors = [] + +readme = "README.md" +packages = [ + {include = "test_3_1_features_client"}, +] +include = ["CHANGELOG.md", "test_3_1_features_client/py.typed"] + +[tool.poetry.dependencies] +python = "^3.8" +httpx = ">=0.20.0,<0.27.0" +attrs = ">=21.3.0" +python-dateutil = "^2.8.0" + +[build-system] +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api" + +[tool.ruff] +select = ["F", "I"] +line-length = 120 diff --git a/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/__init__.py b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/__init__.py new file mode 100644 index 000000000..e1b05febe --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/__init__.py @@ -0,0 +1,7 @@ +""" A client library for accessing Test 3.1 Features """ +from .client import AuthenticatedClient, Client + +__all__ = ( + "AuthenticatedClient", + "Client", +) diff --git a/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/__init__.py b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/__init__.py new file mode 100644 index 000000000..dc035f4ce --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/__init__.py @@ -0,0 +1 @@ +""" Contains methods for accessing the API """ diff --git a/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/const/__init__.py b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/const/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/const/post_const_path.py b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/const/post_const_path.py new file mode 100644 index 000000000..306968daf --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/const/post_const_path.py @@ -0,0 +1,197 @@ +from http import HTTPStatus +from typing import Any, Dict, Literal, Optional, Union, cast + +import httpx + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.post_const_path_json_body import PostConstPathJsonBody +from ...types import UNSET, Response, Unset + + +def _get_kwargs( + path: Literal["this goes in the path"], + *, + json_body: PostConstPathJsonBody, + required_query: Literal["this always goes in the query"], + optional_query: Union[Literal["this sometimes goes in the query"], Unset] = UNSET, +) -> Dict[str, Any]: + params: Dict[str, Any] = {} + + params["required query"] = required_query + + params["optional query"] = optional_query + + params = {k: v for k, v in params.items() if v is not UNSET and v is not None} + + json_json_body = json_body.to_dict() + + return { + "method": "post", + "url": "/const/{path}".format( + path=path, + ), + "json": json_json_body, + "params": params, + } + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[Literal["Why have a fixed response? I dunno"]]: + if response.status_code == HTTPStatus.OK: + response_200 = cast(Literal["Why have a fixed response? I dunno"], response.json()) + return response_200 + if client.raise_on_unexpected_status: + raise errors.UnexpectedStatus(response.status_code, response.content) + else: + return None + + +def _build_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Response[Literal["Why have a fixed response? I dunno"]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +def sync_detailed( + path: Literal["this goes in the path"], + *, + client: Union[AuthenticatedClient, Client], + json_body: PostConstPathJsonBody, + required_query: Literal["this always goes in the query"], + optional_query: Union[Literal["this sometimes goes in the query"], Unset] = UNSET, +) -> Response[Literal["Why have a fixed response? I dunno"]]: + """ + Args: + path (Literal['this goes in the path']): + required_query (Literal['this always goes in the query']): + optional_query (Union[Literal['this sometimes goes in the query'], Unset]): + json_body (PostConstPathJsonBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Literal['Why have a fixed response? I dunno']] + """ + + kwargs = _get_kwargs( + path=path, + json_body=json_body, + required_query=required_query, + optional_query=optional_query, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +def sync( + path: Literal["this goes in the path"], + *, + client: Union[AuthenticatedClient, Client], + json_body: PostConstPathJsonBody, + required_query: Literal["this always goes in the query"], + optional_query: Union[Literal["this sometimes goes in the query"], Unset] = UNSET, +) -> Optional[Literal["Why have a fixed response? I dunno"]]: + """ + Args: + path (Literal['this goes in the path']): + required_query (Literal['this always goes in the query']): + optional_query (Union[Literal['this sometimes goes in the query'], Unset]): + json_body (PostConstPathJsonBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Literal['Why have a fixed response? I dunno'] + """ + + return sync_detailed( + path=path, + client=client, + json_body=json_body, + required_query=required_query, + optional_query=optional_query, + ).parsed + + +async def asyncio_detailed( + path: Literal["this goes in the path"], + *, + client: Union[AuthenticatedClient, Client], + json_body: PostConstPathJsonBody, + required_query: Literal["this always goes in the query"], + optional_query: Union[Literal["this sometimes goes in the query"], Unset] = UNSET, +) -> Response[Literal["Why have a fixed response? I dunno"]]: + """ + Args: + path (Literal['this goes in the path']): + required_query (Literal['this always goes in the query']): + optional_query (Union[Literal['this sometimes goes in the query'], Unset]): + json_body (PostConstPathJsonBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Response[Literal['Why have a fixed response? I dunno']] + """ + + kwargs = _get_kwargs( + path=path, + json_body=json_body, + required_query=required_query, + optional_query=optional_query, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +async def asyncio( + path: Literal["this goes in the path"], + *, + client: Union[AuthenticatedClient, Client], + json_body: PostConstPathJsonBody, + required_query: Literal["this always goes in the query"], + optional_query: Union[Literal["this sometimes goes in the query"], Unset] = UNSET, +) -> Optional[Literal["Why have a fixed response? I dunno"]]: + """ + Args: + path (Literal['this goes in the path']): + required_query (Literal['this always goes in the query']): + optional_query (Union[Literal['this sometimes goes in the query'], Unset]): + json_body (PostConstPathJsonBody): + + Raises: + errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. + httpx.TimeoutException: If the request takes longer than Client.timeout. + + Returns: + Literal['Why have a fixed response? I dunno'] + """ + + return ( + await asyncio_detailed( + path=path, + client=client, + json_body=json_body, + required_query=required_query, + optional_query=optional_query, + ) + ).parsed diff --git a/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/client.py b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/client.py new file mode 100644 index 000000000..74b476ca8 --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/client.py @@ -0,0 +1,268 @@ +import ssl +from typing import Any, Dict, Optional, Union + +import httpx +from attrs import define, evolve, field + + +@define +class Client: + """A class for keeping track of data related to the API + + The following are accepted as keyword arguments and will be used to construct httpx Clients internally: + + ``base_url``: The base URL for the API, all requests are made to a relative path to this URL + + ``cookies``: A dictionary of cookies to be sent with every request + + ``headers``: A dictionary of headers to be sent with every request + + ``timeout``: The maximum amount of a time a request can take. API functions will raise + httpx.TimeoutException if this is exceeded. + + ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production, + but can be set to False for testing purposes. + + ``follow_redirects``: Whether or not to follow redirects. Default value is False. + + ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor. + + + Attributes: + raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a + status code that was not documented in the source OpenAPI document. Can also be provided as a keyword + argument to the constructor. + """ + + raise_on_unexpected_status: bool = field(default=False, kw_only=True) + _base_url: str + _cookies: Dict[str, str] = field(factory=dict, kw_only=True) + _headers: Dict[str, str] = field(factory=dict, kw_only=True) + _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True) + _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True) + _follow_redirects: bool = field(default=False, kw_only=True) + _httpx_args: Dict[str, Any] = field(factory=dict, kw_only=True) + _client: Optional[httpx.Client] = field(default=None, init=False) + _async_client: Optional[httpx.AsyncClient] = field(default=None, init=False) + + def with_headers(self, headers: Dict[str, str]) -> "Client": + """Get a new client matching this one with additional headers""" + if self._client is not None: + self._client.headers.update(headers) + if self._async_client is not None: + self._async_client.headers.update(headers) + return evolve(self, headers={**self._headers, **headers}) + + def with_cookies(self, cookies: Dict[str, str]) -> "Client": + """Get a new client matching this one with additional cookies""" + if self._client is not None: + self._client.cookies.update(cookies) + if self._async_client is not None: + self._async_client.cookies.update(cookies) + return evolve(self, cookies={**self._cookies, **cookies}) + + def with_timeout(self, timeout: httpx.Timeout) -> "Client": + """Get a new client matching this one with a new timeout (in seconds)""" + if self._client is not None: + self._client.timeout = timeout + if self._async_client is not None: + self._async_client.timeout = timeout + return evolve(self, timeout=timeout) + + def set_httpx_client(self, client: httpx.Client) -> "Client": + """Manually the underlying httpx.Client + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._client = client + return self + + def get_httpx_client(self) -> httpx.Client: + """Get the underlying httpx.Client, constructing a new one if not previously set""" + if self._client is None: + self._client = httpx.Client( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._client + + def __enter__(self) -> "Client": + """Enter a context manager for self.client—you cannot enter twice (see httpx docs)""" + self.get_httpx_client().__enter__() + return self + + def __exit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for internal httpx.Client (see httpx docs)""" + self.get_httpx_client().__exit__(*args, **kwargs) + + def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "Client": + """Manually the underlying httpx.AsyncClient + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._async_client = async_client + return self + + def get_async_httpx_client(self) -> httpx.AsyncClient: + """Get the underlying httpx.AsyncClient, constructing a new one if not previously set""" + if self._async_client is None: + self._async_client = httpx.AsyncClient( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._async_client + + async def __aenter__(self) -> "Client": + """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)""" + await self.get_async_httpx_client().__aenter__() + return self + + async def __aexit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)""" + await self.get_async_httpx_client().__aexit__(*args, **kwargs) + + +@define +class AuthenticatedClient: + """A Client which has been authenticated for use on secured endpoints + + The following are accepted as keyword arguments and will be used to construct httpx Clients internally: + + ``base_url``: The base URL for the API, all requests are made to a relative path to this URL + + ``cookies``: A dictionary of cookies to be sent with every request + + ``headers``: A dictionary of headers to be sent with every request + + ``timeout``: The maximum amount of a time a request can take. API functions will raise + httpx.TimeoutException if this is exceeded. + + ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production, + but can be set to False for testing purposes. + + ``follow_redirects``: Whether or not to follow redirects. Default value is False. + + ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor. + + + Attributes: + raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a + status code that was not documented in the source OpenAPI document. Can also be provided as a keyword + argument to the constructor. + token: The token to use for authentication + prefix: The prefix to use for the Authorization header + auth_header_name: The name of the Authorization header + """ + + raise_on_unexpected_status: bool = field(default=False, kw_only=True) + _base_url: str + _cookies: Dict[str, str] = field(factory=dict, kw_only=True) + _headers: Dict[str, str] = field(factory=dict, kw_only=True) + _timeout: Optional[httpx.Timeout] = field(default=None, kw_only=True) + _verify_ssl: Union[str, bool, ssl.SSLContext] = field(default=True, kw_only=True) + _follow_redirects: bool = field(default=False, kw_only=True) + _httpx_args: Dict[str, Any] = field(factory=dict, kw_only=True) + _client: Optional[httpx.Client] = field(default=None, init=False) + _async_client: Optional[httpx.AsyncClient] = field(default=None, init=False) + + token: str + prefix: str = "Bearer" + auth_header_name: str = "Authorization" + + def with_headers(self, headers: Dict[str, str]) -> "AuthenticatedClient": + """Get a new client matching this one with additional headers""" + if self._client is not None: + self._client.headers.update(headers) + if self._async_client is not None: + self._async_client.headers.update(headers) + return evolve(self, headers={**self._headers, **headers}) + + def with_cookies(self, cookies: Dict[str, str]) -> "AuthenticatedClient": + """Get a new client matching this one with additional cookies""" + if self._client is not None: + self._client.cookies.update(cookies) + if self._async_client is not None: + self._async_client.cookies.update(cookies) + return evolve(self, cookies={**self._cookies, **cookies}) + + def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient": + """Get a new client matching this one with a new timeout (in seconds)""" + if self._client is not None: + self._client.timeout = timeout + if self._async_client is not None: + self._async_client.timeout = timeout + return evolve(self, timeout=timeout) + + def set_httpx_client(self, client: httpx.Client) -> "AuthenticatedClient": + """Manually the underlying httpx.Client + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._client = client + return self + + def get_httpx_client(self) -> httpx.Client: + """Get the underlying httpx.Client, constructing a new one if not previously set""" + if self._client is None: + self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token + self._client = httpx.Client( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._client + + def __enter__(self) -> "AuthenticatedClient": + """Enter a context manager for self.client—you cannot enter twice (see httpx docs)""" + self.get_httpx_client().__enter__() + return self + + def __exit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for internal httpx.Client (see httpx docs)""" + self.get_httpx_client().__exit__(*args, **kwargs) + + def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> "AuthenticatedClient": + """Manually the underlying httpx.AsyncClient + + **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout. + """ + self._async_client = async_client + return self + + def get_async_httpx_client(self) -> httpx.AsyncClient: + """Get the underlying httpx.AsyncClient, constructing a new one if not previously set""" + if self._async_client is None: + self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token + self._async_client = httpx.AsyncClient( + base_url=self._base_url, + cookies=self._cookies, + headers=self._headers, + timeout=self._timeout, + verify=self._verify_ssl, + follow_redirects=self._follow_redirects, + **self._httpx_args, + ) + return self._async_client + + async def __aenter__(self) -> "AuthenticatedClient": + """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)""" + await self.get_async_httpx_client().__aenter__() + return self + + async def __aexit__(self, *args: Any, **kwargs: Any) -> None: + """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)""" + await self.get_async_httpx_client().__aexit__(*args, **kwargs) diff --git a/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/errors.py b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/errors.py new file mode 100644 index 000000000..426f8a2ed --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/errors.py @@ -0,0 +1,14 @@ +""" Contains shared errors types that can be raised from API functions """ + + +class UnexpectedStatus(Exception): + """Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True""" + + def __init__(self, status_code: int, content: bytes): + self.status_code = status_code + self.content = content + + super().__init__(f"Unexpected status code: {status_code}") + + +__all__ = ["UnexpectedStatus"] diff --git a/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/models/__init__.py b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/models/__init__.py new file mode 100644 index 000000000..da482ad8b --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/models/__init__.py @@ -0,0 +1,5 @@ +""" Contains all the data models used in inputs/outputs """ + +from .post_const_path_json_body import PostConstPathJsonBody + +__all__ = ("PostConstPathJsonBody",) diff --git a/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/models/post_const_path_json_body.py b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/models/post_const_path_json_body.py new file mode 100644 index 000000000..e7cfcf3a8 --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/models/post_const_path_json_body.py @@ -0,0 +1,83 @@ +from typing import Any, Dict, List, Literal, Type, TypeVar, Union, cast + +from attrs import define as _attrs_define +from attrs import field as _attrs_field + +from ..types import UNSET, Unset + +T = TypeVar("T", bound="PostConstPathJsonBody") + + +@_attrs_define +class PostConstPathJsonBody: + """ + Attributes: + required (Literal['this always goes in the body']): + nullable (Union[Literal['this or null goes in the body'], None]): + optional (Union[Literal['this sometimes goes in the body'], Unset]): + """ + + required: Literal["this always goes in the body"] + nullable: Union[Literal["this or null goes in the body"], None] + optional: Union[Literal["this sometimes goes in the body"], Unset] = UNSET + additional_properties: Dict[str, Any] = _attrs_field(init=False, factory=dict) + + def to_dict(self) -> Dict[str, Any]: + required = self.required + + nullable: Union[Literal["this or null goes in the body"], None] + nullable = self.nullable + + optional = self.optional + + field_dict: Dict[str, Any] = {} + field_dict.update(self.additional_properties) + field_dict.update( + { + "required": required, + "nullable": nullable, + } + ) + if optional is not UNSET: + field_dict["optional"] = optional + + return field_dict + + @classmethod + def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T: + d = src_dict.copy() + required = d.pop("required") + + def _parse_nullable(data: object) -> Union[Literal["this or null goes in the body"], None]: + if data is None: + return data + return cast(Union[Literal["this or null goes in the body"], None], data) + + nullable = _parse_nullable(d.pop("nullable")) + + optional = d.pop("optional", UNSET) + + post_const_path_json_body = cls( + required=required, + nullable=nullable, + optional=optional, + ) + + post_const_path_json_body.additional_properties = d + return post_const_path_json_body + + @property + def additional_keys(self) -> List[str]: + return list(self.additional_properties.keys()) + + def __getitem__(self, key: str) -> Any: + return self.additional_properties[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.additional_properties[key] = value + + def __delitem__(self, key: str) -> None: + del self.additional_properties[key] + + def __contains__(self, key: str) -> bool: + return key in self.additional_properties diff --git a/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/py.typed b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/py.typed new file mode 100644 index 000000000..1aad32711 --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561 \ No newline at end of file diff --git a/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/types.py b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/types.py new file mode 100644 index 000000000..15700b858 --- /dev/null +++ b/end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/types.py @@ -0,0 +1,44 @@ +""" Contains some shared types for properties """ +from http import HTTPStatus +from typing import BinaryIO, Generic, Literal, MutableMapping, Optional, Tuple, TypeVar + +from attrs import define + + +class Unset: + def __bool__(self) -> Literal[False]: + return False + + +UNSET: Unset = Unset() + +FileJsonType = Tuple[Optional[str], BinaryIO, Optional[str]] + + +@define +class File: + """Contains information for file uploads""" + + payload: BinaryIO + file_name: Optional[str] = None + mime_type: Optional[str] = None + + def to_tuple(self) -> FileJsonType: + """Return a tuple representation that httpx will accept for multipart/form-data""" + return self.file_name, self.payload, self.mime_type + + +T = TypeVar("T") + + +@define +class Response(Generic[T]): + """A response from an endpoint""" + + status_code: HTTPStatus + content: bytes + headers: MutableMapping[str, str] + parsed: Optional[T] + + +__all__ = ["File", "Response", "FileJsonType"] diff --git a/end_to_end_tests/test_end_to_end.py b/end_to_end_tests/test_end_to_end.py index b6d614cf0..084a10068 100644 --- a/end_to_end_tests/test_end_to_end.py +++ b/end_to_end_tests/test_end_to_end.py @@ -29,10 +29,15 @@ def _compare_directories( dc = dircmp(record, test_subject, ignore=[".ruff_cache"]) missing_files = dc.left_only + dc.right_only if missing_files: - pytest.fail(f"{first_printable} or {second_printable} was missing: {missing_files}", pytrace=False) + pytest.fail( + f"{first_printable} or {second_printable} was missing: {missing_files}", + pytrace=False, + ) expected_differences = expected_differences or {} - _, mismatches, errors = cmpfiles(record, test_subject, dc.common_files, shallow=False) + _, mismatches, errors = cmpfiles( + record, test_subject, dc.common_files, shallow=False + ) mismatches = set(mismatches) for file_name in mismatches: @@ -45,24 +50,40 @@ def _compare_directories( expected_content = (record / file_name).read_text() generated_content = (test_subject / file_name).read_text() - assert generated_content == expected_content, f"Unexpected output in {mismatch_file_path}" + assert ( + generated_content == expected_content + ), f"Unexpected output in {mismatch_file_path}" for sub_path in dc.common_dirs: _compare_directories( - record / sub_path, test_subject / sub_path, expected_differences=expected_differences, depth=depth + 1 + record / sub_path, + test_subject / sub_path, + expected_differences=expected_differences, + depth=depth + 1, ) if depth == 0 and len(expected_differences.keys()) > 0: - failure = "\n".join([f"Expected {path} to be different but it was not" for path in expected_differences.keys()]) + failure = "\n".join( + [ + f"Expected {path} to be different but it was not" + for path in expected_differences.keys() + ] + ) pytest.fail(failure, pytrace=False) -def run_e2e_test(extra_args: List[str], expected_differences: Dict[Path, str]): +def run_e2e_test( + openapi_document: str, + extra_args: List[str], + expected_differences: Dict[Path, str], + golden_record_path: str = "golden-record", + output_path: str = "my-test-api-client", +): runner = CliRunner() - openapi_path = Path(__file__).parent / "openapi.json" + openapi_path = Path(__file__).parent / openapi_document config_path = Path(__file__).parent / "config.yml" - gr_path = Path(__file__).parent / "golden-record" - output_path = Path.cwd() / "my-test-api-client" + gr_path = Path(__file__).parent / golden_record_path + output_path = Path.cwd() / output_path shutil.rmtree(output_path, ignore_errors=True) args = ["generate", f"--config={config_path}", f"--path={openapi_path}"] @@ -74,8 +95,12 @@ def run_e2e_test(extra_args: List[str], expected_differences: Dict[Path, str]): raise result.exception # Use absolute paths for expected differences for easier comparisons - expected_differences = {output_path.joinpath(key): value for key, value in expected_differences.items()} - _compare_directories(gr_path, output_path, expected_differences=expected_differences) + expected_differences = { + output_path.joinpath(key): value for key, value in expected_differences.items() + } + _compare_directories( + gr_path, output_path, expected_differences=expected_differences + ) import mypy.api @@ -85,14 +110,32 @@ def run_e2e_test(extra_args: List[str], expected_differences: Dict[Path, str]): shutil.rmtree(output_path) -def test_end_to_end(): - run_e2e_test([], {}) +def test_baseline_end_to_end_3_0(): + run_e2e_test("baseline_openapi_3.0.json", [], {}) + + +def test_baseline_end_to_end_3_1(): + run_e2e_test("baseline_openapi_3.1.yaml", [], {}) + + +def test_3_1_specific_features(): + run_e2e_test( + "3.1_specific.openapi.yaml", + [], + {}, + "test-3-1-golden-record", + "test-3-1-features-client", + ) def test_custom_templates(): - expected_differences = {} # key: path relative to generated directory, value: expected generated content + expected_differences = ( + {} + ) # key: path relative to generated directory, value: expected generated content api_dir = Path("my_test_api_client").joinpath("api") - golden_tpls_root_dir = Path(__file__).parent.joinpath("custom-templates-golden-record") + golden_tpls_root_dir = Path(__file__).parent.joinpath( + "custom-templates-golden-record" + ) expected_difference_paths = [ Path("README.md"), @@ -100,7 +143,9 @@ def test_custom_templates(): ] for expected_difference_path in expected_difference_paths: - expected_differences[expected_difference_path] = (golden_tpls_root_dir / expected_difference_path).read_text() + expected_differences[expected_difference_path] = ( + golden_tpls_root_dir / expected_difference_path + ).read_text() # Each API module (defined by tag) has a custom __init__.py in it now. for endpoint_mod in golden_tpls_root_dir.joinpath(api_dir).iterdir(): @@ -111,6 +156,7 @@ def test_custom_templates(): expected_differences[relative_path] = expected_text run_e2e_test( + "baseline_openapi_3.0.json", extra_args=["--custom-template-path=end_to_end_tests/test_custom_templates/"], expected_differences=expected_differences, ) diff --git a/integration-tests/integration_tests/models/post_body_multipart_multipart_data.py b/integration-tests/integration_tests/models/post_body_multipart_multipart_data.py index be94fc27e..526c489f4 100644 --- a/integration-tests/integration_tests/models/post_body_multipart_multipart_data.py +++ b/integration-tests/integration_tests/models/post_body_multipart_multipart_data.py @@ -26,6 +26,7 @@ class PostBodyMultipartMultipartData: def to_dict(self) -> Dict[str, Any]: a_string = self.a_string + file = self.file.to_tuple() description = self.description @@ -47,6 +48,7 @@ def to_multipart(self) -> Dict[str, Any]: a_string = ( self.a_string if isinstance(self.a_string, Unset) else (None, str(self.a_string).encode(), "text/plain") ) + file = self.file.to_tuple() description = ( diff --git a/integration-tests/integration_tests/models/post_body_multipart_response_200.py b/integration-tests/integration_tests/models/post_body_multipart_response_200.py index b1ca022db..79359ec41 100644 --- a/integration-tests/integration_tests/models/post_body_multipart_response_200.py +++ b/integration-tests/integration_tests/models/post_body_multipart_response_200.py @@ -26,9 +26,13 @@ class PostBodyMultipartResponse200: def to_dict(self) -> Dict[str, Any]: a_string = self.a_string + file_data = self.file_data + description = self.description + file_name = self.file_name + file_content_type = self.file_content_type field_dict: Dict[str, Any] = {} diff --git a/integration-tests/integration_tests/models/post_parameters_header_response_200.py b/integration-tests/integration_tests/models/post_parameters_header_response_200.py index cc633bc4a..03e688ba1 100644 --- a/integration-tests/integration_tests/models/post_parameters_header_response_200.py +++ b/integration-tests/integration_tests/models/post_parameters_header_response_200.py @@ -24,8 +24,11 @@ class PostParametersHeaderResponse200: def to_dict(self) -> Dict[str, Any]: boolean = self.boolean + string = self.string + number = self.number + integer = self.integer field_dict: Dict[str, Any] = {} diff --git a/integration-tests/integration_tests/models/problem.py b/integration-tests/integration_tests/models/problem.py index 3b5f102cd..bde5b6d37 100644 --- a/integration-tests/integration_tests/models/problem.py +++ b/integration-tests/integration_tests/models/problem.py @@ -22,6 +22,7 @@ class Problem: def to_dict(self) -> Dict[str, Any]: parameter_name = self.parameter_name + description = self.description field_dict: Dict[str, Any] = {} diff --git a/integration-tests/integration_tests/models/public_error.py b/integration-tests/integration_tests/models/public_error.py index 74e3fc67c..993bd8ad3 100644 --- a/integration-tests/integration_tests/models/public_error.py +++ b/integration-tests/integration_tests/models/public_error.py @@ -42,7 +42,6 @@ def to_dict(self) -> Dict[str, Any]: invalid_parameters = [] for invalid_parameters_item_data in self.invalid_parameters: invalid_parameters_item = invalid_parameters_item_data.to_dict() - invalid_parameters.append(invalid_parameters_item) missing_parameters: Union[Unset, List[str]] = UNSET diff --git a/openapi_python_client/parser/errors.py b/openapi_python_client/parser/errors.py index d7111a7b8..76a795b24 100644 --- a/openapi_python_client/parser/errors.py +++ b/openapi_python_client/parser/errors.py @@ -2,7 +2,7 @@ from enum import Enum from typing import Optional -__all__ = ["ErrorLevel", "GeneratorError", "ParseError", "PropertyError", "ValidationError", "ParameterError"] +__all__ = ["ErrorLevel", "GeneratorError", "ParseError", "PropertyError", "ParameterError"] from pydantic import BaseModel @@ -44,7 +44,3 @@ class ParameterError(ParseError): """Error raised when there's a problem creating a Parameter.""" header = "Problem creating a Parameter: " - - -class ValidationError(Exception): - """Used internally to exit quickly from property parsing due to some internal exception.""" diff --git a/openapi_python_client/parser/openapi.py b/openapi_python_client/parser/openapi.py index 0ab5cd26c..299542b2b 100644 --- a/openapi_python_client/parser/openapi.py +++ b/openapi_python_client/parser/openapi.py @@ -342,7 +342,7 @@ def _add_responses( return endpoint, schemas @staticmethod - def add_parameters( # noqa: PLR0911, PLR0912 + def add_parameters( # noqa: PLR0911 *, endpoint: "Endpoint", data: Union[oai.Operation, oai.PathItem], @@ -388,13 +388,12 @@ def add_parameters( # noqa: PLR0911, PLR0912 "client": AnyProperty( "client", True, - False, None, PythonIdentifier("client", ""), None, None, ), - "url": AnyProperty("url", True, False, None, PythonIdentifier("url", ""), None, None), + "url": AnyProperty("url", True, None, PythonIdentifier("url", ""), None, None), }, } @@ -437,7 +436,7 @@ def add_parameters( # noqa: PLR0911, PLR0912 if isinstance(prop, ParseError): return ( ParseError( - detail=f"cannot parse parameter of endpoint {endpoint.name}", + detail=f"cannot parse parameter of endpoint {endpoint.name}: {prop.detail}", data=prop.data, ), schemas, @@ -484,9 +483,6 @@ def add_parameters( # noqa: PLR0911, PLR0912 schemas, parameters, ) - if param.param_in == oai.ParameterLocation.QUERY and (prop.nullable or not prop.required): - # There is no NULL for query params, so nullable and not required are the same. - prop = attr.evolve(prop, required=False, nullable=True) # No reasons to use lazy imports in endpoints, so add lazy imports to relative here. endpoint.relative_imports.update(prop.get_lazy_imports(prefix=models_relative_prefix)) diff --git a/openapi_python_client/parser/properties/__init__.py b/openapi_python_client/parser/properties/__init__.py index f434bca61..7d3cc1c21 100644 --- a/openapi_python_client/parser/properties/__init__.py +++ b/openapi_python_client/parser/properties/__init__.py @@ -1,3 +1,5 @@ +from __future__ import annotations + __all__ = [ "AnyProperty", "Class", @@ -11,17 +13,25 @@ "property_from_data", ] -from itertools import chain -from typing import Any, ClassVar, Dict, Generic, Iterable, List, Optional, Set, Tuple, TypeVar, Union +from typing import Iterable -from attrs import define, evolve +from attrs import evolve from ... import Config, utils from ... import schema as oai -from ..errors import ParameterError, ParseError, PropertyError, ValidationError -from .converter import convert, convert_chain +from ..errors import ParameterError, ParseError, PropertyError +from .any import AnyProperty +from .boolean import BooleanProperty +from .const import ConstProperty +from .date import DateProperty +from .datetime import DateTimeProperty from .enum_property import EnumProperty -from .model_property import ModelProperty, build_model_property, process_model +from .file import FileProperty +from .float import FloatProperty +from .int import IntProperty +from .list_property import ListProperty +from .model_property import ModelProperty, process_model +from .none import NoneProperty from .property import Property from .schemas import ( Class, @@ -32,601 +42,129 @@ update_parameters_with_data, update_schemas_with_data, ) - - -@define -class AnyProperty(Property): - """A property that can be any type (used for empty schemas)""" - - _type_string: ClassVar[str] = "Any" - _json_type_string: ClassVar[str] = "Any" - - -@define -class NoneProperty(Property): - """A property that can only be None""" - - _type_string: ClassVar[str] = "None" - _json_type_string: ClassVar[str] = "None" - - -@define -class StringProperty(Property): - """A property of type str""" - - max_length: Optional[int] = None - pattern: Optional[str] = None - _type_string: ClassVar[str] = "str" - _json_type_string: ClassVar[str] = "str" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - - -@define -class DateTimeProperty(Property): - """ - A property of type datetime.datetime - """ - - _type_string: ClassVar[str] = "datetime.datetime" - _json_type_string: ClassVar[str] = "str" - template: ClassVar[str] = "datetime_property.py.jinja" - - def get_imports(self, *, prefix: str) -> Set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.update({"import datetime", "from typing import cast", "from dateutil.parser import isoparse"}) - return imports - - -@define -class DateProperty(Property): - """A property of type datetime.date""" - - _type_string: ClassVar[str] = "datetime.date" - _json_type_string: ClassVar[str] = "str" - template: ClassVar[str] = "date_property.py.jinja" - - def get_imports(self, *, prefix: str) -> Set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.update({"import datetime", "from typing import cast", "from dateutil.parser import isoparse"}) - return imports - - -@define -class FileProperty(Property): - """A property used for uploading files""" - - _type_string: ClassVar[str] = "File" - # Return type of File.to_tuple() - _json_type_string: ClassVar[str] = "FileJsonType" - template: ClassVar[str] = "file_property.py.jinja" - - def get_imports(self, *, prefix: str) -> Set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.update({f"from {prefix}types import File, FileJsonType", "from io import BytesIO"}) - return imports - - -@define -class FloatProperty(Property): - """A property of type float""" - - _type_string: ClassVar[str] = "float" - _json_type_string: ClassVar[str] = "float" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - template: ClassVar[str] = "float_property.py.jinja" - - -@define -class IntProperty(Property): - """A property of type int""" - - _type_string: ClassVar[str] = "int" - _json_type_string: ClassVar[str] = "int" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - template: ClassVar[str] = "int_property.py.jinja" - - -@define -class BooleanProperty(Property): - """Property for bool""" - - _type_string: ClassVar[str] = "bool" - _json_type_string: ClassVar[str] = "bool" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - oai.ParameterLocation.HEADER, - } - template: ClassVar[str] = "boolean_property.py.jinja" - - -InnerProp = TypeVar("InnerProp", bound=Property) - - -@define -class ListProperty(Property, Generic[InnerProp]): - """A property representing a list (array) of other properties""" - - inner_property: InnerProp - template: ClassVar[str] = "list_property.py.jinja" - - def get_base_type_string(self, *, quoted: bool = False) -> str: - return f"List[{self.inner_property.get_type_string(quoted=not self.inner_property.is_base_type)}]" - - def get_base_json_type_string(self, *, quoted: bool = False) -> str: - return f"List[{self.inner_property.get_type_string(json=True, quoted=not self.inner_property.is_base_type)}]" - - def get_instance_type_string(self) -> str: - """Get a string representation of runtime type that should be used for `isinstance` checks""" - return "list" - - def get_imports(self, *, prefix: str) -> Set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - imports.update(self.inner_property.get_imports(prefix=prefix)) - imports.add("from typing import cast, List") - return imports - - def get_lazy_imports(self, *, prefix: str) -> Set[str]: - lazy_imports = super().get_lazy_imports(prefix=prefix) - lazy_imports.update(self.inner_property.get_lazy_imports(prefix=prefix)) - return lazy_imports - - -@define -class UnionProperty(Property): - """A property representing a Union (anyOf) of other properties""" - - inner_properties: List[Property] - template: ClassVar[str] = "union_property.py.jinja" - - def _get_inner_type_strings(self, json: bool = False) -> Set[str]: - return { - p.get_type_string(no_optional=True, json=json, quoted=not p.is_base_type) for p in self.inner_properties - } - - @staticmethod - def _get_type_string_from_inner_type_strings(inner_types: Set[str]) -> str: - if len(inner_types) == 1: - return inner_types.pop() - return f"Union[{', '.join(sorted(inner_types))}]" - - def get_base_type_string(self, *, quoted: bool = False) -> str: - return self._get_type_string_from_inner_type_strings(self._get_inner_type_strings(json=False)) - - def get_base_json_type_string(self, *, quoted: bool = False) -> str: - return self._get_type_string_from_inner_type_strings(self._get_inner_type_strings(json=True)) - - def get_type_strings_in_union(self, no_optional: bool = False, json: bool = False) -> Set[str]: - """ - Get the set of all the types that should appear within the `Union` representing this property. - - This function is called from the union property macros, thus the public visibility. - - Args: - no_optional: Do not include `None` or `Unset` in this set. - json: If True, this returns the JSON types, not the Python types, of this property. - - Returns: - A set of strings containing the types that should appear within `Union`. - """ - type_strings = self._get_inner_type_strings(json=json) - if no_optional: - return type_strings - if self.nullable: - type_strings.add("None") - if not self.required: - type_strings.add("Unset") - return type_strings - - def get_type_string( - self, - no_optional: bool = False, - json: bool = False, - *, - quoted: bool = False, - ) -> str: - """ - Get a string representation of type that should be used when declaring this property. - This implementation differs slightly from `Property.get_type_string` in order to collapse - nested union types. - """ - type_strings_in_union = self.get_type_strings_in_union(no_optional=no_optional, json=json) - return self._get_type_string_from_inner_type_strings(type_strings_in_union) - - def get_imports(self, *, prefix: str) -> Set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = super().get_imports(prefix=prefix) - for inner_prop in self.inner_properties: - imports.update(inner_prop.get_imports(prefix=prefix)) - imports.add("from typing import cast, Union") - return imports - - def get_lazy_imports(self, *, prefix: str) -> Set[str]: - lazy_imports = super().get_lazy_imports(prefix=prefix) - for inner_prop in self.inner_properties: - lazy_imports.update(inner_prop.get_lazy_imports(prefix=prefix)) - return lazy_imports +from .string import StringProperty +from .union import UnionProperty def _string_based_property( name: str, required: bool, data: oai.Schema, config: Config -) -> Union[StringProperty, DateProperty, DateTimeProperty, FileProperty]: +) -> StringProperty | DateProperty | DateTimeProperty | FileProperty | PropertyError: """Construct a Property from the type "string" """ string_format = data.schema_format python_name = utils.PythonIdentifier(value=name, prefix=config.field_prefix) if string_format == "date-time": - return DateTimeProperty( + return DateTimeProperty.build( name=name, required=required, - default=convert("datetime.datetime", data.default), - nullable=data.nullable, + default=data.default, python_name=python_name, description=data.description, example=data.example, ) if string_format == "date": - return DateProperty( + return DateProperty.build( name=name, required=required, - default=convert("datetime.date", data.default), - nullable=data.nullable, + default=data.default, python_name=python_name, description=data.description, example=data.example, ) if string_format == "binary": - return FileProperty( + return FileProperty.build( name=name, required=required, default=None, - nullable=data.nullable, python_name=python_name, description=data.description, example=data.example, ) - return StringProperty( + return StringProperty.build( name=name, - default=convert("str", data.default), + default=data.default, required=required, pattern=data.pattern, - nullable=data.nullable, python_name=python_name, description=data.description, example=data.example, ) -def build_enum_property( - *, - data: oai.Schema, - name: str, - required: bool, - schemas: Schemas, - enum: Union[List[Optional[str]], List[Optional[int]]], - parent_name: Optional[str], - config: Config, -) -> Tuple[Union[EnumProperty, NoneProperty, PropertyError], Schemas]: - """ - Create an EnumProperty from schema data. - - Args: - data: The OpenAPI Schema which defines this enum. - name: The name to use for variables which receive this Enum's value (e.g. model property name) - required: Whether or not this Property is required in the calling context - schemas: The Schemas which have been defined so far (used to prevent naming collisions) - enum: The enum from the provided data. Required separately here to prevent extra type checking. - parent_name: The context in which this EnumProperty is defined, used to create more specific class names. - config: The global config for this run of the generator - - Returns: - A tuple containing either the created property or a PropertyError describing what went wrong AND update schemas. - """ - - if len(enum) == 0: - return PropertyError(detail="No values provided for Enum", data=data), schemas - - class_name = data.title or name - if parent_name: - class_name = f"{utils.pascal_case(parent_name)}{utils.pascal_case(class_name)}" - class_info = Class.from_string(string=class_name, config=config) - - # OpenAPI allows for null as an enum value, but it doesn't make sense with how enums are constructed in Python. - # So instead, if null is a possible value, make the property nullable. - # Mypy is not smart enough to know that the type is right though - value_list: Union[List[str], List[int]] = [value for value in enum if value is not None] # type: ignore - if len(value_list) < len(enum): - data.nullable = True - - # It's legal to have an enum that only contains null as a value, we don't bother constructing an enum in that case - if len(value_list) == 0: - return ( - NoneProperty( - name=name, - required=required, - nullable=False, - default="None", - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=None, - example=None, - ), - schemas, - ) - values = EnumProperty.values_from_list(value_list) - - if class_info.name in schemas.classes_by_name: - existing = schemas.classes_by_name[class_info.name] - if not isinstance(existing, EnumProperty) or values != existing.values: - return ( - PropertyError( - detail=f"Found conflicting enums named {class_info.name} with incompatible values.", data=data - ), - schemas, - ) - - value_type = type(next(iter(values.values()))) - - prop = EnumProperty( - name=name, - required=required, - nullable=data.nullable, - class_info=class_info, - values=values, - value_type=value_type, - default=None, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ) - - default = get_enum_default(prop, data) - if isinstance(default, PropertyError): - return default, schemas - prop = evolve(prop, default=default) - - schemas = evolve(schemas, classes_by_name={**schemas.classes_by_name, class_info.name: prop}) - return prop, schemas - - -def get_enum_default(prop: EnumProperty, data: oai.Schema) -> Union[Optional[str], PropertyError]: - """ - Run through the available values in an EnumProperty and return the string representing the default value - in `data`. - - Args: - prop: The EnumProperty to search for the default value. - data: The schema containing the default value for this enum. - - Returns: - If `default` is `None`, then `None`. - If `default` is a valid value in `prop`, then the string representing that variant (e.g. MyEnum.MY_VARIANT) - If `default` is a value that doesn't match a variant of the enum, then a `PropertyError`. - """ - default = data.default - if default is None: - return None - - inverse_values = {v: k for k, v in prop.values.items()} - try: - return f"{prop.class_info.name}.{inverse_values[default]}" - except KeyError: - return PropertyError(detail=f"{default} is an invalid default for enum {prop.class_info.name}", data=data) - - -def build_union_property( - *, data: oai.Schema, name: str, required: bool, schemas: Schemas, parent_name: str, config: Config -) -> Tuple[Union[UnionProperty, PropertyError], Schemas]: - """ - Create a `UnionProperty` the right way. - - Args: - data: The `Schema` describing the `UnionProperty`. - name: The name of the property where it appears in the OpenAPI document. - required: Whether or not this property is required where it's being used. - schemas: The `Schemas` so far describing existing classes / references. - parent_name: The name of the thing which holds this property (used for renaming inner classes). - config: User-defined config values for modifying inner properties. - - Returns: - `(result, schemas)` where `schemas` is the updated version of the input `schemas` and `result` is the - constructed `UnionProperty` or a `PropertyError` describing what went wrong. - """ - sub_properties: List[Property] = [] - - for i, sub_prop_data in enumerate(chain(data.anyOf, data.oneOf)): - sub_prop, schemas = property_from_data( - name=f"{name}_type_{i}", - required=required, - data=sub_prop_data, - schemas=schemas, - parent_name=parent_name, - config=config, - ) - if isinstance(sub_prop, PropertyError): - return PropertyError(detail=f"Invalid property in union {name}", data=sub_prop_data), schemas - sub_properties.append(sub_prop) - - default = convert_chain((prop.get_base_type_string() for prop in sub_properties), data.default) - return ( - UnionProperty( - name=name, - required=required, - default=default, - inner_properties=sub_properties, - nullable=data.nullable, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ), - schemas, - ) - - -def build_list_property( - *, - data: oai.Schema, - name: str, - required: bool, - schemas: Schemas, - parent_name: str, - config: Config, - process_properties: bool, - roots: Set[Union[ReferencePath, utils.ClassName]], -) -> Tuple[Union[ListProperty[Any], PropertyError], Schemas]: - """ - Build a ListProperty the right way, use this instead of the normal constructor. - - Args: - data: `oai.Schema` representing this `ListProperty`. - name: The name of this property where it's used. - required: Whether or not this `ListProperty` can be `Unset` where it's used. - schemas: Collected `Schemas` so far containing any classes or references. - parent_name: The name of the thing containing this property (used for naming inner classes). - config: User-provided config for overriding default behaviors. - - Returns: - `(result, schemas)` where `schemas` is an updated version of the input named the same including any inner - classes that were defined and `result` is either the `ListProperty` or a `PropertyError`. - """ - if data.items is None: - return PropertyError(data=data, detail="type array must have items defined"), schemas - inner_prop, schemas = property_from_data( - name=f"{name}_item", - required=True, - data=data.items, - schemas=schemas, - parent_name=parent_name, - config=config, - process_properties=process_properties, - roots=roots, - ) - if isinstance(inner_prop, PropertyError): - inner_prop.header = f'invalid data in items of array named "{name}"' - return inner_prop, schemas - return ( - ListProperty( - name=name, - required=required, - default=None, - inner_property=inner_prop, - nullable=data.nullable, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - description=data.description, - example=data.example, - ), - schemas, - ) - - def _property_from_ref( name: str, required: bool, - parent: Union[oai.Schema, None], + parent: oai.Schema | None, data: oai.Reference, schemas: Schemas, config: Config, - roots: Set[Union[ReferencePath, utils.ClassName]], -) -> Tuple[Union[Property, PropertyError], Schemas]: + roots: set[ReferencePath | utils.ClassName], +) -> tuple[Property | PropertyError, Schemas]: ref_path = parse_reference_path(data.ref) if isinstance(ref_path, ParseError): return PropertyError(data=data, detail=ref_path.detail), schemas existing = schemas.classes_by_reference.get(ref_path) if not existing: - return PropertyError(data=data, detail="Could not find reference in parsed models or enums"), schemas + return ( + PropertyError(data=data, detail="Could not find reference in parsed models or enums"), + schemas, + ) + + default = existing.convert_value(parent.default) if parent is not None else None + if isinstance(default, PropertyError): + default.data = parent or data + return default, schemas prop = evolve( existing, required=required, name=name, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + default=default, # type: ignore # mypy can't tell that default comes from the same class... ) - if parent: - prop = evolve(prop, nullable=parent.nullable) - if isinstance(prop, EnumProperty): - default = get_enum_default(prop, parent) - if isinstance(default, PropertyError): - return default, schemas - prop = evolve(prop, default=default) schemas.add_dependencies(ref_path=ref_path, roots=roots) return prop, schemas -def _property_from_data( # noqa: PLR0911 +def property_from_data( # noqa: PLR0911 name: str, required: bool, - data: Union[oai.Reference, oai.Schema], + data: oai.Reference | oai.Schema, schemas: Schemas, parent_name: str, config: Config, - process_properties: bool, - roots: Set[Union[ReferencePath, utils.ClassName]], -) -> Tuple[Union[Property, PropertyError], Schemas]: + process_properties: bool = True, + roots: set[ReferencePath | utils.ClassName] | None = None, +) -> tuple[Property | PropertyError, Schemas]: """Generate a Property from the OpenAPI dictionary representation of it""" + roots = roots or set() name = utils.remove_string_escapes(name) if isinstance(data, oai.Reference): return _property_from_ref( - name=name, required=required, parent=None, data=data, schemas=schemas, config=config, roots=roots + name=name, + required=required, + parent=None, + data=data, + schemas=schemas, + config=config, + roots=roots, ) - sub_data: List[Union[oai.Schema, oai.Reference]] = data.allOf + data.anyOf + data.oneOf + sub_data: list[oai.Schema | oai.Reference] = data.allOf + data.anyOf + data.oneOf # A union of a single reference should just be passed through to that reference (don't create copy class) if len(sub_data) == 1 and isinstance(sub_data[0], oai.Reference): return _property_from_ref( - name=name, required=required, parent=data, data=sub_data[0], schemas=schemas, config=config, roots=roots + name=name, + required=required, + parent=data, + data=sub_data[0], + schemas=schemas, + config=config, + roots=roots, ) if data.enum: - return build_enum_property( + return EnumProperty.build( data=data, name=name, required=required, @@ -635,19 +173,38 @@ def _property_from_data( # noqa: PLR0911 parent_name=parent_name, config=config, ) - if data.anyOf or data.oneOf: - return build_union_property( - data=data, name=name, required=required, schemas=schemas, parent_name=parent_name, config=config + if data.anyOf or data.oneOf or isinstance(data.type, list): + return UnionProperty.build( + data=data, + name=name, + required=required, + schemas=schemas, + parent_name=parent_name, + config=config, + ) + if data.const is not None: + return ( + ConstProperty.build( + name=name, + required=required, + default=data.default, + const=data.const, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + ), + schemas, ) if data.type == oai.DataType.STRING: - return _string_based_property(name=name, required=required, data=data, config=config), schemas + return ( + _string_based_property(name=name, required=required, data=data, config=config), + schemas, + ) if data.type == oai.DataType.NUMBER: return ( - FloatProperty( + FloatProperty.build( name=name, - default=convert("float", data.default), + default=data.default, required=required, - nullable=data.nullable, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), description=data.description, example=data.example, @@ -656,11 +213,10 @@ def _property_from_data( # noqa: PLR0911 ) if data.type == oai.DataType.INTEGER: return ( - IntProperty( + IntProperty.build( name=name, - default=convert("int", data.default), + default=data.default, required=required, - nullable=data.nullable, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), description=data.description, example=data.example, @@ -669,11 +225,22 @@ def _property_from_data( # noqa: PLR0911 ) if data.type == oai.DataType.BOOLEAN: return ( - BooleanProperty( + BooleanProperty.build( name=name, required=required, - default=convert("bool", data.default), - nullable=data.nullable, + default=data.default, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ), + schemas, + ) + if data.type == oai.DataType.NULL: + return ( + NoneProperty( + name=name, + required=required, + default=None, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), description=data.description, example=data.example, @@ -681,7 +248,7 @@ def _property_from_data( # noqa: PLR0911 schemas, ) if data.type == oai.DataType.ARRAY: - return build_list_property( + return ListProperty.build( data=data, name=name, required=required, @@ -692,7 +259,7 @@ def _property_from_data( # noqa: PLR0911 roots=roots, ) if data.type == oai.DataType.OBJECT or data.allOf or (data.type is None and data.properties): - return build_model_property( + return ModelProperty.build( data=data, name=name, schemas=schemas, @@ -703,10 +270,9 @@ def _property_from_data( # noqa: PLR0911 roots=roots, ) return ( - AnyProperty( + AnyProperty.build( name=name, required=required, - nullable=False, default=None, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), description=data.description, @@ -716,65 +282,15 @@ def _property_from_data( # noqa: PLR0911 ) -def property_from_data( +def _create_schemas( *, - name: str, - required: bool, - data: Union[oai.Reference, oai.Schema], + components: dict[str, oai.Reference | oai.Schema], schemas: Schemas, - parent_name: str, config: Config, - process_properties: bool = True, - roots: Optional[Set[Union[ReferencePath, utils.ClassName]]] = None, -) -> Tuple[Union[Property, PropertyError], Schemas]: - """ - Build a Property from an OpenAPI schema or reference. This Property represents a single input or output for a - generated API operation. - - Args: - name: The name of the property, defined in OpenAPI as the key pointing at the schema. This is the parameter used - to send this data to an API or that the API will respond with. This will be used to generate a `python_name` - which is the name of the variable/attribute in generated Python. - required: Whether or not this property is required in whatever source is creating it. OpenAPI defines this by - including the property's name in the `required` list. If the property is required, `Unset` will not be - included in the generated code's available types. - data: The OpenAPI schema or reference that defines the details of this property (e.g. type, sub-properties). - schemas: A structure containing all of the parsed schemas so far that will become generated classes. This is - used to resolve references and to ensure that conflicting class names are not generated. - parent_name: The name of the thing above this property, prepended to generated class names to reduce the chance - of duplication. - config: Contains the parsed config that the user provided to tweak generation settings. Needed to apply class - name overrides for generated classes. - process_properties: If the new property is a ModelProperty, determines whether it will be initialized with - property data - roots: The set of `ReferencePath`s and `ClassName`s to remove from the schemas if a child reference becomes - invalid - Returns: - A tuple containing either the parsed Property or a PropertyError (if something went wrong) and the updated - Schemas (including any new classes that should be generated). - """ - roots = roots or set() - try: - return _property_from_data( - name=name, - required=required, - data=data, - schemas=schemas, - parent_name=parent_name, - config=config, - process_properties=process_properties, - roots=roots, - ) - except ValidationError: - return PropertyError(detail="Failed to validate default value", data=data), schemas - - -def _create_schemas( - *, components: Dict[str, Union[oai.Reference, oai.Schema]], schemas: Schemas, config: Config ) -> Schemas: - to_process: Iterable[Tuple[str, Union[oai.Reference, oai.Schema]]] = components.items() + to_process: Iterable[tuple[str, oai.Reference | oai.Schema]] = components.items() still_making_progress = True - errors: List[PropertyError] = [] + errors: list[PropertyError] = [] # References could have forward References so keep going as long as we are making progress while still_making_progress: @@ -803,7 +319,7 @@ def _create_schemas( return schemas -def _propogate_removal(*, root: Union[ReferencePath, utils.ClassName], schemas: Schemas, error: PropertyError) -> None: +def _propogate_removal(*, root: ReferencePath | utils.ClassName, schemas: Schemas, error: PropertyError) -> None: if isinstance(root, utils.ClassName): schemas.classes_by_name.pop(root, None) return @@ -816,8 +332,8 @@ def _propogate_removal(*, root: Union[ReferencePath, utils.ClassName], schemas: def _process_model_errors( - model_errors: List[Tuple[ModelProperty, PropertyError]], *, schemas: Schemas -) -> List[PropertyError]: + model_errors: list[tuple[ModelProperty, PropertyError]], *, schemas: Schemas +) -> list[PropertyError]: for model, error in model_errors: error.detail = error.detail or "" error.detail += "\n\nFailure to process schema has resulted in the removal of:" @@ -829,8 +345,8 @@ def _process_model_errors( def _process_models(*, schemas: Schemas, config: Config) -> Schemas: to_process = (prop for prop in schemas.classes_by_name.values() if isinstance(prop, ModelProperty)) still_making_progress = True - final_model_errors: List[Tuple[ModelProperty, PropertyError]] = [] - latest_model_errors: List[Tuple[ModelProperty, PropertyError]] = [] + final_model_errors: list[tuple[ModelProperty, PropertyError]] = [] + latest_model_errors: list[tuple[ModelProperty, PropertyError]] = [] # Models which refer to other models in their allOf must be processed after their referenced models while still_making_progress: @@ -863,7 +379,10 @@ def _process_models(*, schemas: Schemas, config: Config) -> Schemas: def build_schemas( - *, components: Dict[str, Union[oai.Reference, oai.Schema]], schemas: Schemas, config: Config + *, + components: dict[str, oai.Reference | oai.Schema], + schemas: Schemas, + config: Config, ) -> Schemas: """Get a list of Schemas from an OpenAPI dict""" schemas = _create_schemas(components=components, schemas=schemas, config=config) @@ -873,16 +392,16 @@ def build_schemas( def build_parameters( *, - components: Dict[str, Union[oai.Reference, oai.Parameter]], + components: dict[str, oai.Reference | oai.Parameter], parameters: Parameters, config: Config, ) -> Parameters: """Get a list of Parameters from an OpenAPI dict""" - to_process: Iterable[Tuple[str, Union[oai.Reference, oai.Parameter]]] = [] + to_process: Iterable[tuple[str, oai.Reference | oai.Parameter]] = [] if components is not None: to_process = components.items() still_making_progress = True - errors: List[ParameterError] = [] + errors: list[ParameterError] = [] # References could have forward References so keep going as long as we are making progress while still_making_progress: diff --git a/openapi_python_client/parser/properties/any.py b/openapi_python_client/parser/properties/any.py new file mode 100644 index 000000000..fdeef93a1 --- /dev/null +++ b/openapi_python_client/parser/properties/any.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ...utils import PythonIdentifier +from .protocol import PropertyProtocol, Value + + +@define +class AnyProperty(PropertyProtocol): + """A property that can be any type (used for empty schemas)""" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> AnyProperty: + return cls( + name=name, + required=required, + default=AnyProperty.convert_value(default), + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None: + if value is None or isinstance(value, Value): + return value + return Value(str(value)) + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + _type_string: ClassVar[str] = "Any" + _json_type_string: ClassVar[str] = "Any" diff --git a/openapi_python_client/parser/properties/boolean.py b/openapi_python_client/parser/properties/boolean.py new file mode 100644 index 000000000..e6bb883a8 --- /dev/null +++ b/openapi_python_client/parser/properties/boolean.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class BooleanProperty(PropertyProtocol): + """Property for bool""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "bool" + _json_type_string: ClassVar[str] = "bool" + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + template: ClassVar[str] = "boolean_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> BooleanProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if isinstance(value, Value) or value is None: + return value + if isinstance(value, str): + if value.lower() == "true": + return Value("True") + elif value.lower() == "false": + return Value("False") + if isinstance(value, bool): + return Value(str(value)) + return PropertyError(f"Invalid boolean value: {value}") diff --git a/openapi_python_client/parser/properties/const.py b/openapi_python_client/parser/properties/const.py new file mode 100644 index 000000000..249808a8a --- /dev/null +++ b/openapi_python_client/parser/properties/const.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +from typing import Any, overload + +from attr import define + +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value +from .string import StringProperty + + +@define +class ConstProperty(PropertyProtocol): + """A property representing a Union (anyOf) of other properties""" + + name: str + required: bool + value: Value + default: Value | None + python_name: PythonIdentifier + description: str | None + example: None + + @classmethod + def build( + cls, + *, + const: str | int, + default: Any, + name: str, + python_name: PythonIdentifier, + required: bool, + description: str | None, + ) -> ConstProperty | PropertyError: + """ + Create a `ConstProperty` the right way. + + Args: + const: The `const` value of the schema, indicating the literal value this represents + default: The default value of this property, if any. Must be equal to `const` if set. + name: The name of the property where it appears in the OpenAPI document. + required: Whether this property is required where it's being used. + python_name: The name used to represent this variable/property in generated Python code + description: The description of this property, used for docstrings + """ + value = cls._convert_value(const) + + prop = cls( + value=value, + python_name=python_name, + name=name, + required=required, + default=None, + description=description, + example=None, + ) + converted_default = prop.convert_value(default) + if isinstance(converted_default, PropertyError): + return converted_default + prop.default = converted_default + return prop + + def convert_value(self, value: Any) -> Value | None | PropertyError: + if isinstance(value, Value): + return value + value = self._convert_value(value) + if value is None: + return value + if value != self.value: + return PropertyError(detail=f"Invalid value for const {self.name}; {value} != {self.value}") + return value + + @staticmethod + @overload + def _convert_value(value: None) -> None: # type: ignore[misc] + ... # pragma: no cover + + @staticmethod + @overload + def _convert_value(value: Any) -> Value: + ... # pragma: no cover + + @staticmethod + def _convert_value(value: Any) -> Value | None: + if value is None or isinstance(value, Value): + return value + if isinstance(value, Value): + return value # pragma: no cover + if isinstance(value, str): + return StringProperty.convert_value(value) + return Value(str(value)) + + def get_type_string( + self, + no_optional: bool = False, + json: bool = False, + *, + multipart: bool = False, + quoted: bool = False, + ) -> str: + lit = f"Literal[{self.value}]" + if not no_optional and not self.required: + return f"Union[{lit}, Unset]" + return lit + + def get_imports(self, *, prefix: str) -> set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + if self.required: + return {"from typing import Literal"} + return { + "from typing import Literal, Union", + f"from {prefix}types import UNSET, Unset", + } diff --git a/openapi_python_client/parser/properties/converter.py b/openapi_python_client/parser/properties/converter.py deleted file mode 100644 index 9b8f27073..000000000 --- a/openapi_python_client/parser/properties/converter.py +++ /dev/null @@ -1,82 +0,0 @@ -""" Utils for converting default values into valid Python """ -__all__ = ["convert", "convert_chain"] - -from typing import Any, Callable, Dict, Iterable, Optional - -from dateutil.parser import isoparse - -from ... import utils -from ..errors import ValidationError - - -def convert(type_string: str, value: Any) -> Optional[Any]: - """ - Used by properties to convert some value into a valid value for the type_string. - - Args: - type_string: The string of the actual type that this default will be in the generated client. - value: The default value to try to convert. - - Returns: - The converted value if conversion was successful, or None of the value was None. - - Raises: - ValidationError if value could not be converted for type_string. - """ - if value is None: - return None - if type_string not in _CONVERTERS: - raise ValidationError() - try: - return _CONVERTERS[type_string](value) - except (KeyError, ValueError, AttributeError) as err: - raise ValidationError from err - - -def convert_chain(type_strings: Iterable[str], value: Any) -> Optional[Any]: - """ - Used by properties which support multiple possible converters (Unions). - - Args: - type_strings: Iterable of all the supported type_strings. - value: The default value to try to convert. - - Returns: - The converted value if conversion was successful, or None of the value was None. - - Raises: - ValidationError if value could not be converted for type_string. - """ - for type_string in type_strings: - try: - val = convert(type_string, value) - return val - except ValidationError: - continue - raise ValidationError() - - -def _convert_string(value: Any) -> Optional[str]: - if isinstance(value, str): - value = utils.remove_string_escapes(value) - return repr(value) - - -def _convert_datetime(value: str) -> Optional[str]: - isoparse(value) # Make sure it works - return f"isoparse({value!r})" - - -def _convert_date(value: str) -> Optional[str]: - isoparse(value).date() - return f"isoparse({value!r}).date()" - - -_CONVERTERS: Dict[str, Callable[[Any], Optional[Any]]] = { - "str": _convert_string, - "datetime.datetime": _convert_datetime, - "datetime.date": _convert_date, - "float": float, - "int": int, - "bool": bool, -} diff --git a/openapi_python_client/parser/properties/date.py b/openapi_python_client/parser/properties/date.py new file mode 100644 index 000000000..24e0c34fe --- /dev/null +++ b/openapi_python_client/parser/properties/date.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define +from dateutil.parser import isoparse + +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class DateProperty(PropertyProtocol): + """A property of type datetime.date""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "datetime.date" + _json_type_string: ClassVar[str] = "str" + template: ClassVar[str] = "date_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> DateProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + + return DateProperty( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if isinstance(value, Value) or value is None: + return value + if isinstance(value, str): + try: + isoparse(value).date() # make sure it's a valid value + except ValueError as e: + return PropertyError(f"Invalid date: {e}") + return Value(f"isoparse({value!r}).date()") + return PropertyError(f"Cannot convert {value} to a date") + + def get_imports(self, *, prefix: str) -> set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.update({"import datetime", "from typing import cast", "from dateutil.parser import isoparse"}) + return imports diff --git a/openapi_python_client/parser/properties/datetime.py b/openapi_python_client/parser/properties/datetime.py new file mode 100644 index 000000000..abb28ac22 --- /dev/null +++ b/openapi_python_client/parser/properties/datetime.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define +from dateutil.parser import isoparse + +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class DateTimeProperty(PropertyProtocol): + """ + A property of type datetime.datetime + """ + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "datetime.datetime" + _json_type_string: ClassVar[str] = "str" + template: ClassVar[str] = "datetime_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> DateTimeProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + + return DateTimeProperty( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if value is None or isinstance(value, Value): + return value + if isinstance(value, str): + try: + isoparse(value) # make sure it's a valid value + except ValueError as e: + return PropertyError(f"Invalid datetime: {e}") + return Value(f"isoparse({value!r})") + return PropertyError(f"Cannot convert {value} to a datetime") + + def get_imports(self, *, prefix: str) -> set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.update({"import datetime", "from typing import cast", "from dateutil.parser import isoparse"}) + return imports diff --git a/openapi_python_client/parser/properties/enum_property.py b/openapi_python_client/parser/properties/enum_property.py index 9ba858e50..4348989ea 100644 --- a/openapi_python_client/parser/properties/enum_property.py +++ b/openapi_python_client/parser/properties/enum_property.py @@ -1,42 +1,167 @@ +from __future__ import annotations + __all__ = ["EnumProperty"] -from typing import Any, ClassVar, Dict, List, Optional, Set, Type, Union, cast +from typing import Any, ClassVar, Union, cast -from attrs import define, field +from attr import evolve +from attrs import define +from ... import Config, utils from ... import schema as oai -from ... import utils -from .property import Property -from .schemas import Class +from ...schema import DataType +from ..errors import PropertyError +from .none import NoneProperty +from .protocol import PropertyProtocol, Value +from .schemas import Class, Schemas +from .union import UnionProperty ValueType = Union[str, int] @define -class EnumProperty(Property): +class EnumProperty(PropertyProtocol): """A property that should use an enum""" - values: Dict[str, ValueType] + name: str + required: bool + default: Value | None + python_name: utils.PythonIdentifier + description: str | None + example: str | None + values: dict[str, ValueType] class_info: Class - value_type: Type[ValueType] - default: Optional[Any] = field() + value_type: type[ValueType] template: ClassVar[str] = "enum_property.py.jinja" - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { oai.ParameterLocation.QUERY, oai.ParameterLocation.PATH, oai.ParameterLocation.COOKIE, oai.ParameterLocation.HEADER, } + @classmethod + def build( + cls, + *, + data: oai.Schema, + name: str, + required: bool, + schemas: Schemas, + enum: list[str | None] | list[int | None], + parent_name: str, + config: Config, + ) -> tuple[EnumProperty | NoneProperty | UnionProperty | PropertyError, Schemas]: + """ + Create an EnumProperty from schema data. + + Args: + data: The OpenAPI Schema which defines this enum. + name: The name to use for variables which receive this Enum's value (e.g. model property name) + required: Whether or not this Property is required in the calling context + schemas: The Schemas which have been defined so far (used to prevent naming collisions) + enum: The enum from the provided data. Required separately here to prevent extra type checking. + parent_name: The context in which this EnumProperty is defined, used to create more specific class names. + config: The global config for this run of the generator + + Returns: + A tuple containing either the created property or a PropertyError AND update schemas. + """ + + if len(enum) == 0: + return PropertyError(detail="No values provided for Enum", data=data), schemas + + # OpenAPI allows for null as an enum value, but it doesn't make sense with how enums are constructed in Python. + # So instead, if null is a possible value, make the property nullable. + # Mypy is not smart enough to know that the type is right though + value_list: list[str] | list[int] = [value for value in enum if value is not None] # type: ignore + + # It's legal to have an enum that only contains null as a value, we don't bother constructing an enum for that + if len(value_list) == 0: + return ( + NoneProperty.build( + name=name, + required=required, + default="None", + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=None, + example=None, + ), + schemas, + ) + if len(value_list) < len(enum): # Only one of the values was None, that becomes a union + data.oneOf = [ + oai.Schema(type=DataType.NULL), + data.model_copy(update={"enum": value_list, "default": data.default}), + ] + data.enum = None + return UnionProperty.build( + data=data, + name=name, + required=required, + schemas=schemas, + parent_name=parent_name, + config=config, + ) + + class_name = data.title or name + if parent_name: + class_name = f"{utils.pascal_case(parent_name)}{utils.pascal_case(class_name)}" + class_info = Class.from_string(string=class_name, config=config) + values = EnumProperty.values_from_list(value_list) + + if class_info.name in schemas.classes_by_name: + existing = schemas.classes_by_name[class_info.name] + if not isinstance(existing, EnumProperty) or values != existing.values: + return ( + PropertyError( + detail=f"Found conflicting enums named {class_info.name} with incompatible values.", data=data + ), + schemas, + ) + + value_type = type(next(iter(values.values()))) + + prop = EnumProperty( + name=name, + required=required, + class_info=class_info, + values=values, + value_type=value_type, + default=None, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ) + checked_default = prop.convert_value(data.default) + if isinstance(checked_default, PropertyError): + checked_default.data = data + return checked_default, schemas + prop = evolve(prop, default=checked_default) + + schemas = evolve(schemas, classes_by_name={**schemas.classes_by_name, class_info.name: prop}) + return prop, schemas + + def convert_value(self, value: Any) -> Value | PropertyError | None: + if value is None or isinstance(value, Value): + return value + if isinstance(value, self.value_type): + inverse_values = {v: k for k, v in self.values.items()} + try: + return Value(f"{self.class_info.name}.{inverse_values[value]}") + except KeyError: + return PropertyError(detail=f"Value {value} is not valid for enum {self.name}") + return PropertyError(detail=f"Cannot convert {value} to enum {self.name} of type {self.value_type}") + def get_base_type_string(self, *, quoted: bool = False) -> str: return self.class_info.name def get_base_json_type_string(self, *, quoted: bool = False) -> str: return self.value_type.__name__ - def get_imports(self, *, prefix: str) -> Set[str]: + def get_imports(self, *, prefix: str) -> set[str]: """ Get a set of import strings that should be included when this property is used somewhere @@ -49,9 +174,9 @@ def get_imports(self, *, prefix: str) -> Set[str]: return imports @staticmethod - def values_from_list(values: Union[List[str], List[int]]) -> Dict[str, ValueType]: + def values_from_list(values: list[str] | list[int]) -> dict[str, ValueType]: """Convert a list of values into dict of {name: value}, where value can sometimes be None""" - output: Dict[str, ValueType] = {} + output: dict[str, ValueType] = {} for i, value in enumerate(values): value = cast(Union[str, int], value) diff --git a/openapi_python_client/parser/properties/file.py b/openapi_python_client/parser/properties/file.py new file mode 100644 index 000000000..505876b63 --- /dev/null +++ b/openapi_python_client/parser/properties/file.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol + + +@define +class FileProperty(PropertyProtocol): + """A property used for uploading files""" + + name: str + required: bool + default: None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "File" + # Return type of File.to_tuple() + _json_type_string: ClassVar[str] = "FileJsonType" + template: ClassVar[str] = "file_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> FileProperty | PropertyError: + default_or_err = cls.convert_value(default) + if isinstance(default_or_err, PropertyError): + return default_or_err + + return cls( + name=name, + required=required, + default=default_or_err, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> None | PropertyError: + if value is not None: + return PropertyError(detail="File properties cannot have a default value") + return value + + def get_imports(self, *, prefix: str) -> set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.update({f"from {prefix}types import File, FileJsonType", "from io import BytesIO"}) + return imports diff --git a/openapi_python_client/parser/properties/float.py b/openapi_python_client/parser/properties/float.py new file mode 100644 index 000000000..d8f469c69 --- /dev/null +++ b/openapi_python_client/parser/properties/float.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class FloatProperty(PropertyProtocol): + """A property of type float""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "float" + _json_type_string: ClassVar[str] = "float" + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + template: ClassVar[str] = "float_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> FloatProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if isinstance(value, Value) or value is None: + return value + if isinstance(value, str): + try: + parsed = float(value) + return Value(str(parsed)) + except ValueError: + return PropertyError(f"Invalid float value: {value}") + if isinstance(value, float): + return Value(str(value)) + if isinstance(value, int) and not isinstance(value, bool): + return Value(str(float(value))) + return PropertyError(f"Cannot convert {value} to a float") diff --git a/openapi_python_client/parser/properties/int.py b/openapi_python_client/parser/properties/int.py new file mode 100644 index 000000000..ab7173d3d --- /dev/null +++ b/openapi_python_client/parser/properties/int.py @@ -0,0 +1,69 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class IntProperty(PropertyProtocol): + """A property of type int""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _type_string: ClassVar[str] = "int" + _json_type_string: ClassVar[str] = "int" + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + template: ClassVar[str] = "int_property.py.jinja" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> IntProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if value is None or isinstance(value, Value): + return value + if isinstance(value, str): + try: + int(value) + except ValueError: + return PropertyError(f"Invalid int value: {value}") + return Value(value) + if isinstance(value, int) and not isinstance(value, bool): + return Value(str(value)) + return PropertyError(f"Invalid int value: {value}") diff --git a/openapi_python_client/parser/properties/list_property.py b/openapi_python_client/parser/properties/list_property.py new file mode 100644 index 000000000..7adc1f682 --- /dev/null +++ b/openapi_python_client/parser/properties/list_property.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ... import Config, utils +from ... import schema as oai +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value +from .schemas import ReferencePath, Schemas + + +@define +class ListProperty(PropertyProtocol): + """A property representing a list (array) of other properties""" + + name: str + required: bool + default: Value | None + python_name: utils.PythonIdentifier + description: str | None + example: str | None + inner_property: PropertyProtocol + template: ClassVar[str] = "list_property.py.jinja" + + @classmethod + def build( + cls, + *, + data: oai.Schema, + name: str, + required: bool, + schemas: Schemas, + parent_name: str, + config: Config, + process_properties: bool, + roots: set[ReferencePath | utils.ClassName], + ) -> tuple[ListProperty | PropertyError, Schemas]: + """ + Build a ListProperty the right way, use this instead of the normal constructor. + + Args: + data: `oai.Schema` representing this `ListProperty`. + name: The name of this property where it's used. + required: Whether this `ListProperty` can be `Unset` where it's used. + schemas: Collected `Schemas` so far containing any classes or references. + parent_name: The name of the thing containing this property (used for naming inner classes). + config: User-provided config for overriding default behaviors. + process_properties: If the new property is a ModelProperty, determines whether it will be initialized with + property data + roots: The set of `ReferencePath`s and `ClassName`s to remove from the schemas if a child reference becomes + invalid + + Returns: + `(result, schemas)` where `schemas` is an updated version of the input named the same including any inner + classes that were defined and `result` is either the `ListProperty` or a `PropertyError`. + """ + from . import property_from_data + + if data.items is None: + return PropertyError(data=data, detail="type array must have items defined"), schemas + inner_prop, schemas = property_from_data( + name=f"{name}_item", + required=True, + data=data.items, + schemas=schemas, + parent_name=parent_name, + config=config, + process_properties=process_properties, + roots=roots, + ) + if isinstance(inner_prop, PropertyError): + inner_prop.header = f'invalid data in items of array named "{name}"' + return inner_prop, schemas + return ( + ListProperty( + name=name, + required=required, + default=None, + inner_property=inner_prop, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ), + schemas, + ) + + def convert_value(self, value: Any) -> Value | None | PropertyError: + return None # pragma: no cover + + def get_base_type_string(self, *, quoted: bool = False) -> str: + return f"List[{self.inner_property.get_type_string(quoted=not self.inner_property.is_base_type)}]" + + def get_base_json_type_string(self, *, quoted: bool = False) -> str: + return f"List[{self.inner_property.get_type_string(json=True, quoted=not self.inner_property.is_base_type)}]" + + def get_instance_type_string(self) -> str: + """Get a string representation of runtime type that should be used for `isinstance` checks""" + return "list" + + def get_imports(self, *, prefix: str) -> set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + imports.update(self.inner_property.get_imports(prefix=prefix)) + imports.add("from typing import cast, List") + return imports + + def get_lazy_imports(self, *, prefix: str) -> set[str]: + lazy_imports = super().get_lazy_imports(prefix=prefix) + lazy_imports.update(self.inner_property.get_lazy_imports(prefix=prefix)) + return lazy_imports diff --git a/openapi_python_client/parser/properties/model_property.py b/openapi_python_client/parser/properties/model_property.py index 28fb00b29..76c55a97c 100644 --- a/openapi_python_client/parser/properties/model_property.py +++ b/openapi_python_client/parser/properties/model_property.py @@ -1,7 +1,7 @@ from __future__ import annotations from itertools import chain -from typing import ClassVar, NamedTuple +from typing import Any, ClassVar, NamedTuple from attrs import define, evolve @@ -9,14 +9,19 @@ from ... import schema as oai from ..errors import ParseError, PropertyError from .enum_property import EnumProperty -from .property import Property +from .protocol import PropertyProtocol, Value from .schemas import Class, ReferencePath, Schemas, parse_reference_path @define -class ModelProperty(Property): +class ModelProperty(PropertyProtocol): """A property which refers to another Schema""" + name: str + required: bool + default: Value | None + python_name: utils.PythonIdentifier + example: str | None class_info: Class data: oai.Schema description: str @@ -32,6 +37,95 @@ class ModelProperty(Property): json_is_dict: ClassVar[bool] = True is_multipart_body: bool = False + @classmethod + def build( + cls, + *, + data: oai.Schema, + name: str, + schemas: Schemas, + required: bool, + parent_name: str | None, + config: Config, + process_properties: bool, + roots: set[ReferencePath | utils.ClassName], + ) -> tuple[ModelProperty | PropertyError, Schemas]: + """ + A single ModelProperty from its OAI data + + Args: + data: Data of a single Schema + name: Name by which the schema is referenced, such as a model name. + Used to infer the type name if a `title` property is not available. + schemas: Existing Schemas which have already been processed (to check name conflicts) + required: Whether or not this property is required by the parent (affects typing) + parent_name: The name of the property that this property is inside of (affects class naming) + config: Config data for this run of the generator, used to modifying names + roots: Set of strings that identify schema objects on which the new ModelProperty will depend + process_properties: Determines whether the new ModelProperty will be initialized with property data + """ + if not config.use_path_prefixes_for_title_model_names and data.title: + class_string = data.title + else: + title = data.title or name + if parent_name: + class_string = f"{utils.pascal_case(parent_name)}{utils.pascal_case(title)}" + else: + class_string = title + class_info = Class.from_string(string=class_string, config=config) + model_roots = {*roots, class_info.name} + required_properties: list[Property] | None = None + optional_properties: list[Property] | None = None + relative_imports: set[str] | None = None + lazy_imports: set[str] | None = None + additional_properties: bool | Property | None = None + if process_properties: + data_or_err, schemas = _process_property_data( + data=data, schemas=schemas, class_info=class_info, config=config, roots=model_roots + ) + if isinstance(data_or_err, PropertyError): + return data_or_err, schemas + property_data, additional_properties = data_or_err + required_properties = property_data.required_props + optional_properties = property_data.optional_props + relative_imports = property_data.relative_imports + lazy_imports = property_data.lazy_imports + for root in roots: + if isinstance(root, utils.ClassName): + continue + schemas.add_dependencies(root, {class_info.name}) + + prop = ModelProperty( + class_info=class_info, + data=data, + roots=model_roots, + required_properties=required_properties, + optional_properties=optional_properties, + relative_imports=relative_imports, + lazy_imports=lazy_imports, + additional_properties=additional_properties, + description=data.description or "", + default=None, + required=required, + name=name, + python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), + example=data.example, + ) + if class_info.name in schemas.classes_by_name: + error = PropertyError( + data=data, detail=f'Attempted to generate duplicate models with name "{class_info.name}"' + ) + return error, schemas + + schemas = evolve(schemas, classes_by_name={**schemas.classes_by_name, class_info.name: prop}) + return prop, schemas + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if value is not None: + return PropertyError(detail="ModelProperty cannot have a default value") # pragma: no cover + return None + def __attrs_post_init__(self) -> None: if self.relative_imports: self.set_relative_imports(self.relative_imports) @@ -91,6 +185,7 @@ def get_type_string( no_optional: bool = False, json: bool = False, *, + multipart: bool = False, quoted: bool = False, ) -> str: """ @@ -102,6 +197,8 @@ def get_type_string( """ if json: type_string = self.get_base_json_type_string() + elif multipart: + type_string = "Tuple[None, bytes, str]" else: type_string = self.get_base_type_string() @@ -109,16 +206,14 @@ def get_type_string( if type_string == self.class_info.name: type_string = f"'{type_string}'" - if no_optional or (self.required and not self.nullable): + if no_optional or self.required: return type_string - if self.required and self.nullable: - return f"Optional[{type_string}]" - if not self.required and self.nullable: - return f"Union[Unset, None, {type_string}]" - return f"Union[Unset, {type_string}]" +from .property import Property # noqa: E402 + + def _values_are_subset(first: EnumProperty, second: EnumProperty) -> bool: return set(first.values.items()) <= set(second.values.items()) @@ -151,21 +246,20 @@ def _enum_subset(first: Property, second: Property) -> EnumProperty | None: def _merge_properties(first: Property, second: Property) -> Property | PropertyError: - nullable = first.nullable and second.nullable required = first.required or second.required err = None if first.__class__ == second.__class__: - first = evolve(first, nullable=nullable, required=required) - second = evolve(second, nullable=nullable, required=required) + first = evolve(first, required=required) + second = evolve(second, required=required) if first == second: return first err = PropertyError(header="Cannot merge properties", detail="Properties has conflicting values") enum_subset = _enum_subset(first, second) if enum_subset is not None: - return evolve(enum_subset, nullable=nullable, required=required) + return evolve(enum_subset, required=required) return err or PropertyError( header="Cannot merge properties", @@ -246,7 +340,7 @@ def _add_if_no_conflict(new_prop: Property) -> PropertyError | None: config=config, roots=roots, ) - if isinstance(prop_or_error, Property): + if not isinstance(prop_or_error, PropertyError): prop_or_error = _add_if_no_conflict(prop_or_error) if isinstance(prop_or_error, PropertyError): return prop_or_error @@ -254,7 +348,7 @@ def _add_if_no_conflict(new_prop: Property) -> PropertyError | None: required_properties = [] optional_properties = [] for prop in properties.values(): - if prop.required and not prop.nullable: + if prop.required: required_properties.append(prop) else: optional_properties.append(prop) @@ -325,11 +419,13 @@ def _process_property_data( config=config, roots=roots, ) - if isinstance(additional_properties, Property): + if isinstance(additional_properties, PropertyError): + return additional_properties, schemas + elif isinstance(additional_properties, bool): + pass + else: property_data.relative_imports.update(additional_properties.get_imports(prefix="..")) property_data.lazy_imports.update(additional_properties.get_lazy_imports(prefix="..")) - elif isinstance(additional_properties, PropertyError): - return additional_properties, schemas return (property_data, additional_properties), schemas @@ -361,84 +457,3 @@ def process_model(model_prop: ModelProperty, *, schemas: Schemas, config: Config model_prop.set_lazy_imports(property_data.lazy_imports) object.__setattr__(model_prop, "additional_properties", additional_properties) return schemas - - -def build_model_property( - *, - data: oai.Schema, - name: str, - schemas: Schemas, - required: bool, - parent_name: str | None, - config: Config, - process_properties: bool, - roots: set[ReferencePath | utils.ClassName], -) -> tuple[ModelProperty | PropertyError, Schemas]: - """ - A single ModelProperty from its OAI data - - Args: - data: Data of a single Schema - name: Name by which the schema is referenced, such as a model name. - Used to infer the type name if a `title` property is not available. - schemas: Existing Schemas which have already been processed (to check name conflicts) - required: Whether or not this property is required by the parent (affects typing) - parent_name: The name of the property that this property is inside of (affects class naming) - config: Config data for this run of the generator, used to modifying names - roots: Set of strings that identify schema objects on which the new ModelProperty will depend - process_properties: Determines whether the new ModelProperty will be initialized with property data - """ - if not config.use_path_prefixes_for_title_model_names and data.title: - class_string = data.title - else: - title = data.title or name - if parent_name: - class_string = f"{utils.pascal_case(parent_name)}{utils.pascal_case(title)}" - else: - class_string = title - class_info = Class.from_string(string=class_string, config=config) - model_roots = {*roots, class_info.name} - required_properties: list[Property] | None = None - optional_properties: list[Property] | None = None - relative_imports: set[str] | None = None - lazy_imports: set[str] | None = None - additional_properties: bool | Property | None = None - if process_properties: - data_or_err, schemas = _process_property_data( - data=data, schemas=schemas, class_info=class_info, config=config, roots=model_roots - ) - if isinstance(data_or_err, PropertyError): - return data_or_err, schemas - property_data, additional_properties = data_or_err - required_properties = property_data.required_props - optional_properties = property_data.optional_props - relative_imports = property_data.relative_imports - lazy_imports = property_data.lazy_imports - for root in roots: - if isinstance(root, utils.ClassName): - continue - schemas.add_dependencies(root, {class_info.name}) - - prop = ModelProperty( - class_info=class_info, - data=data, - roots=model_roots, - required_properties=required_properties, - optional_properties=optional_properties, - relative_imports=relative_imports, - lazy_imports=lazy_imports, - additional_properties=additional_properties, - description=data.description or "", - default=None, - nullable=data.nullable, - required=required, - name=name, - python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - example=data.example, - ) - if class_info.name in schemas.classes_by_name: - error = PropertyError(data=data, detail=f'Attempted to generate duplicate models with name "{class_info.name}"') - return error, schemas - - schemas = evolve(schemas, classes_by_name={**schemas.classes_by_name, class_info.name: prop}) - return prop, schemas diff --git a/openapi_python_client/parser/properties/none.py b/openapi_python_client/parser/properties/none.py new file mode 100644 index 000000000..c329dac40 --- /dev/null +++ b/openapi_python_client/parser/properties/none.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +from typing import Any, ClassVar + +from attr import define + +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class NoneProperty(PropertyProtocol): + """A property that can only be None""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + _type_string: ClassVar[str] = "None" + _json_type_string: ClassVar[str] = "None" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> NoneProperty | PropertyError: + checked_default = cls.convert_value(default) + if isinstance(checked_default, PropertyError): + return checked_default + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if value is None or isinstance(value, Value): + return value + if isinstance(value, str): + if value == "None": + return Value(value) + return PropertyError(f"Value {value} is not valid, only None is allowed") diff --git a/openapi_python_client/parser/properties/property.py b/openapi_python_client/parser/properties/property.py index d00826b73..fa3a26beb 100644 --- a/openapi_python_client/parser/properties/property.py +++ b/openapi_python_client/parser/properties/property.py @@ -1,166 +1,37 @@ __all__ = ["Property"] -from typing import TYPE_CHECKING, ClassVar, Optional, Set - -from attrs import define, field - -from ... import Config -from ... import schema as oai -from ...utils import PythonIdentifier -from ..errors import ParseError - -if TYPE_CHECKING: # pragma: no cover - from .model_property import ModelProperty -else: - ModelProperty = "ModelProperty" - - -@define -class Property: - """ - Describes a single property for a schema - - Attributes: - template: Name of the template file (if any) to use for this property. Must be stored in - templates/property_templates and must contain two macros: construct and transform. Construct will be used to - build this property from JSON data (a response from an API). Transform will be used to convert this property - to JSON data (when sending a request to the API). - - Raises: - ValidationError: Raised when the default value fails to be converted to the expected type - """ - - name: str - required: bool - nullable: bool - _type_string: ClassVar[str] = "" - _json_type_string: ClassVar[str] = "" # Type of the property after JSON serialization - _allowed_locations: ClassVar[Set[oai.ParameterLocation]] = { - oai.ParameterLocation.QUERY, - oai.ParameterLocation.PATH, - oai.ParameterLocation.COOKIE, - } - default: Optional[str] = field() - python_name: PythonIdentifier - description: Optional[str] = field() - example: Optional[str] = field() - - template: ClassVar[str] = "any_property.py.jinja" - json_is_dict: ClassVar[bool] = False - - def validate_location(self, location: oai.ParameterLocation) -> Optional[ParseError]: - """Returns an error if this type of property is not allowed in the given location""" - if location not in self._allowed_locations: - return ParseError(detail=f"{self.get_type_string()} is not allowed in {location}") - if location == oai.ParameterLocation.PATH and not self.required: - return ParseError(detail="Path parameter must be required") - return None - - def set_python_name(self, new_name: str, config: Config) -> None: - """Mutates this Property to set a new python_name. - - Required to mutate due to how Properties are stored and the difficulty of updating them in-dict. - `new_name` will be validated before it is set, so `python_name` is not guaranteed to equal `new_name` after - calling this. - """ - object.__setattr__(self, "python_name", PythonIdentifier(value=new_name, prefix=config.field_prefix)) - - def get_base_type_string(self, *, quoted: bool = False) -> str: - """Get the string describing the Python type of this property. Base types no require quoting.""" - return f'"{self._type_string}"' if not self.is_base_type and quoted else self._type_string - - def get_base_json_type_string(self, *, quoted: bool = False) -> str: - """Get the string describing the JSON type of this property. Base types no require quoting.""" - return f'"{self._json_type_string}"' if not self.is_base_type and quoted else self._json_type_string - - def get_type_string( - self, - no_optional: bool = False, - json: bool = False, - *, - quoted: bool = False, - ) -> str: - """ - Get a string representation of type that should be used when declaring this property - - Args: - no_optional: Do not include Optional or Unset even if the value is optional (needed for isinstance checks) - json: True if the type refers to the property after JSON serialization - """ - if json: - type_string = self.get_base_json_type_string(quoted=quoted) - else: - type_string = self.get_base_type_string(quoted=quoted) - - if no_optional or (self.required and not self.nullable): - return type_string - if self.required and self.nullable: - return f"Optional[{type_string}]" - if not self.required and self.nullable: - return f"Union[Unset, None, {type_string}]" - - return f"Union[Unset, {type_string}]" - - def get_instance_type_string(self) -> str: - """Get a string representation of runtime type that should be used for `isinstance` checks""" - return self.get_type_string(no_optional=True, quoted=False) - - # noinspection PyUnusedLocal - def get_imports(self, *, prefix: str) -> Set[str]: - """ - Get a set of import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - imports = set() - if self.nullable: - imports.add("from typing import Optional") - if not self.required: - imports.add("from typing import Union") - imports.add(f"from {prefix}types import UNSET, Unset") - return imports - - def get_lazy_imports(self, *, prefix: str) -> Set[str]: - """Get a set of lazy import strings that should be included when this property is used somewhere - - Args: - prefix: A prefix to put before any relative (local) module names. This should be the number of . to get - back to the root of the generated client. - """ - return set() - - def to_string(self) -> str: - """How this should be declared in a dataclass""" - default: Optional[str] - if self.default is not None: - default = self.default - elif not self.required: - default = "UNSET" - else: - default = None - - if default is not None: - return f"{self.python_name}: {self.get_type_string(quoted=True)} = {default}" - return f"{self.python_name}: {self.get_type_string(quoted=True)}" - - def to_docstring(self) -> str: - """Returns property docstring""" - doc = f"{self.python_name} ({self.get_type_string()}): {self.description or ''}" - if self.default: - doc += f" Default: {self.default}." - if self.example: - doc += f" Example: {self.example}." - return doc - - @property - def is_base_type(self) -> bool: - """Base types, represented by any other of `Property` than `ModelProperty` should not be quoted.""" - from . import ListProperty, ModelProperty, UnionProperty - - return self.__class__.__name__ not in { - ModelProperty.__name__, - ListProperty.__name__, - UnionProperty.__name__, - } +from typing import Union + +from typing_extensions import TypeAlias + +from .any import AnyProperty +from .boolean import BooleanProperty +from .const import ConstProperty +from .date import DateProperty +from .datetime import DateTimeProperty +from .enum_property import EnumProperty +from .file import FileProperty +from .float import FloatProperty +from .int import IntProperty +from .list_property import ListProperty +from .model_property import ModelProperty +from .none import NoneProperty +from .string import StringProperty +from .union import UnionProperty + +Property: TypeAlias = Union[ + AnyProperty, + BooleanProperty, + ConstProperty, + DateProperty, + DateTimeProperty, + EnumProperty, + FileProperty, + FloatProperty, + IntProperty, + ListProperty, + ModelProperty, + NoneProperty, + StringProperty, + UnionProperty, +] diff --git a/openapi_python_client/parser/properties/protocol.py b/openapi_python_client/parser/properties/protocol.py new file mode 100644 index 000000000..c7907da98 --- /dev/null +++ b/openapi_python_client/parser/properties/protocol.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +__all__ = ["PropertyProtocol", "Value"] + +from abc import abstractmethod +from typing import TYPE_CHECKING, Any, ClassVar, Protocol, TypeVar + +from ... import Config +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import ParseError, PropertyError + +if TYPE_CHECKING: # pragma: no cover + from .model_property import ModelProperty +else: + ModelProperty = "ModelProperty" + + +class Value(str): + """Represents a valid (converted) value for a property""" + + +PropertyType = TypeVar("PropertyType", bound="PropertyProtocol") + + +class PropertyProtocol(Protocol): + """ + Describes a single property for a schema + + Attributes: + template: Name of the template file (if any) to use for this property. Must be stored in + templates/property_templates and must contain two macros: construct and transform. Construct will be used to + build this property from JSON data (a response from an API). Transform will be used to convert this property + to JSON data (when sending a request to the API). + + Raises: + ValidationError: Raised when the default value fails to be converted to the expected type + """ + + name: str + required: bool + _type_string: ClassVar[str] = "" + _json_type_string: ClassVar[str] = "" # Type of the property after JSON serialization + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + } + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + + template: ClassVar[str] = "any_property.py.jinja" + json_is_dict: ClassVar[bool] = False + + @abstractmethod + def convert_value(self, value: Any) -> Value | None | PropertyError: + """Convert a string value to a Value object""" + raise NotImplementedError() # pragma: no cover + + def validate_location(self, location: oai.ParameterLocation) -> ParseError | None: + """Returns an error if this type of property is not allowed in the given location""" + if location not in self._allowed_locations: + return ParseError(detail=f"{self.get_type_string()} is not allowed in {location}") + if location == oai.ParameterLocation.PATH and not self.required: + return ParseError(detail="Path parameter must be required") + return None + + def set_python_name(self, new_name: str, config: Config) -> None: + """Mutates this Property to set a new python_name. + + Required to mutate due to how Properties are stored and the difficulty of updating them in-dict. + `new_name` will be validated before it is set, so `python_name` is not guaranteed to equal `new_name` after + calling this. + """ + object.__setattr__(self, "python_name", PythonIdentifier(value=new_name, prefix=config.field_prefix)) + + def get_base_type_string(self, *, quoted: bool = False) -> str: + """Get the string describing the Python type of this property. Base types no require quoting.""" + return f'"{self._type_string}"' if not self.is_base_type and quoted else self._type_string + + def get_base_json_type_string(self, *, quoted: bool = False) -> str: + """Get the string describing the JSON type of this property. Base types no require quoting.""" + return f'"{self._json_type_string}"' if not self.is_base_type and quoted else self._json_type_string + + def get_type_string( + self, + no_optional: bool = False, + json: bool = False, + *, + multipart: bool = False, + quoted: bool = False, + ) -> str: + """ + Get a string representation of type that should be used when declaring this property + + Args: + no_optional: Do not include Optional or Unset even if the value is optional (needed for isinstance checks) + json: True if the type refers to the property after JSON serialization + multipart: True if the type should be used in a multipart request + quoted: True if the type should be wrapped in quotes (if not a base type) + """ + if json: + type_string = self.get_base_json_type_string(quoted=quoted) + else: + type_string = self.get_base_type_string(quoted=quoted) + + if no_optional or self.required: + return type_string + return f"Union[Unset, {type_string}]" + + def get_instance_type_string(self) -> str: + """Get a string representation of runtime type that should be used for `isinstance` checks""" + return self.get_type_string(no_optional=True, quoted=False) + + # noinspection PyUnusedLocal + def get_imports(self, *, prefix: str) -> set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = set() + if not self.required: + imports.add("from typing import Union") + imports.add(f"from {prefix}types import UNSET, Unset") + return imports + + def get_lazy_imports(self, *, prefix: str) -> set[str]: + """Get a set of lazy import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + return set() + + def to_string(self) -> str: + """How this should be declared in a dataclass""" + default: str | None + if self.default is not None: + default = self.default + elif not self.required: + default = "UNSET" + else: + default = None + + if default is not None: + return f"{self.python_name}: {self.get_type_string(quoted=True)} = {default}" + return f"{self.python_name}: {self.get_type_string(quoted=True)}" + + def to_docstring(self) -> str: + """Returns property docstring""" + doc = f"{self.python_name} ({self.get_type_string()}): {self.description or ''}" + if self.default: + doc += f" Default: {self.default}." + if self.example: + doc += f" Example: {self.example}." + return doc + + @property + def is_base_type(self) -> bool: + """Base types, represented by any other of `Property` than `ModelProperty` should not be quoted.""" + from . import ListProperty, ModelProperty, UnionProperty + + return self.__class__.__name__ not in { + ModelProperty.__name__, + ListProperty.__name__, + UnionProperty.__name__, + } diff --git a/openapi_python_client/parser/properties/schemas.py b/openapi_python_client/parser/properties/schemas.py index 046c0ca48..9e4fc545e 100644 --- a/openapi_python_client/parser/properties/schemas.py +++ b/openapi_python_client/parser/properties/schemas.py @@ -2,6 +2,7 @@ "Class", "Schemas", "Parameters", + "ReferencePath", "parse_reference_path", "update_schemas_with_data", "update_parameters_with_data", diff --git a/openapi_python_client/parser/properties/string.py b/openapi_python_client/parser/properties/string.py new file mode 100644 index 000000000..9a1603f01 --- /dev/null +++ b/openapi_python_client/parser/properties/string.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import Any, ClassVar, overload + +from attr import define + +from ... import schema as oai +from ... import utils +from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value + + +@define +class StringProperty(PropertyProtocol): + """A property of type str""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + max_length: int | None = None + pattern: str | None = None + _type_string: ClassVar[str] = "str" + _json_type_string: ClassVar[str] = "str" + _allowed_locations: ClassVar[set[oai.ParameterLocation]] = { + oai.ParameterLocation.QUERY, + oai.ParameterLocation.PATH, + oai.ParameterLocation.COOKIE, + oai.ParameterLocation.HEADER, + } + + @classmethod + def build( + cls, + name: str, + required: bool, + default: Any, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + pattern: str | None = None, + ) -> StringProperty | PropertyError: + checked_default = cls.convert_value(default) + return cls( + name=name, + required=required, + default=checked_default, + python_name=python_name, + description=description, + example=example, + pattern=pattern, + ) + + @classmethod + @overload + def convert_value(cls, value: None) -> None: # type: ignore[misc] + ... # pragma: no cover + + @classmethod + @overload + def convert_value(cls, value: Any) -> Value: + ... # pragma: no cover + + @classmethod + def convert_value(cls, value: Any) -> Value | None: + if value is None or isinstance(value, Value): + return value + if not isinstance(value, str): + value = str(value) + return Value(repr(utils.remove_string_escapes(value))) diff --git a/openapi_python_client/parser/properties/union.py b/openapi_python_client/parser/properties/union.py new file mode 100644 index 000000000..a18ad24d2 --- /dev/null +++ b/openapi_python_client/parser/properties/union.py @@ -0,0 +1,178 @@ +from __future__ import annotations + +from itertools import chain +from typing import Any, ClassVar + +from attr import define, evolve + +from ... import Config +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import ParseError, PropertyError +from .protocol import PropertyProtocol, Value +from .schemas import Schemas + + +@define +class UnionProperty(PropertyProtocol): + """A property representing a Union (anyOf) of other properties""" + + name: str + required: bool + default: Value | None + python_name: PythonIdentifier + description: str | None + example: str | None + inner_properties: list[PropertyProtocol] + template: ClassVar[str] = "union_property.py.jinja" + + @classmethod + def build( + cls, *, data: oai.Schema, name: str, required: bool, schemas: Schemas, parent_name: str, config: Config + ) -> tuple[UnionProperty | PropertyError, Schemas]: + """ + Create a `UnionProperty` the right way. + + Args: + data: The `Schema` describing the `UnionProperty`. + name: The name of the property where it appears in the OpenAPI document. + required: Whether this property is required where it's being used. + schemas: The `Schemas` so far describing existing classes / references. + parent_name: The name of the thing which holds this property (used for renaming inner classes). + config: User-defined config values for modifying inner properties. + + Returns: + `(result, schemas)` where `schemas` is the updated version of the input `schemas` and `result` is the + constructed `UnionProperty` or a `PropertyError` describing what went wrong. + """ + from . import property_from_data + + sub_properties: list[PropertyProtocol] = [] + + type_list_data = [] + if isinstance(data.type, list): + for _type in data.type: + type_list_data.append(data.model_copy(update={"type": _type, "default": None})) + + for i, sub_prop_data in enumerate(chain(data.anyOf, data.oneOf, type_list_data)): + sub_prop, schemas = property_from_data( + name=f"{name}_type_{i}", + required=required, + data=sub_prop_data, + schemas=schemas, + parent_name=parent_name, + config=config, + ) + if isinstance(sub_prop, PropertyError): + return PropertyError(detail=f"Invalid property in union {name}", data=sub_prop_data), schemas + sub_properties.append(sub_prop) + + prop = UnionProperty( + name=name, + required=required, + default=None, + inner_properties=sub_properties, + python_name=PythonIdentifier(value=name, prefix=config.field_prefix), + description=data.description, + example=data.example, + ) + default_or_error = prop.convert_value(data.default) + if isinstance(default_or_error, PropertyError): + default_or_error.data = data + return default_or_error, schemas + prop = evolve(prop, default=default_or_error) + return prop, schemas + + def convert_value(self, value: Any) -> Value | None | PropertyError: + if value is None or isinstance(value, Value): + return None + value_or_error: Value | PropertyError | None = PropertyError( + detail=f"Invalid default value for union {self.name}" + ) + for sub_prop in self.inner_properties: + value_or_error = sub_prop.convert_value(value) + if not isinstance(value_or_error, PropertyError): + return value_or_error + return value_or_error + + def _get_inner_type_strings(self, json: bool, multipart: bool) -> set[str]: + return { + p.get_type_string(no_optional=True, json=json, multipart=multipart, quoted=not p.is_base_type) + for p in self.inner_properties + } + + @staticmethod + def _get_type_string_from_inner_type_strings(inner_types: set[str]) -> str: + if len(inner_types) == 1: + return inner_types.pop() + return f"Union[{', '.join(sorted(inner_types))}]" + + def get_base_type_string(self, *, quoted: bool = False) -> str: + return self._get_type_string_from_inner_type_strings(self._get_inner_type_strings(json=False, multipart=False)) + + def get_base_json_type_string(self, *, quoted: bool = False) -> str: + return self._get_type_string_from_inner_type_strings(self._get_inner_type_strings(json=True, multipart=False)) + + def get_type_strings_in_union(self, *, no_optional: bool = False, json: bool, multipart: bool) -> set[str]: + """ + Get the set of all the types that should appear within the `Union` representing this property. + + This function is called from the union property macros, thus the public visibility. + + Args: + no_optional: Do not include `None` or `Unset` in this set. + json: If True, this returns the JSON types, not the Python types, of this property. + multipart: If True, this returns the multipart types, not the Python types, of this property. + + Returns: + A set of strings containing the types that should appear within `Union`. + """ + type_strings = self._get_inner_type_strings(json=json, multipart=multipart) + if no_optional: + return type_strings + if not self.required: + type_strings.add("Unset") + return type_strings + + def get_type_string( + self, + no_optional: bool = False, + json: bool = False, + *, + multipart: bool = False, + quoted: bool = False, + ) -> str: + """ + Get a string representation of type that should be used when declaring this property. + This implementation differs slightly from `Property.get_type_string` in order to collapse + nested union types. + """ + type_strings_in_union = self.get_type_strings_in_union(no_optional=no_optional, json=json, multipart=multipart) + return self._get_type_string_from_inner_type_strings(type_strings_in_union) + + def get_imports(self, *, prefix: str) -> set[str]: + """ + Get a set of import strings that should be included when this property is used somewhere + + Args: + prefix: A prefix to put before any relative (local) module names. This should be the number of . to get + back to the root of the generated client. + """ + imports = super().get_imports(prefix=prefix) + for inner_prop in self.inner_properties: + imports.update(inner_prop.get_imports(prefix=prefix)) + imports.add("from typing import cast, Union") + return imports + + def get_lazy_imports(self, *, prefix: str) -> set[str]: + lazy_imports = super().get_lazy_imports(prefix=prefix) + for inner_prop in self.inner_properties: + lazy_imports.update(inner_prop.get_lazy_imports(prefix=prefix)) + return lazy_imports + + def validate_location(self, location: oai.ParameterLocation) -> ParseError | None: + """Returns an error if this type of property is not allowed in the given location""" + for inner_prop in self.inner_properties: + if inner_prop.validate_location(location) is not None: + return ParseError(detail=f"{self.get_type_string()} is not allowed in {location}") + return None diff --git a/openapi_python_client/parser/responses.py b/openapi_python_client/parser/responses.py index 97909a40c..a8350777f 100644 --- a/openapi_python_client/parser/responses.py +++ b/openapi_python_client/parser/responses.py @@ -68,7 +68,6 @@ def empty_response( prop=AnyProperty( name=response_name, default=None, - nullable=False, required=True, python_name=PythonIdentifier(value=response_name, prefix=config.field_prefix), description=description, diff --git a/openapi_python_client/schema/3.0.3.md b/openapi_python_client/schema/3.0.3.md new file mode 100644 index 000000000..e21aa4655 --- /dev/null +++ b/openapi_python_client/schema/3.0.3.md @@ -0,0 +1,3454 @@ +# OpenAPI Specification + +#### Version 3.0.3 + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://tools.ietf.org/html/bcp14) [RFC2119](https://tools.ietf.org/html/rfc2119) [RFC8174](https://tools.ietf.org/html/rfc8174) when, and only when, they appear in all capitals, as shown here. + +This document is licensed under [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). + +## Introduction + +The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. + +An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases. + +## Table of Contents + + +- [Definitions](#definitions) + - [OpenAPI Document](#oasDocument) + - [Path Templating](#pathTemplating) + - [Media Types](#mediaTypes) + - [HTTP Status Codes](#httpCodes) +- [Specification](#specification) + - [Versions](#versions) + - [Format](#format) + - [Document Structure](#documentStructure) + - [Data Types](#dataTypes) + - [Rich Text Formatting](#richText) + - [Relative References In URLs](#relativeReferences) + - [Schema](#schema) + - [OpenAPI Object](#oasObject) + - [Info Object](#infoObject) + - [Contact Object](#contactObject) + - [License Object](#licenseObject) + - [Server Object](#serverObject) + - [Server Variable Object](#serverVariableObject) + - [Components Object](#componentsObject) + - [Paths Object](#pathsObject) + - [Path Item Object](#pathItemObject) + - [Operation Object](#operationObject) + - [External Documentation Object](#externalDocumentationObject) + - [Parameter Object](#parameterObject) + - [Request Body Object](#requestBodyObject) + - [Media Type Object](#mediaTypeObject) + - [Encoding Object](#encodingObject) + - [Responses Object](#responsesObject) + - [Response Object](#responseObject) + - [Callback Object](#callbackObject) + - [Example Object](#exampleObject) + - [Link Object](#linkObject) + - [Header Object](#headerObject) + - [Tag Object](#tagObject) + - [Reference Object](#referenceObject) + - [Schema Object](#schemaObject) + - [Discriminator Object](#discriminatorObject) + - [XML Object](#xmlObject) + - [Security Scheme Object](#securitySchemeObject) + - [OAuth Flows Object](#oauthFlowsObject) + - [OAuth Flow Object](#oauthFlowObject) + - [Security Requirement Object](#securityRequirementObject) + - [Specification Extensions](#specificationExtensions) + - [Security Filtering](#securityFiltering) +- [Appendix A: Revision History](#revisionHistory) + + + + +## Definitions + +##### OpenAPI Document +A document (or set of documents) that defines or describes an API. An OpenAPI definition uses and conforms to the OpenAPI Specification. + +##### Path Templating +Path templating refers to the usage of template expressions, delimited by curly braces ({}), to mark a section of a URL path as replaceable using path parameters. + +Each template expression in the path MUST correspond to a path parameter that is included in the [Path Item](#path-item-object) itself and/or in each of the Path Item's [Operations](#operation-object). + +##### Media Types +Media type definitions are spread across several resources. +The media type definitions SHOULD be in compliance with [RFC6838](https://tools.ietf.org/html/rfc6838). + +Some examples of possible media type definitions: +``` + text/plain; charset=utf-8 + application/json + application/vnd.github+json + application/vnd.github.v3+json + application/vnd.github.v3.raw+json + application/vnd.github.v3.text+json + application/vnd.github.v3.html+json + application/vnd.github.v3.full+json + application/vnd.github.v3.diff + application/vnd.github.v3.patch +``` +##### HTTP Status Codes +The HTTP Status Codes are used to indicate the status of the executed operation. +The available status codes are defined by [RFC7231](https://tools.ietf.org/html/rfc7231#section-6) and registered status codes are listed in the [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml). + +## Specification + +### Versions + +The OpenAPI Specification is versioned using [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html) (semver) and follows the semver specification. + +The `major`.`minor` portion of the semver (for example `3.0`) SHALL designate the OAS feature set. Typically, *`.patch`* versions address errors in this document, not the feature set. Tooling which supports OAS 3.0 SHOULD be compatible with all OAS 3.0.\* versions. The patch version SHOULD NOT be considered by tooling, making no distinction between `3.0.0` and `3.0.1` for example. + +Each new minor version of the OpenAPI Specification SHALL allow any OpenAPI document that is valid against any previous minor version of the Specification, within the same major version, to be updated to the new Specification version with equivalent semantics. Such an update MUST only require changing the `openapi` property to the new minor version. + +For example, a valid OpenAPI 3.0.2 document, upon changing its `openapi` property to `3.1.0`, SHALL be a valid OpenAPI 3.1.0 document, semantically equivalent to the original OpenAPI 3.0.2 document. New minor versions of the OpenAPI Specification MUST be written to ensure this form of backward compatibility. + +An OpenAPI document compatible with OAS 3.\*.\* contains a required [`openapi`](#oasVersion) field which designates the semantic version of the OAS that it uses. (OAS 2.0 documents contain a top-level version field named [`swagger`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swaggerObject) and value `"2.0"`.) + +### Format + +An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either in JSON or YAML format. + +For example, if a field has an array value, the JSON array representation will be used: + +```json +{ + "field": [ 1, 2, 3 ] +} +``` +All field names in the specification are **case sensitive**. +This includes all fields that are used as keys in a map, except where explicitly noted that keys are **case insensitive**. + +The schema exposes two types of fields: Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name. + +Patterned fields MUST have unique names within the containing object. + +In order to preserve the ability to round-trip between YAML and JSON formats, YAML version [1.2](https://yaml.org/spec/1.2/spec.html) is RECOMMENDED along with some additional constraints: + +- Tags MUST be limited to those allowed by the [JSON Schema ruleset](https://yaml.org/spec/1.2/spec.html#id2803231). +- Keys used in YAML maps MUST be limited to a scalar string, as defined by the [YAML Failsafe schema ruleset](https://yaml.org/spec/1.2/spec.html#id2802346). + +**Note:** While APIs may be defined by OpenAPI documents in either YAML or JSON format, the API request and response bodies and other content are not required to be JSON or YAML. + +### Document Structure + +An OpenAPI document MAY be made up of a single document or be divided into multiple, connected parts at the discretion of the user. In the latter case, `$ref` fields MUST be used in the specification to reference those parts as follows from the [JSON Schema](https://json-schema.org) definitions. + +It is RECOMMENDED that the root OpenAPI document be named: `openapi.json` or `openapi.yaml`. + +### Data Types + +Primitive data types in the OAS are based on the types supported by the [JSON Schema Specification Wright Draft 00](https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2). +Note that `integer` as a type is also supported and is defined as a JSON number without a fraction or exponent part. +`null` is not supported as a type (see [`nullable`](#schemaNullable) for an alternative solution). +Models are defined using the [Schema Object](#schemaObject), which is an extended subset of JSON Schema Specification Wright Draft 00. + +Primitives have an optional modifier property: `format`. +OAS uses several known formats to define in fine detail the data type being used. +However, to support documentation needs, the `format` property is an open `string`-valued property, and can have any value. +Formats such as `"email"`, `"uuid"`, and so on, MAY be used even though undefined by this specification. +Types that are not accompanied by a `format` property follow the type definition in the JSON Schema. Tools that do not recognize a specific `format` MAY default back to the `type` alone, as if the `format` is not specified. + +The formats defined by the OAS are: + +[`type`](#dataTypes) | [`format`](#dataTypeFormat) | Comments +------ | -------- | -------- +`integer` | `int32` | signed 32 bits +`integer` | `int64` | signed 64 bits (a.k.a long) +`number` | `float` | | +`number` | `double` | | +`string` | | | +`string` | `byte` | base64 encoded characters +`string` | `binary` | any sequence of octets +`boolean` | | | +`string` | `date` | As defined by `full-date` - [RFC3339](https://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14) +`string` | `date-time` | As defined by `date-time` - [RFC3339](https://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14) +`string` | `password` | A hint to UIs to obscure input. + + +### Rich Text Formatting +Throughout the specification `description` fields are noted as supporting CommonMark markdown formatting. +Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by [CommonMark 0.27](https://spec.commonmark.org/0.27/). Tooling MAY choose to ignore some CommonMark features to address security concerns. + +### Relative References in URLs + +Unless specified otherwise, all properties that are URLs MAY be relative references as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-4.2). +Relative references are resolved using the URLs defined in the [`Server Object`](#serverObject) as a Base URI. + +Relative references used in `$ref` are processed as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03), using the URL of the current document as the base URI. See also the [Reference Object](#referenceObject). + +### Schema + +In the following description, if a field is not explicitly **REQUIRED** or described with a MUST or SHALL, it can be considered OPTIONAL. + +#### OpenAPI Object + +This is the root document object of the [OpenAPI document](#oasDocument). + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +openapi | `string` | **REQUIRED**. This string MUST be the [semantic version number](https://semver.org/spec/v2.0.0.html) of the [OpenAPI Specification version](#versions) that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document. This is *not* related to the API [`info.version`](#infoVersion) string. +info | [Info Object](#infoObject) | **REQUIRED**. Provides metadata about the API. The metadata MAY be used by tooling as required. +servers | [[Server Object](#serverObject)] | An array of Server Objects, which provide connectivity information to a target server. If the `servers` property is not provided, or is an empty array, the default value would be a [Server Object](#serverObject) with a [url](#serverUrl) value of `/`. +paths | [Paths Object](#pathsObject) | **REQUIRED**. The available paths and operations for the API. +components | [Components Object](#componentsObject) | An element to hold various schemas for the specification. +security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement (`{}`) can be included in the array. +tags | [[Tag Object](#tagObject)] | A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](#operationObject) must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### Info Object + +The object provides metadata about the API. +The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +title | `string` | **REQUIRED**. The title of the API. +description | `string` | A short description of the API. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +termsOfService | `string` | A URL to the Terms of Service for the API. MUST be in the format of a URL. +contact | [Contact Object](#contactObject) | The contact information for the exposed API. +license | [License Object](#licenseObject) | The license information for the exposed API. +version | `string` | **REQUIRED**. The version of the OpenAPI document (which is distinct from the [OpenAPI Specification version](#oasVersion) or the API implementation version). + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Info Object Example + +```json +{ + "title": "Sample Pet Store App", + "description": "This is a sample server for a pet store.", + "termsOfService": "http://example.com/terms/", + "contact": { + "name": "API Support", + "url": "http://www.example.com/support", + "email": "support@example.com" + }, + "license": { + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.1" +} +``` + +```yaml +title: Sample Pet Store App +description: This is a sample server for a pet store. +termsOfService: http://example.com/terms/ +contact: + name: API Support + url: http://www.example.com/support + email: support@example.com +license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +version: 1.0.1 +``` + +#### Contact Object + +Contact information for the exposed API. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +name | `string` | The identifying name of the contact person/organization. +url | `string` | The URL pointing to the contact information. MUST be in the format of a URL. +email | `string` | The email address of the contact person/organization. MUST be in the format of an email address. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Contact Object Example + +```json +{ + "name": "API Support", + "url": "http://www.example.com/support", + "email": "support@example.com" +} +``` + +```yaml +name: API Support +url: http://www.example.com/support +email: support@example.com +``` + +#### License Object + +License information for the exposed API. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The license name used for the API. +url | `string` | A URL to the license used for the API. MUST be in the format of a URL. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### License Object Example + +```json +{ + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html" +} +``` + +```yaml +name: Apache 2.0 +url: https://www.apache.org/licenses/LICENSE-2.0.html +``` + +#### Server Object + +An object representing a Server. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +url | `string` | **REQUIRED**. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{`brackets`}`. +description | `string` | An optional string describing the host designated by the URL. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +variables | Map[`string`, [Server Variable Object](#serverVariableObject)] | A map between a variable name and its value. The value is used for substitution in the server's URL template. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Server Object Example + +A single server would be described as: + +```json +{ + "url": "https://development.gigantic-server.com/v1", + "description": "Development server" +} +``` + +```yaml +url: https://development.gigantic-server.com/v1 +description: Development server +``` + +The following shows how multiple servers can be described, for example, at the OpenAPI Object's [`servers`](#oasServers): + +```json +{ + "servers": [ + { + "url": "https://development.gigantic-server.com/v1", + "description": "Development server" + }, + { + "url": "https://staging.gigantic-server.com/v1", + "description": "Staging server" + }, + { + "url": "https://api.gigantic-server.com/v1", + "description": "Production server" + } + ] +} +``` + +```yaml +servers: +- url: https://development.gigantic-server.com/v1 + description: Development server +- url: https://staging.gigantic-server.com/v1 + description: Staging server +- url: https://api.gigantic-server.com/v1 + description: Production server +``` + +The following shows how variables can be used for a server configuration: + +```json +{ + "servers": [ + { + "url": "https://{username}.gigantic-server.com:{port}/{basePath}", + "description": "The production API server", + "variables": { + "username": { + "default": "demo", + "description": "this value is assigned by the service provider, in this example `gigantic-server.com`" + }, + "port": { + "enum": [ + "8443", + "443" + ], + "default": "8443" + }, + "basePath": { + "default": "v2" + } + } + } + ] +} +``` + +```yaml +servers: +- url: https://{username}.gigantic-server.com:{port}/{basePath} + description: The production API server + variables: + username: + # note! no enum here means it is an open value + default: demo + description: this value is assigned by the service provider, in this example `gigantic-server.com` + port: + enum: + - '8443' + - '443' + default: '8443' + basePath: + # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2` + default: v2 +``` + + +#### Server Variable Object + +An object representing a Server Variable for server URL template substitution. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +enum | [`string`] | An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty. +default | `string` | **REQUIRED**. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. Note this behavior is different than the [Schema Object's](#schemaObject) treatment of default values, because in those cases parameter values are optional. If the [`enum`](#serverVariableEnum) is defined, the value SHOULD exist in the enum's values. +description | `string` | An optional description for the server variable. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### Components Object + +Holds a set of reusable objects for different aspects of the OAS. +All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. + + +##### Fixed Fields + +Field Name | Type | Description +---|:---|--- + schemas | Map[`string`, [Schema Object](#schemaObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Schema Objects](#schemaObject). + responses | Map[`string`, [Response Object](#responseObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Response Objects](#responseObject). + parameters | Map[`string`, [Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Parameter Objects](#parameterObject). + examples | Map[`string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Example Objects](#exampleObject). + requestBodies | Map[`string`, [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Request Body Objects](#requestBodyObject). + headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Header Objects](#headerObject). + securitySchemes| Map[`string`, [Security Scheme Object](#securitySchemeObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Security Scheme Objects](#securitySchemeObject). + links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Link Objects](#linkObject). + callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Callback Objects](#callbackObject). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`. + +Field Name Examples: + +``` +User +User_1 +User_Name +user-name +my.org.User +``` + +##### Components Object Example + +```json +"components": { + "schemas": { + "GeneralError": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + } + }, + "parameters": { + "skipParam": { + "name": "skip", + "in": "query", + "description": "number of items to skip", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + } + }, + "limitParam": { + "name": "limit", + "in": "query", + "description": "max records to return", + "required": true, + "schema" : { + "type": "integer", + "format": "int32" + } + } + }, + "responses": { + "NotFound": { + "description": "Entity not found." + }, + "IllegalInput": { + "description": "Illegal input for operation." + }, + "GeneralError": { + "description": "General Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GeneralError" + } + } + } + } + }, + "securitySchemes": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "http://example.org/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } + } + } +} +``` + +```yaml +components: + schemas: + GeneralError: + type: object + properties: + code: + type: integer + format: int32 + message: + type: string + Category: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + parameters: + skipParam: + name: skip + in: query + description: number of items to skip + required: true + schema: + type: integer + format: int32 + limitParam: + name: limit + in: query + description: max records to return + required: true + schema: + type: integer + format: int32 + responses: + NotFound: + description: Entity not found. + IllegalInput: + description: Illegal input for operation. + GeneralError: + description: General Error + content: + application/json: + schema: + $ref: '#/components/schemas/GeneralError' + securitySchemes: + api_key: + type: apiKey + name: api_key + in: header + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: http://example.org/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + + +#### Paths Object + +Holds the relative paths to the individual endpoints and their operations. +The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. The Paths MAY be empty, due to [ACL constraints](#securityFiltering). + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +/{path} | [Path Item Object](#pathItemObject) | A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is **appended** (no relative URL resolution) to the expanded URL from the [`Server Object`](#serverObject)'s `url` field in order to construct the full URL. [Path templating](#pathTemplating) is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Path Templating Matching + +Assuming the following paths, the concrete definition, `/pets/mine`, will be matched first if used: + +``` + /pets/{petId} + /pets/mine +``` + +The following paths are considered identical and invalid: + +``` + /pets/{petId} + /pets/{name} +``` + +The following may lead to ambiguous resolution: + +``` + /{entity}/me + /books/{id} +``` + +##### Paths Object Example + +```json +{ + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "responses": { + "200": { + "description": "A list of pets.", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/pet" + } + } + } + } + } + } + } + } +} +``` + +```yaml +/pets: + get: + description: Returns all pets from the system that the user has access to + responses: + '200': + description: A list of pets. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/pet' +``` + +#### Path Item Object + +Describes the operations available on a single path. +A Path Item MAY be empty, due to [ACL constraints](#securityFiltering). +The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +$ref | `string` | Allows for an external definition of this path item. The referenced structure MUST be in the format of a [Path Item Object](#pathItemObject). In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. +summary| `string` | An optional, string summary, intended to apply to all operations in this path. +description | `string` | An optional, string description, intended to apply to all operations in this path. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +get | [Operation Object](#operationObject) | A definition of a GET operation on this path. +put | [Operation Object](#operationObject) | A definition of a PUT operation on this path. +post | [Operation Object](#operationObject) | A definition of a POST operation on this path. +delete | [Operation Object](#operationObject) | A definition of a DELETE operation on this path. +options | [Operation Object](#operationObject) | A definition of a OPTIONS operation on this path. +head | [Operation Object](#operationObject) | A definition of a HEAD operation on this path. +patch | [Operation Object](#operationObject) | A definition of a PATCH operation on this path. +trace | [Operation Object](#operationObject) | A definition of a TRACE operation on this path. +servers | [[Server Object](#serverObject)] | An alternative `server` array to service all operations in this path. +parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Path Item Object Example + +```json +{ + "get": { + "description": "Returns pets based on ID", + "summary": "Find pets by ID", + "operationId": "getPetsById", + "responses": { + "200": { + "description": "pet response", + "content": { + "*/*": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Pet" + } + } + } + } + }, + "default": { + "description": "error payload", + "content": { + "text/html": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to use", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "simple" + } + ] +} +``` + +```yaml +get: + description: Returns pets based on ID + summary: Find pets by ID + operationId: getPetsById + responses: + '200': + description: pet response + content: + '*/*' : + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + default: + description: error payload + content: + 'text/html': + schema: + $ref: '#/components/schemas/ErrorModel' +parameters: +- name: id + in: path + description: ID of pet to use + required: true + schema: + type: array + items: + type: string + style: simple +``` + +#### Operation Object + +Describes a single API operation on a path. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +tags | [`string`] | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. +summary | `string` | A short summary of what the operation does. +description | `string` | A verbose explanation of the operation behavior. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this operation. +operationId | `string` | Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is **case-sensitive**. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. +parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for this operation. If a parameter is already defined at the [Path Item](#pathItemParameters), the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). +requestBody | [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject) | The request body applicable for this operation. The `requestBody` is only supported in HTTP methods where the HTTP 1.1 specification [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, `requestBody` SHALL be ignored by consumers. +responses | [Responses Object](#responsesObject) | **REQUIRED**. The list of possible responses as they are returned from executing this operation. +callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a [Callback Object](#callbackObject) that describes a request that may be initiated by the API provider and the expected responses. +deprecated | `boolean` | Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`. +security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level [`security`](#oasSecurity). To remove a top-level security declaration, an empty array can be used. +servers | [[Server Object](#serverObject)] | An alternative `server` array to service this operation. If an alternative `server` object is specified at the Path Item Object or Root level, it will be overridden by this value. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Operation Object Example + +```json +{ + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "operationId": "updatePetWithForm", + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "Updated name of the pet", + "type": "string" + }, + "status": { + "description": "Updated status of the pet", + "type": "string" + } + }, + "required": ["status"] + } + } + } + }, + "responses": { + "200": { + "description": "Pet updated.", + "content": { + "application/json": {}, + "application/xml": {} + } + }, + "405": { + "description": "Method Not Allowed", + "content": { + "application/json": {}, + "application/xml": {} + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] +} +``` + +```yaml +tags: +- pet +summary: Updates a pet in the store with form data +operationId: updatePetWithForm +parameters: +- name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: string +requestBody: + content: + 'application/x-www-form-urlencoded': + schema: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + required: + - status +responses: + '200': + description: Pet updated. + content: + 'application/json': {} + 'application/xml': {} + '405': + description: Method Not Allowed + content: + 'application/json': {} + 'application/xml': {} +security: +- petstore_auth: + - write:pets + - read:pets +``` + + +#### External Documentation Object + +Allows referencing an external resource for extended documentation. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +description | `string` | A short description of the target documentation. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +url | `string` | **REQUIRED**. The URL for the target documentation. Value MUST be in the format of a URL. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### External Documentation Object Example + +```json +{ + "description": "Find more info here", + "url": "https://example.com" +} +``` + +```yaml +description: Find more info here +url: https://example.com +``` + +#### Parameter Object + +Describes a single operation parameter. + +A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). + +##### Parameter Locations +There are four possible parameter locations specified by the `in` field: +* path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. +* query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. +* header - Custom headers that are expected as part of the request. Note that [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. +* cookie - Used to pass a specific cookie value to the API. + + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The name of the parameter. Parameter names are *case sensitive*.
  • If [`in`](#parameterIn) is `"path"`, the `name` field MUST correspond to a template expression occurring within the [path](#pathsPath) field in the [Paths Object](#pathsObject). See [Path Templating](#pathTemplating) for further information.
  • If [`in`](#parameterIn) is `"header"` and the `name` field is `"Accept"`, `"Content-Type"` or `"Authorization"`, the parameter definition SHALL be ignored.
  • For all other cases, the `name` corresponds to the parameter name used by the [`in`](#parameterIn) property.
+in | `string` | **REQUIRED**. The location of the parameter. Possible values are `"query"`, `"header"`, `"path"` or `"cookie"`. +description | `string` | A brief description of the parameter. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +required | `boolean` | Determines whether this parameter is mandatory. If the [parameter location](#parameterIn) is `"path"`, this property is **REQUIRED** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. + deprecated | `boolean` | Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`. + allowEmptyValue | `boolean` | Sets the ability to pass empty-valued parameters. This is valid only for `query` parameters and allows sending a parameter with an empty value. Default value is `false`. If [`style`](#parameterStyle) is used, and if behavior is `n/a` (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision. + +The rules for serialization of the parameter are specified in one of two ways. +For simpler scenarios, a [`schema`](#parameterSchema) and [`style`](#parameterStyle) can describe the structure and syntax of the parameter. + +Field Name | Type | Description +---|:---:|--- +style | `string` | Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `query` - `form`; for `path` - `simple`; for `header` - `simple`; for `cookie` - `form`. +explode | `boolean` | When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this property has no effect. When [`style`](#parameterStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. +allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. This property only applies to parameters with an `in` value of `query`. The default value is `false`. +schema | [Schema Object](#schemaObject) \| [Reference Object](#referenceObject) | The schema defining the type used for the parameter. +example | Any | Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` that contains an example, the `example` value SHALL _override_ the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary. +examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` that contains an example, the `examples` value SHALL _override_ the example provided by the schema. + +For more complex scenarios, the [`content`](#parameterContent) property can define the media type and schema of the parameter. +A parameter MUST contain either a `schema` property, or a `content` property, but not both. +When `example` or `examples` are provided in conjunction with the `schema` object, the example MUST follow the prescribed serialization strategy for the parameter. + + +Field Name | Type | Description +---|:---:|--- +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. + +##### Style Values + +In order to support common ways of serializing simple parameters, a set of `style` values are defined. + +`style` | [`type`](#dataTypes) | `in` | Comments +----------- | ------ | -------- | -------- +matrix | `primitive`, `array`, `object` | `path` | Path-style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7) +label | `primitive`, `array`, `object` | `path` | Label style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.5) +form | `primitive`, `array`, `object` | `query`, `cookie` | Form style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.8). This option replaces `collectionFormat` with a `csv` (when `explode` is false) or `multi` (when `explode` is true) value from OpenAPI 2.0. +simple | `array` | `path`, `header` | Simple style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.2). This option replaces `collectionFormat` with a `csv` value from OpenAPI 2.0. +spaceDelimited | `array` | `query` | Space separated array values. This option replaces `collectionFormat` equal to `ssv` from OpenAPI 2.0. +pipeDelimited | `array` | `query` | Pipe separated array values. This option replaces `collectionFormat` equal to `pipes` from OpenAPI 2.0. +deepObject | `object` | `query` | Provides a simple way of rendering nested objects using form parameters. + + +##### Style Examples + +Assume a parameter named `color` has one of the following values: + +``` + string -> "blue" + array -> ["blue","black","brown"] + object -> { "R": 100, "G": 200, "B": 150 } +``` +The following table shows examples of rendering differences for each value. + +[`style`](#dataTypeFormat) | `explode` | `empty` | `string` | `array` | `object` +----------- | ------ | -------- | -------- | -------- | ------- +matrix | false | ;color | ;color=blue | ;color=blue,black,brown | ;color=R,100,G,200,B,150 +matrix | true | ;color | ;color=blue | ;color=blue;color=black;color=brown | ;R=100;G=200;B=150 +label | false | . | .blue | .blue.black.brown | .R.100.G.200.B.150 +label | true | . | .blue | .blue.black.brown | .R=100.G=200.B=150 +form | false | color= | color=blue | color=blue,black,brown | color=R,100,G,200,B,150 +form | true | color= | color=blue | color=blue&color=black&color=brown | R=100&G=200&B=150 +simple | false | n/a | blue | blue,black,brown | R,100,G,200,B,150 +simple | true | n/a | blue | blue,black,brown | R=100,G=200,B=150 +spaceDelimited | false | n/a | n/a | blue%20black%20brown | R%20100%20G%20200%20B%20150 +pipeDelimited | false | n/a | n/a | blue\|black\|brown | R\|100\|G\|200\|B\|150 +deepObject | true | n/a | n/a | n/a | color[R]=100&color[G]=200&color[B]=150 + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Parameter Object Examples + +A header parameter with an array of 64 bit integer numbers: + +```json +{ + "name": "token", + "in": "header", + "description": "token to be passed as a header", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int64" + } + }, + "style": "simple" +} +``` + +```yaml +name: token +in: header +description: token to be passed as a header +required: true +schema: + type: array + items: + type: integer + format: int64 +style: simple +``` + +A path parameter of a string value: +```json +{ + "name": "username", + "in": "path", + "description": "username to fetch", + "required": true, + "schema": { + "type": "string" + } +} +``` + +```yaml +name: username +in: path +description: username to fetch +required: true +schema: + type: string +``` + +An optional query parameter of a string value, allowing multiple values by repeating the query parameter: +```json +{ + "name": "id", + "in": "query", + "description": "ID of the object to fetch", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "form", + "explode": true +} +``` + +```yaml +name: id +in: query +description: ID of the object to fetch +required: false +schema: + type: array + items: + type: string +style: form +explode: true +``` + +A free-form query parameter, allowing undefined parameters of a specific type: +```json +{ + "in": "query", + "name": "freeForm", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer" + }, + }, + "style": "form" +} +``` + +```yaml +in: query +name: freeForm +schema: + type: object + additionalProperties: + type: integer +style: form +``` + +A complex parameter using `content` to define serialization: + +```json +{ + "in": "query", + "name": "coordinates", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "lat", + "long" + ], + "properties": { + "lat": { + "type": "number" + }, + "long": { + "type": "number" + } + } + } + } + } +} +``` + +```yaml +in: query +name: coordinates +content: + application/json: + schema: + type: object + required: + - lat + - long + properties: + lat: + type: number + long: + type: number +``` + +#### Request Body Object + +Describes a single request body. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +description | `string` | A brief description of the request body. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | **REQUIRED**. The content of the request body. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* +required | `boolean` | Determines if the request body is required in the request. Defaults to `false`. + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Request Body Examples + +A request body with a referenced model definition. +```json +{ + "description": "user to add to the system", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + }, + "examples": { + "user" : { + "summary": "User Example", + "externalValue": "http://foo.bar/examples/user-example.json" + } + } + }, + "application/xml": { + "schema": { + "$ref": "#/components/schemas/User" + }, + "examples": { + "user" : { + "summary": "User example in XML", + "externalValue": "http://foo.bar/examples/user-example.xml" + } + } + }, + "text/plain": { + "examples": { + "user" : { + "summary": "User example in Plain text", + "externalValue": "http://foo.bar/examples/user-example.txt" + } + } + }, + "*/*": { + "examples": { + "user" : { + "summary": "User example in other format", + "externalValue": "http://foo.bar/examples/user-example.whatever" + } + } + } + } +} +``` + +```yaml +description: user to add to the system +content: + 'application/json': + schema: + $ref: '#/components/schemas/User' + examples: + user: + summary: User Example + externalValue: 'http://foo.bar/examples/user-example.json' + 'application/xml': + schema: + $ref: '#/components/schemas/User' + examples: + user: + summary: User Example in XML + externalValue: 'http://foo.bar/examples/user-example.xml' + 'text/plain': + examples: + user: + summary: User example in text plain format + externalValue: 'http://foo.bar/examples/user-example.txt' + '*/*': + examples: + user: + summary: User example in other format + externalValue: 'http://foo.bar/examples/user-example.whatever' +``` + +A body parameter that is an array of string values: +```json +{ + "description": "user to add to the system", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + } +} +``` + +```yaml +description: user to add to the system +required: true +content: + text/plain: + schema: + type: array + items: + type: string +``` + + +#### Media Type Object +Each Media Type Object provides schema and examples for the media type identified by its key. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +schema | [Schema Object](#schemaObject) \| [Reference Object](#referenceObject) | The schema defining the content of the request, response, or parameter. +example | Any | Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` which contains an example, the `example` value SHALL _override_ the example provided by the schema. +examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` which contains an example, the `examples` value SHALL _override_ the example provided by the schema. +encoding | Map[`string`, [Encoding Object](#encodingObject)] | A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to `requestBody` objects when the media type is `multipart` or `application/x-www-form-urlencoded`. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Media Type Examples + +```json +{ + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pet" + }, + "examples": { + "cat" : { + "summary": "An example of a cat", + "value": + { + "name": "Fluffy", + "petType": "Cat", + "color": "White", + "gender": "male", + "breed": "Persian" + } + }, + "dog": { + "summary": "An example of a dog with a cat's name", + "value" : { + "name": "Puma", + "petType": "Dog", + "color": "Black", + "gender": "Female", + "breed": "Mixed" + }, + "frog": { + "$ref": "#/components/examples/frog-example" + } + } + } + } +} +``` + +```yaml +application/json: + schema: + $ref: "#/components/schemas/Pet" + examples: + cat: + summary: An example of a cat + value: + name: Fluffy + petType: Cat + color: White + gender: male + breed: Persian + dog: + summary: An example of a dog with a cat's name + value: + name: Puma + petType: Dog + color: Black + gender: Female + breed: Mixed + frog: + $ref: "#/components/examples/frog-example" +``` + +##### Considerations for File Uploads + +In contrast with the 2.0 specification, `file` input/output content in OpenAPI is described with the same semantics as any other schema type. Specifically: + +```yaml +# content transferred with base64 encoding +schema: + type: string + format: base64 +``` + +```yaml +# content transferred in binary (octet-stream): +schema: + type: string + format: binary +``` + +These examples apply to either input payloads of file uploads or response payloads. + +A `requestBody` for submitting a file in a `POST` operation may look like the following example: + +```yaml +requestBody: + content: + application/octet-stream: + schema: + # a binary file of any type + type: string + format: binary +``` + +In addition, specific media types MAY be specified: + +```yaml +# multiple, specific media types may be specified: +requestBody: + content: + # a binary file of type png or jpeg + 'image/jpeg': + schema: + type: string + format: binary + 'image/png': + schema: + type: string + format: binary +``` + +To upload multiple files, a `multipart` media type MUST be used: + +```yaml +requestBody: + content: + multipart/form-data: + schema: + properties: + # The property name 'file' will be used for all files. + file: + type: array + items: + type: string + format: binary + +``` + +##### Support for x-www-form-urlencoded Request Bodies + +To submit content using form url encoding via [RFC1866](https://tools.ietf.org/html/rfc1866), the following +definition may be used: + +```yaml +requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + # complex types are stringified to support RFC 1866 + type: object + properties: {} +``` + +In this example, the contents in the `requestBody` MUST be stringified per [RFC1866](https://tools.ietf.org/html/rfc1866/) when passed to the server. In addition, the `address` field complex object will be stringified. + +When passing complex objects in the `application/x-www-form-urlencoded` content type, the default serialization strategy of such properties is described in the [`Encoding Object`](#encodingObject)'s [`style`](#encodingStyle) property as `form`. + +##### Special Considerations for `multipart` Content + +It is common to use `multipart/form-data` as a `Content-Type` when transferring request bodies to operations. In contrast to 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content. This supports complex structures as well as supporting mechanisms for multiple file uploads. + +When passing in `multipart` types, boundaries MAY be used to separate sections of the content being transferred — thus, the following default `Content-Type`s are defined for `multipart`: + +* If the property is a primitive, or an array of primitive values, the default Content-Type is `text/plain` +* If the property is complex, or an array of complex values, the default Content-Type is `application/json` +* If the property is a `type: string` with `format: binary` or `format: base64` (aka a file object), the default Content-Type is `application/octet-stream` + + +Examples: + +```yaml +requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + # default Content-Type for objects is `application/json` + type: object + properties: {} + profileImage: + # default Content-Type for string/binary is `application/octet-stream` + type: string + format: binary + children: + # default Content-Type for arrays is based on the `inner` type (text/plain here) + type: array + items: + type: string + addresses: + # default Content-Type for arrays is based on the `inner` type (object shown, so `application/json` in this example) + type: array + items: + type: '#/components/schemas/Address' +``` + +An `encoding` attribute is introduced to give you control over the serialization of parts of `multipart` request bodies. This attribute is _only_ applicable to `multipart` and `application/x-www-form-urlencoded` request bodies. + +#### Encoding Object + +A single encoding definition applied to a single schema property. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +contentType | `string` | The Content-Type for encoding a specific property. Default value depends on the property type: for `string` with `format` being `binary` – `application/octet-stream`; for other primitive types – `text/plain`; for `object` - `application/json`; for `array` – the default is defined based on the inner type. The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or a comma-separated list of the two types. +headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | A map allowing additional information to be provided as headers, for example `Content-Disposition`. `Content-Type` is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a `multipart`. +style | `string` | Describes how a specific property value will be serialized depending on its type. See [Parameter Object](#parameterObject) for details on the [`style`](#parameterStyle) property. The behavior follows the same values as `query` parameters, including default values. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. +explode | `boolean` | When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When [`style`](#encodingStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. +allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Encoding Object Example + +```yaml +requestBody: + content: + multipart/mixed: + schema: + type: object + properties: + id: + # default is text/plain + type: string + format: uuid + address: + # default is application/json + type: object + properties: {} + historyMetadata: + # need to declare XML format! + description: metadata in XML format + type: object + properties: {} + profileImage: + # default is application/octet-stream, need to declare an image type only! + type: string + format: binary + encoding: + historyMetadata: + # require XML Content-Type in utf-8 encoding + contentType: application/xml; charset=utf-8 + profileImage: + # only accept png/jpeg + contentType: image/png, image/jpeg + headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer +``` + +#### Responses Object + +A container for the expected responses of an operation. +The container maps a HTTP response code to the expected response. + +The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. +However, documentation is expected to cover a successful operation response and any known errors. + +The `default` MAY be used as a default response object for all HTTP codes +that are not covered individually by the specification. + +The `Responses Object` MUST contain at least one response code, and it +SHOULD be the response for a successful operation call. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +default | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. A [Reference Object](#referenceObject) can link to a response that the [OpenAPI Object's components/responses](#componentsResponses) section defines. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +[HTTP Status Code](#httpCodes) | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | Any [HTTP status code](#httpCodes) can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. A [Reference Object](#referenceObject) can link to a response that is defined in the [OpenAPI Object's components/responses](#componentsResponses) section. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `[200-299]`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Responses Object Example + +A 200 response for a successful operation and a default response for others (implying an error): + +```json +{ + "200": { + "description": "a pet to be returned", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pet" + } + } + } + }, + "default": { + "description": "Unexpected error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } +} +``` + +```yaml +'200': + description: a pet to be returned + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +default: + description: Unexpected error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorModel' +``` + +#### Response Object +Describes a single response from an API Operation, including design-time, static +`links` to operations based on the response. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +description | `string` | **REQUIRED**. A short description of the response. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | Maps a header name to its definition. [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL be ignored. +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing descriptions of potential response payloads. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* +links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for [Component Objects](#componentsObject). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Response Object Examples + +Response of an array of a complex type: + +```json +{ + "description": "A complex object array response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VeryComplexType" + } + } + } + } +} +``` + +```yaml +description: A complex object array response +content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/VeryComplexType' +``` + +Response with a string type: + +```json +{ + "description": "A simple string response", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + +} +``` + +```yaml +description: A simple string response +content: + text/plain: + schema: + type: string +``` + +Plain text response with headers: + +```json +{ + "description": "A simple string response", + "content": { + "text/plain": { + "schema": { + "type": "string", + "example": "whoa!" + } + } + }, + "headers": { + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Remaining": { + "description": "The number of remaining requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Reset": { + "description": "The number of seconds left in the current period", + "schema": { + "type": "integer" + } + } + } +} +``` + +```yaml +description: A simple string response +content: + text/plain: + schema: + type: string + example: 'whoa!' +headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer + X-Rate-Limit-Remaining: + description: The number of remaining requests in the current period + schema: + type: integer + X-Rate-Limit-Reset: + description: The number of seconds left in the current period + schema: + type: integer +``` + +Response with no return value: + +```json +{ + "description": "object created" +} +``` + +```yaml +description: object created +``` + +#### Callback Object + +A map of possible out-of band callbacks related to the parent operation. +Each value in the map is a [Path Item Object](#pathItemObject) that describes a set of requests that may be initiated by the API provider and the expected responses. +The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +{expression} | [Path Item Object](#pathItemObject) | A Path Item Object used to define a callback request and expected responses. A [complete example](../examples/v3.0/callback-example.yaml) is available. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Key Expression + +The key that identifies the [Path Item Object](#pathItemObject) is a [runtime expression](#runtimeExpression) that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. +A simple example might be `$request.body#/url`. +However, using a [runtime expression](#runtimeExpression) the complete HTTP message can be accessed. +This includes accessing any part of a body that a JSON Pointer [RFC6901](https://tools.ietf.org/html/rfc6901) can reference. + +For example, given the following HTTP request: + +```http +POST /subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning HTTP/1.1 +Host: example.org +Content-Type: application/json +Content-Length: 187 + +{ + "failedUrl" : "http://clientdomain.com/failed", + "successUrls" : [ + "http://clientdomain.com/fast", + "http://clientdomain.com/medium", + "http://clientdomain.com/slow" + ] +} + +201 Created +Location: http://example.org/subscription/1 +``` + +The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named `eventType` and a query parameter named `queryUrl`. + +Expression | Value +---|:--- +$url | http://example.org/subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning +$method | POST +$request.path.eventType | myevent +$request.query.queryUrl | http://clientdomain.com/stillrunning +$request.header.content-Type | application/json +$request.body#/failedUrl | http://clientdomain.com/failed +$request.body#/successUrls/2 | http://clientdomain.com/medium +$response.header.Location | http://example.org/subscription/1 + + +##### Callback Object Examples + +The following example uses the user provided `queryUrl` query string parameter to define the callback URL. This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook. + +```yaml +myCallback: + '{$request.query.queryUrl}': + post: + requestBody: + description: Callback payload + content: + 'application/json': + schema: + $ref: '#/components/schemas/SomePayload' + responses: + '200': + description: callback successfully processed +``` + +The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the `id` and `email` property in the request body. + +```yaml +transactionCallback: + 'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}': + post: + requestBody: + description: Callback payload + content: + 'application/json': + schema: + $ref: '#/components/schemas/SomePayload' + responses: + '200': + description: callback successfully processed +``` + +#### Example Object + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +summary | `string` | Short description for the example. +description | `string` | Long description for the example. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +value | Any | Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary. +externalValue | `string` | A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +In all cases, the example value is expected to be compatible with the type schema +of its associated value. Tooling implementations MAY choose to +validate compatibility automatically, and reject the example value(s) if incompatible. + +##### Example Object Examples + +In a request body: + +```yaml +requestBody: + content: + 'application/json': + schema: + $ref: '#/components/schemas/Address' + examples: + foo: + summary: A foo example + value: {"foo": "bar"} + bar: + summary: A bar example + value: {"bar": "baz"} + 'application/xml': + examples: + xmlExample: + summary: This is an example in XML + externalValue: 'http://example.org/examples/address-example.xml' + 'text/plain': + examples: + textExample: + summary: This is a text example + externalValue: 'http://foo.bar/examples/address-example.txt' +``` + +In a parameter: + +```yaml +parameters: + - name: 'zipCode' + in: 'query' + schema: + type: 'string' + format: 'zip-code' + examples: + zip-example: + $ref: '#/components/examples/zip-example' +``` + +In a response: + +```yaml +responses: + '200': + description: your car appointment has been booked + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessResponse' + examples: + confirmation-success: + $ref: '#/components/examples/confirmation-success' +``` + + +#### Link Object + +The `Link object` represents a possible design-time link for a response. +The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. + +Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. + +For computing links, and providing instructions to execute them, a [runtime expression](#runtimeExpression) is used for accessing values in an operation and using them as parameters while invoking the linked operation. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +operationRef | `string` | A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an [Operation Object](#operationObject). Relative `operationRef` values MAY be used to locate an existing [Operation Object](#operationObject) in the OpenAPI definition. +operationId | `string` | The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field. +parameters | Map[`string`, Any \| [{expression}](#runtimeExpression)] | A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the [parameter location](#parameterIn) `[{in}.]{name}` for operations that use the same parameter name in different locations (e.g. path.id). +requestBody | Any \| [{expression}](#runtimeExpression) | A literal value or [{expression}](#runtimeExpression) to use as a request body when calling the target operation. +description | `string` | A description of the link. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +server | [Server Object](#serverObject) | A server object to be used by the target operation. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +A linked operation MUST be identified using either an `operationRef` or `operationId`. +In the case of an `operationId`, it MUST be unique and resolved in the scope of the OAS document. +Because of the potential for name clashes, the `operationRef` syntax is preferred +for specifications with external references. + +##### Examples + +Computing a link from a request operation where the `$request.path.id` is used to pass a request parameter to the linked operation. + +```yaml +paths: + /users/{id}: + parameters: + - name: id + in: path + required: true + description: the user identifier, as userId + schema: + type: string + get: + responses: + '200': + description: the user being returned + content: + application/json: + schema: + type: object + properties: + uuid: # the unique user id + type: string + format: uuid + links: + address: + # the target link operationId + operationId: getUserAddress + parameters: + # get the `id` field from the request path parameter named `id` + userId: $request.path.id + # the path item of the linked operation + /users/{userid}/address: + parameters: + - name: userid + in: path + required: true + description: the user identifier, as userId + schema: + type: string + # linked operation + get: + operationId: getUserAddress + responses: + '200': + description: the user's address +``` + +When a runtime expression fails to evaluate, no parameter value is passed to the target operation. + +Values from the response body can be used to drive a linked operation. + +```yaml +links: + address: + operationId: getUserAddressByUUID + parameters: + # get the `uuid` field from the `uuid` field in the response body + userUuid: $response.body#/uuid +``` + +Clients follow all links at their discretion. +Neither permissions, nor the capability to make a successful call to that link, is guaranteed +solely by the existence of a relationship. + + +##### OperationRef Examples + +As references to `operationId` MAY NOT be possible (the `operationId` is an optional +field in an [Operation Object](#operationObject)), references MAY also be made through a relative `operationRef`: + +```yaml +links: + UserRepositories: + # returns array of '#/components/schemas/repository' + operationRef: '#/paths/~12.0~1repositories~1{username}/get' + parameters: + username: $response.body#/username +``` + +or an absolute `operationRef`: + +```yaml +links: + UserRepositories: + # returns array of '#/components/schemas/repository' + operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get' + parameters: + username: $response.body#/username +``` + +Note that in the use of `operationRef`, the _escaped forward-slash_ is necessary when +using JSON references. + + +##### Runtime Expressions + +Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. +This mechanism is used by [Link Objects](#linkObject) and [Callback Objects](#callbackObject). + +The runtime expression is defined by the following [ABNF](https://tools.ietf.org/html/rfc5234) syntax + +```abnf + expression = ( "$url" / "$method" / "$statusCode" / "$request." source / "$response." source ) + source = ( header-reference / query-reference / path-reference / body-reference ) + header-reference = "header." token + query-reference = "query." name + path-reference = "path." name + body-reference = "body" ["#" json-pointer ] + json-pointer = *( "/" reference-token ) + reference-token = *( unescaped / escaped ) + unescaped = %x00-2E / %x30-7D / %x7F-10FFFF + ; %x2F ('/') and %x7E ('~') are excluded from 'unescaped' + escaped = "~" ( "0" / "1" ) + ; representing '~' and '/', respectively + name = *( CHAR ) + token = 1*tchar + tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / + "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA +``` + +Here, `json-pointer` is taken from [RFC 6901](https://tools.ietf.org/html/rfc6901), `char` from [RFC 7159](https://tools.ietf.org/html/rfc7159#section-7) and `token` from [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2.6). + +The `name` identifier is case-sensitive, whereas `token` is not. + +The table below provides examples of runtime expressions and examples of their use in a value: + +##### Examples + +Source Location | example expression | notes +---|:---|:---| +HTTP Method | `$method` | The allowable values for the `$method` will be those for the HTTP operation. +Requested media type | `$request.header.accept` | +Request parameter | `$request.path.id` | Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated. This includes request headers. +Request body property | `$request.body#/user/uuid` | In operations which accept payloads, references may be made to portions of the `requestBody` or the entire body. +Request URL | `$url` | +Response value | `$response.body#/status` | In operations which return payloads, references may be made to portions of the response body or the entire body. +Response header | `$response.header.Server` | Single header values only are available + +Runtime expressions preserve the type of the referenced value. +Expressions can be embedded into string values by surrounding the expression with `{}` curly braces. + +#### Header Object + +The Header Object follows the structure of the [Parameter Object](#parameterObject) with the following changes: + +1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. +1. `in` MUST NOT be specified, it is implicitly in `header`. +1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, [`style`](#parameterStyle)). + +##### Header Object Example + +A simple header of type `integer`: + +```json +{ + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } +} +``` + +```yaml +description: The number of allowed requests in the current period +schema: + type: integer +``` + +#### Tag Object + +Adds metadata to a single tag that is used by the [Operation Object](#operationObject). +It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The name of the tag. +description | `string` | A short description for the tag. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this tag. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Tag Object Example + +```json +{ + "name": "pet", + "description": "Pets operations" +} +``` + +```yaml +name: pet +description: Pets operations +``` + + +#### Reference Object + +A simple object to allow referencing other components in the specification, internally and externally. + +The Reference Object is defined by [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) and follows the same structure, behavior and rules. + +For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +$ref | `string` | **REQUIRED**. The reference string. + +This object cannot be extended with additional properties and any properties added SHALL be ignored. + +##### Reference Object Example + +```json +{ + "$ref": "#/components/schemas/Pet" +} +``` + +```yaml +$ref: '#/components/schemas/Pet' +``` + +##### Relative Schema Document Example +```json +{ + "$ref": "Pet.json" +} +``` + +```yaml +$ref: Pet.yaml +``` + +##### Relative Documents With Embedded Schema Example +```json +{ + "$ref": "definitions.json#/Pet" +} +``` + +```yaml +$ref: definitions.yaml#/Pet +``` + +#### Schema Object + +The Schema Object allows the definition of input and output data types. +These types can be objects, but also primitives and arrays. +This object is an extended subset of the [JSON Schema Specification Wright Draft 00](https://json-schema.org/). + +For more information about the properties, see [JSON Schema Core](https://tools.ietf.org/html/draft-wright-json-schema-00) and [JSON Schema Validation](https://tools.ietf.org/html/draft-wright-json-schema-validation-00). +Unless stated otherwise, the property definitions follow the JSON Schema. + +##### Properties + +The following properties are taken directly from the JSON Schema definition and follow the same specifications: + +- title +- multipleOf +- maximum +- exclusiveMaximum +- minimum +- exclusiveMinimum +- maxLength +- minLength +- pattern (This string SHOULD be a valid regular expression, according to the [Ecma-262 Edition 5.1 regular expression](https://www.ecma-international.org/ecma-262/5.1/#sec-15.10.1) dialect) +- maxItems +- minItems +- uniqueItems +- maxProperties +- minProperties +- required +- enum + +The following properties are taken from the JSON Schema definition but their definitions were adjusted to the OpenAPI Specification. +- type - Value MUST be a string. Multiple types via an array are not supported. +- allOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. +- oneOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. +- anyOf - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. +- not - Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. +- 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`. +- properties - Property definitions MUST be a [Schema Object](#schemaObject) and not a standard JSON Schema (inline or referenced). +- additionalProperties - Value can be boolean or object. Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. Consistent with JSON Schema, `additionalProperties` defaults to `true`. +- description - [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +- 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. +- 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`. + +Alternatively, any time a Schema Object can be used, a [Reference Object](#referenceObject) can be used in its place. This allows referencing definitions instead of defining them inline. + +Additional properties defined by the JSON Schema specification that are not mentioned here are strictly unsupported. + +Other than the JSON Schema subset fields, the following fields MAY be used for further schema documentation: + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +nullable | `boolean` | A `true` value adds `"null"` to the allowed type specified by the `type` keyword, only if `type` is explicitly defined within the same Schema Object. Other Schema Object constraints retain their defined behavior, and therefore may disallow the use of `null` as a value. A `false` value leaves the specified or default `type` unmodified. The default value is `false`. +discriminator | [Discriminator Object](#discriminatorObject) | Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See [Composition and Inheritance](#schemaComposition) for more details. +readOnly | `boolean` | Relevant only for Schema `"properties"` definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as `readOnly` being `true` and is in the `required` list, the `required` will take effect on the response only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`. +writeOnly | `boolean` | Relevant only for Schema `"properties"` definitions. Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as `writeOnly` being `true` and is in the `required` list, the `required` will take effect on the request only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`. +xml | [XML Object](#xmlObject) | This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this schema. +example | Any | A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. + deprecated | `boolean` | Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is `false`. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +###### Composition and Inheritance (Polymorphism) + +The OpenAPI Specification allows combining and extending model definitions using the `allOf` property of JSON Schema, in effect offering model composition. +`allOf` takes an array of object definitions that are validated *independently* but together compose a single object. + +While composition offers model extensibility, it does not imply a hierarchy between the models. +To support polymorphism, the OpenAPI Specification adds the `discriminator` field. +When used, the `discriminator` will be the name of the property that decides which schema definition validates the structure of the model. +As such, the `discriminator` field MUST be a required field. +There are two ways to define the value of a discriminator for an inheriting instance. +- Use the schema name. +- Override the schema name by overriding the property with a new value. If a new value exists, this takes precedence over the schema name. +As such, inline schema definitions, which do not have a given id, *cannot* be used in polymorphism. + +###### XML Modeling + +The [xml](#schemaXml) property allows extra definitions when translating the JSON definition to XML. +The [XML Object](#xmlObject) contains additional information about the available options. + +##### Schema Object Examples + +###### Primitive Sample + +```json +{ + "type": "string", + "format": "email" +} +``` + +```yaml +type: string +format: email +``` + +###### Simple Model + +```json +{ + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "address": { + "$ref": "#/components/schemas/Address" + }, + "age": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } +} +``` + +```yaml +type: object +required: +- name +properties: + name: + type: string + address: + $ref: '#/components/schemas/Address' + age: + type: integer + format: int32 + minimum: 0 +``` + +###### Model with Map/Dictionary Properties + +For a simple string to string mapping: + +```json +{ + "type": "object", + "additionalProperties": { + "type": "string" + } +} +``` + +```yaml +type: object +additionalProperties: + type: string +``` + +For a string to model mapping: + +```json +{ + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ComplexModel" + } +} +``` + +```yaml +type: object +additionalProperties: + $ref: '#/components/schemas/ComplexModel' +``` + +###### Model with Example + +```json +{ + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name" + ], + "example": { + "name": "Puma", + "id": 1 + } +} +``` + +```yaml +type: object +properties: + id: + type: integer + format: int64 + name: + type: string +required: +- name +example: + name: Puma + id: 1 +``` + +###### Models with Composition + +```json +{ + "components": { + "schemas": { + "ErrorModel": { + "type": "object", + "required": [ + "message", + "code" + ], + "properties": { + "message": { + "type": "string" + }, + "code": { + "type": "integer", + "minimum": 100, + "maximum": 600 + } + } + }, + "ExtendedErrorModel": { + "allOf": [ + { + "$ref": "#/components/schemas/ErrorModel" + }, + { + "type": "object", + "required": [ + "rootCause" + ], + "properties": { + "rootCause": { + "type": "string" + } + } + } + ] + } + } + } +} +``` + +```yaml +components: + schemas: + ErrorModel: + type: object + required: + - message + - code + properties: + message: + type: string + code: + type: integer + minimum: 100 + maximum: 600 + ExtendedErrorModel: + allOf: + - $ref: '#/components/schemas/ErrorModel' + - type: object + required: + - rootCause + properties: + rootCause: + type: string +``` + +###### Models with Polymorphism Support + +```json +{ + "components": { + "schemas": { + "Pet": { + "type": "object", + "discriminator": { + "propertyName": "petType" + }, + "properties": { + "name": { + "type": "string" + }, + "petType": { + "type": "string" + } + }, + "required": [ + "name", + "petType" + ] + }, + "Cat": { + "description": "A representation of a cat. Note that `Cat` will be used as the discriminator value.", + "allOf": [ + { + "$ref": "#/components/schemas/Pet" + }, + { + "type": "object", + "properties": { + "huntingSkill": { + "type": "string", + "description": "The measured skill for hunting", + "default": "lazy", + "enum": [ + "clueless", + "lazy", + "adventurous", + "aggressive" + ] + } + }, + "required": [ + "huntingSkill" + ] + } + ] + }, + "Dog": { + "description": "A representation of a dog. Note that `Dog` will be used as the discriminator value.", + "allOf": [ + { + "$ref": "#/components/schemas/Pet" + }, + { + "type": "object", + "properties": { + "packSize": { + "type": "integer", + "format": "int32", + "description": "the size of the pack the dog is from", + "default": 0, + "minimum": 0 + } + }, + "required": [ + "packSize" + ] + } + ] + } + } + } +} +``` + +```yaml +components: + schemas: + Pet: + type: object + discriminator: + propertyName: petType + properties: + name: + type: string + petType: + type: string + required: + - name + - petType + Cat: ## "Cat" will be used as the discriminator value + description: A representation of a cat + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + properties: + huntingSkill: + type: string + description: The measured skill for hunting + enum: + - clueless + - lazy + - adventurous + - aggressive + required: + - huntingSkill + Dog: ## "Dog" will be used as the discriminator value + description: A representation of a dog + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + properties: + packSize: + type: integer + format: int32 + description: the size of the pack the dog is from + default: 0 + minimum: 0 + required: + - packSize +``` + +#### Discriminator Object + +When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it. + +When using the discriminator, _inline_ schemas will not be considered. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +propertyName | `string` | **REQUIRED**. The name of the property in the payload that will hold the discriminator value. + mapping | Map[`string`, `string`] | An object to hold mappings between payload values and schema names or references. + +The discriminator object is legal only when using one of the composite keywords `oneOf`, `anyOf`, `allOf`. + +In OAS 3.0, a response payload MAY be described to be exactly one of any number of types: + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' +``` + +which means the payload _MUST_, by validation, match exactly one of the schemas described by `Cat`, `Dog`, or `Lizard`. In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use: + + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' + discriminator: + propertyName: petType +``` + +The expectation now is that a property with name `petType` _MUST_ be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload: + +```json +{ + "id": 12345, + "petType": "Cat" +} +``` + +Will indicate that the `Cat` schema be used in conjunction with this payload. + +In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used: + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' + - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json' + discriminator: + propertyName: petType + mapping: + dog: '#/components/schemas/Dog' + monster: 'https://gigantic-server.com/schemas/Monster/schema.json' +``` + +Here the discriminator _value_ of `dog` will map to the schema `#/components/schemas/Dog`, rather than the default (implicit) value of `Dog`. If the discriminator _value_ does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison. + +When used in conjunction with the `anyOf` construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload. + +In both the `oneOf` and `anyOf` use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an `allOf` construct may be used as an alternate schema. + +For example: + +```yaml +components: + schemas: + Pet: + type: object + required: + - petType + properties: + petType: + type: string + discriminator: + propertyName: petType + mapping: + dog: Dog + Cat: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Cat` + properties: + name: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Dog` + properties: + bark: + type: string + Lizard: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Lizard` + properties: + lovesRocks: + type: boolean +``` + +a payload like this: + +```json +{ + "petType": "Cat", + "name": "misty" +} +``` + +will indicate that the `Cat` schema be used. Likewise this schema: + +```json +{ + "petType": "dog", + "bark": "soft" +} +``` + +will map to `Dog` because of the definition in the `mappings` element. + + +#### XML Object + +A metadata object that allows for more fine-tuned XML model definitions. + +When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. +See examples for expected behavior. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. +namespace | `string` | The URI of the namespace definition. Value MUST be in the form of an absolute URI. +prefix | `string` | The prefix to be used for the [name](#xmlName). +attribute | `boolean` | Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. +wrapped | `boolean` | MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### XML Object Examples + +The examples of the XML object definitions are included inside a property definition of a [Schema Object](#schemaObject) with a sample of the XML representation of it. + +###### No XML Element + +Basic string property: + +```json +{ + "animals": { + "type": "string" + } +} +``` + +```yaml +animals: + type: string +``` + +```xml +... +``` + +Basic string array property ([`wrapped`](#xmlWrapped) is `false` by default): + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string +``` + +```xml +... +... +... +``` + +###### XML Name Replacement + +```json +{ + "animals": { + "type": "string", + "xml": { + "name": "animal" + } + } +} +``` + +```yaml +animals: + type: string + xml: + name: animal +``` + +```xml +... +``` + + +###### XML Attribute, Prefix and Namespace + +In this example, a full model definition is shown. + +```json +{ + "Person": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32", + "xml": { + "attribute": true + } + }, + "name": { + "type": "string", + "xml": { + "namespace": "http://example.com/schema/sample", + "prefix": "sample" + } + } + } + } +} +``` + +```yaml +Person: + type: object + properties: + id: + type: integer + format: int32 + xml: + attribute: true + name: + type: string + xml: + namespace: http://example.com/schema/sample + prefix: sample +``` + +```xml + + example + +``` + +###### XML Arrays + +Changing the element names: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal +``` + +```xml +value +value +``` + +The external `name` property has no effect on the XML: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens +``` + +```xml +value +value +``` + +Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + wrapped: true +``` + +```xml + + value + value + +``` + +To overcome the naming problem in the example above, the following definition can be used: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + wrapped: true +``` + +```xml + + value + value + +``` + +Affecting both internal and external names: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens + wrapped: true +``` + +```xml + + value + value + +``` + +If we change the external element but not the internal ones: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: aliens + wrapped: true +``` + +```xml + + value + value + +``` + +#### Security Scheme Object + +Defines a security scheme that can be used by the operations. +Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749](https://tools.ietf.org/html/rfc6749), and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06). + +##### Fixed Fields +Field Name | Type | Applies To | Description +---|:---:|---|--- +type | `string` | Any | **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"oauth2"`, `"openIdConnect"`. +description | `string` | Any | A short description for security scheme. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +name | `string` | `apiKey` | **REQUIRED**. The name of the header, query or cookie parameter to be used. +in | `string` | `apiKey` | **REQUIRED**. The location of the API key. Valid values are `"query"`, `"header"` or `"cookie"`. +scheme | `string` | `http` | **REQUIRED**. The name of the HTTP Authorization scheme to be used in the [Authorization header as defined in RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1). The values used SHOULD be registered in the [IANA Authentication Scheme registry](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml). +bearerFormat | `string` | `http` (`"bearer"`) | A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. +flows | [OAuth Flows Object](#oauthFlowsObject) | `oauth2` | **REQUIRED**. An object containing configuration information for the flow types supported. +openIdConnectUrl | `string` | `openIdConnect` | **REQUIRED**. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Security Scheme Object Example + +###### Basic Authentication Sample + +```json +{ + "type": "http", + "scheme": "basic" +} +``` + +```yaml +type: http +scheme: basic +``` + +###### API Key Sample + +```json +{ + "type": "apiKey", + "name": "api_key", + "in": "header" +} +``` + +```yaml +type: apiKey +name: api_key +in: header +``` + +###### JWT Bearer Sample + +```json +{ + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT", +} +``` + +```yaml +type: http +scheme: bearer +bearerFormat: JWT +``` + +###### Implicit OAuth2 Sample + +```json +{ + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } +} +``` + +```yaml +type: oauth2 +flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### OAuth Flows Object + +Allows configuration of the supported OAuth Flows. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +implicit| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Implicit flow +password| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Resource Owner Password flow +clientCredentials| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0. +authorizationCode| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### OAuth Flow Object + +Configuration details for a supported OAuth Flow + +##### Fixed Fields +Field Name | Type | Applies To | Description +---|:---:|---|--- +authorizationUrl | `string` | `oauth2` (`"implicit"`, `"authorizationCode"`) | **REQUIRED**. The authorization URL to be used for this flow. This MUST be in the form of a URL. +tokenUrl | `string` | `oauth2` (`"password"`, `"clientCredentials"`, `"authorizationCode"`) | **REQUIRED**. The token URL to be used for this flow. This MUST be in the form of a URL. +refreshUrl | `string` | `oauth2` | The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. +scopes | Map[`string`, `string`] | `oauth2` | **REQUIRED**. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### OAuth Flow Object Examples + +```JSON +{ + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "authorizationCode": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "tokenUrl": "https://example.com/api/oauth/token", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } +} +``` + +```yaml +type: oauth2 +flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + authorizationCode: + authorizationUrl: https://example.com/api/oauth/dialog + tokenUrl: https://example.com/api/oauth/token + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### Security Requirement Object + +Lists the required security schemes to execute this operation. +The name used for each property MUST correspond to a security scheme declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). + +Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. +This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. + +When a list of Security Requirement Objects is defined on the [OpenAPI Object](#oasObject) or [Operation Object](#operationObject), only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +{name} | [`string`] | Each name MUST correspond to a security scheme which is declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). If the security scheme is of type `"oauth2"` or `"openIdConnect"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MUST be empty. + +##### Security Requirement Object Examples + +###### Non-OAuth2 Security Requirement + +```json +{ + "api_key": [] +} +``` + +```yaml +api_key: [] +``` + +###### OAuth2 Security Requirement + +```json +{ + "petstore_auth": [ + "write:pets", + "read:pets" + ] +} +``` + +```yaml +petstore_auth: +- write:pets +- read:pets +``` + +###### Optional OAuth2 Security + +Optional OAuth2 security as would be defined in an OpenAPI Object or an Operation Object: + +```json +{ + "security": [ + {}, + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] +} +``` + +```yaml +security: + - {} + - petstore_auth: + - write:pets + - read:pets +``` + +### Specification Extensions + +While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points. + +The extensions properties are implemented as patterned fields that are always prefixed by `"x-"`. + +Field Pattern | Type | Description +---|:---:|--- +^x- | Any | Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. Can have any valid JSON format value. + +The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced). + +### Security Filtering + +Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation. + +The reasoning is to allow an additional layer of access control over the documentation. +While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization. + +Two examples of this: + +1. The [Paths Object](#pathsObject) MAY be empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They'd still have access to the [Info Object](#infoObject) which may contain additional information regarding authentication. +2. The [Path Item Object](#pathItemObject) MAY be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different from hiding the path itself from the [Paths Object](#pathsObject), because the user will be aware of its existence. This allows the documentation provider to finely control what the viewer can see. + +## Appendix A: Revision History + +Version | Date | Notes +--- | --- | --- +3.0.3 | 2020-02-20 | Patch release of the OpenAPI Specification 3.0.3 +3.0.2 | 2018-10-08 | Patch release of the OpenAPI Specification 3.0.2 +3.0.1 | 2017-12-06 | Patch release of the OpenAPI Specification 3.0.1 +3.0.0 | 2017-07-26 | Release of the OpenAPI Specification 3.0.0 +3.0.0-rc2 | 2017-06-16 | rc2 of the 3.0 specification +3.0.0-rc1 | 2017-04-27 | rc1 of the 3.0 specification +3.0.0-rc0 | 2017-02-28 | Implementer's Draft of the 3.0 specification +2.0 | 2015-12-31 | Donation of Swagger 2.0 to the OpenAPI Initiative +2.0 | 2014-09-08 | Release of Swagger 2.0 +1.2 | 2014-03-14 | Initial release of the formal document. +1.1 | 2012-08-22 | Release of Swagger 1.1 +1.0 | 2011-08-10 | First release of the Swagger Specification diff --git a/openapi_python_client/schema/3.1.0.md b/openapi_python_client/schema/3.1.0.md new file mode 100644 index 000000000..39425bd6b --- /dev/null +++ b/openapi_python_client/schema/3.1.0.md @@ -0,0 +1,3468 @@ +# OpenAPI Specification + +#### Version 3.1.0 + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://tools.ietf.org/html/bcp14) [RFC2119](https://tools.ietf.org/html/rfc2119) [RFC8174](https://tools.ietf.org/html/rfc8174) when, and only when, they appear in all capitals, as shown here. + +This document is licensed under [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). + +## Introduction + +The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to HTTP APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. + +An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases. + +## Table of Contents + + +- [Definitions](#definitions) + - [OpenAPI Document](#oasDocument) + - [Path Templating](#pathTemplating) + - [Media Types](#mediaTypes) + - [HTTP Status Codes](#httpCodes) +- [Specification](#specification) + - [Versions](#versions) + - [Format](#format) + - [Document Structure](#documentStructure) + - [Data Types](#dataTypes) + - [Rich Text Formatting](#richText) + - [Relative References In URIs](#relativeReferencesURI) + - [Relative References In URLs](#relativeReferencesURL) + - [Schema](#schema) + - [OpenAPI Object](#oasObject) + - [Info Object](#infoObject) + - [Contact Object](#contactObject) + - [License Object](#licenseObject) + - [Server Object](#serverObject) + - [Server Variable Object](#serverVariableObject) + - [Components Object](#componentsObject) + - [Paths Object](#pathsObject) + - [Path Item Object](#pathItemObject) + - [Operation Object](#operationObject) + - [External Documentation Object](#externalDocumentationObject) + - [Parameter Object](#parameterObject) + - [Request Body Object](#requestBodyObject) + - [Media Type Object](#mediaTypeObject) + - [Encoding Object](#encodingObject) + - [Responses Object](#responsesObject) + - [Response Object](#responseObject) + - [Callback Object](#callbackObject) + - [Example Object](#exampleObject) + - [Link Object](#linkObject) + - [Header Object](#headerObject) + - [Tag Object](#tagObject) + - [Reference Object](#referenceObject) + - [Schema Object](#schemaObject) + - [Discriminator Object](#discriminatorObject) + - [XML Object](#xmlObject) + - [Security Scheme Object](#securitySchemeObject) + - [OAuth Flows Object](#oauthFlowsObject) + - [OAuth Flow Object](#oauthFlowObject) + - [Security Requirement Object](#securityRequirementObject) + - [Specification Extensions](#specificationExtensions) + - [Security Filtering](#securityFiltering) +- [Appendix A: Revision History](#revisionHistory) + + + + +## Definitions + +##### OpenAPI Document +A self-contained or composite resource which defines or describes an API or elements of an API. The OpenAPI document MUST contain at least one [paths](#pathsObject) field, a [components](#oasComponents) field or a [webhooks](#oasWebhooks) field. An OpenAPI document uses and conforms to the OpenAPI Specification. + +##### Path Templating +Path templating refers to the usage of template expressions, delimited by curly braces ({}), to mark a section of a URL path as replaceable using path parameters. + +Each template expression in the path MUST correspond to a path parameter that is included in the [Path Item](#path-item-object) itself and/or in each of the Path Item's [Operations](#operation-object). An exception is if the path item is empty, for example due to ACL constraints, matching path parameters are not required. + +The value for these path parameters MUST NOT contain any unescaped "generic syntax" characters described by [RFC3986](https://tools.ietf.org/html/rfc3986#section-3): forward slashes (`/`), question marks (`?`), or hashes (`#`). + +##### Media Types +Media type definitions are spread across several resources. +The media type definitions SHOULD be in compliance with [RFC6838](https://tools.ietf.org/html/rfc6838). + +Some examples of possible media type definitions: +``` + text/plain; charset=utf-8 + application/json + application/vnd.github+json + application/vnd.github.v3+json + application/vnd.github.v3.raw+json + application/vnd.github.v3.text+json + application/vnd.github.v3.html+json + application/vnd.github.v3.full+json + application/vnd.github.v3.diff + application/vnd.github.v3.patch +``` +##### HTTP Status Codes +The HTTP Status Codes are used to indicate the status of the executed operation. +The available status codes are defined by [RFC7231](https://tools.ietf.org/html/rfc7231#section-6) and registered status codes are listed in the [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml). + +## Specification + +### Versions + +The OpenAPI Specification is versioned using a `major`.`minor`.`patch` versioning scheme. The `major`.`minor` portion of the version string (for example `3.1`) SHALL designate the OAS feature set. *`.patch`* versions address errors in, or provide clarifications to, this document, not the feature set. Tooling which supports OAS 3.1 SHOULD be compatible with all OAS 3.1.\* versions. The patch version SHOULD NOT be considered by tooling, making no distinction between `3.1.0` and `3.1.1` for example. + +Occasionally, non-backwards compatible changes may be made in `minor` versions of the OAS where impact is believed to be low relative to the benefit provided. + +An OpenAPI document compatible with OAS 3.\*.\* contains a required [`openapi`](#oasVersion) field which designates the version of the OAS that it uses. + +### Format + +An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either in JSON or YAML format. + +For example, if a field has an array value, the JSON array representation will be used: + +```json +{ + "field": [ 1, 2, 3 ] +} +``` +All field names in the specification are **case sensitive**. +This includes all fields that are used as keys in a map, except where explicitly noted that keys are **case insensitive**. + +The schema exposes two types of fields: Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name. + +Patterned fields MUST have unique names within the containing object. + +In order to preserve the ability to round-trip between YAML and JSON formats, YAML version [1.2](https://yaml.org/spec/1.2/spec.html) is RECOMMENDED along with some additional constraints: + +- Tags MUST be limited to those allowed by the [JSON Schema ruleset](https://yaml.org/spec/1.2/spec.html#id2803231). +- Keys used in YAML maps MUST be limited to a scalar string, as defined by the [YAML Failsafe schema ruleset](https://yaml.org/spec/1.2/spec.html#id2802346). + +**Note:** While APIs may be defined by OpenAPI documents in either YAML or JSON format, the API request and response bodies and other content are not required to be JSON or YAML. + +### Document Structure + +An OpenAPI document MAY be made up of a single document or be divided into multiple, connected parts at the discretion of the author. In the latter case, [`Reference Objects`](#referenceObject) and [`Schema Object`](#schemaObject) `$ref` keywords are used. + +It is RECOMMENDED that the root OpenAPI document be named: `openapi.json` or `openapi.yaml`. + +### Data Types + +Data types in the OAS are based on the types supported by the [JSON Schema Specification Draft 2020-12](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-4.2.1). +Note that `integer` as a type is also supported and is defined as a JSON number without a fraction or exponent part. +Models are defined using the [Schema Object](#schemaObject), which is a superset of JSON Schema Specification Draft 2020-12. + +As defined by the [JSON Schema Validation vocabulary](https://tools.ietf.org/html/draft-bhutton-json-schema-validation-00#section-7.3), data types can have an optional modifier property: `format`. +OAS defines additional formats to provide fine detail for primitive data types. + +The formats defined by the OAS are: + +[`type`](#dataTypes) | [`format`](#dataTypeFormat) | Comments +------ | -------- | -------- +`integer` | `int32` | signed 32 bits +`integer` | `int64` | signed 64 bits (a.k.a long) +`number` | `float` | | +`number` | `double` | | +`string` | `password` | A hint to UIs to obscure input. + +### Rich Text Formatting +Throughout the specification `description` fields are noted as supporting CommonMark markdown formatting. +Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by [CommonMark 0.27](https://spec.commonmark.org/0.27/). Tooling MAY choose to ignore some CommonMark features to address security concerns. + +### Relative References in URIs + +Unless specified otherwise, all properties that are URIs MAY be relative references as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-4.2). + +Relative references, including those in [`Reference Objects`](#referenceObject), [`PathItem Object`](#pathItemObject) `$ref` fields, [`Link Object`](#linkObject) `operationRef` fields and [`Example Object`](#exampleObject) `externalValue` fields, are resolved using the referring document as the Base URI according to [RFC3986](https://tools.ietf.org/html/rfc3986#section-5.2). + +If a URI contains a fragment identifier, then the fragment should be resolved per the fragment resolution mechanism of the referenced document. If the representation of the referenced document is JSON or YAML, then the fragment identifier SHOULD be interpreted as a JSON-Pointer as per [RFC6901](https://tools.ietf.org/html/rfc6901). + +Relative references in [`Schema Objects`](#schemaObject), including any that appear as `$id` values, use the nearest parent `$id` as a Base URI, as described by [JSON Schema Specification Draft 2020-12](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-8.2). If no parent schema contains an `$id`, then the Base URI MUST be determined according to [RFC3986](https://tools.ietf.org/html/rfc3986#section-5.1). + +### Relative References in URLs + +Unless specified otherwise, all properties that are URLs MAY be relative references as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-4.2). +Unless specified otherwise, relative references are resolved using the URLs defined in the [`Server Object`](#serverObject) as a Base URL. Note that these themselves MAY be relative to the referring document. + +### Schema + +In the following description, if a field is not explicitly **REQUIRED** or described with a MUST or SHALL, it can be considered OPTIONAL. + +#### OpenAPI Object + +This is the root object of the [OpenAPI document](#oasDocument). + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +openapi | `string` | **REQUIRED**. This string MUST be the [version number](#versions) of the OpenAPI Specification that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling to interpret the OpenAPI document. This is *not* related to the API [`info.version`](#infoVersion) string. +info | [Info Object](#infoObject) | **REQUIRED**. Provides metadata about the API. The metadata MAY be used by tooling as required. + jsonSchemaDialect | `string` | The default value for the `$schema` keyword within [Schema Objects](#schemaObject) contained within this OAS document. This MUST be in the form of a URI. +servers | [[Server Object](#serverObject)] | An array of Server Objects, which provide connectivity information to a target server. If the `servers` property is not provided, or is an empty array, the default value would be a [Server Object](#serverObject) with a [url](#serverUrl) value of `/`. +paths | [Paths Object](#pathsObject) | The available paths and operations for the API. +webhooks | Map[`string`, [Path Item Object](#pathItemObject) \| [Reference Object](#referenceObject)] ] | The incoming webhooks that MAY be received as part of this API and that the API consumer MAY choose to implement. Closely related to the `callbacks` feature, this section describes requests initiated other than by an API call, for example by an out of band registration. The key name is a unique string to refer to each webhook, while the (optionally referenced) Path Item Object describes a request that may be initiated by the API provider and the expected responses. An [example](../examples/v3.1/webhook-example.yaml) is available. +components | [Components Object](#componentsObject) | An element to hold various schemas for the document. +security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement (`{}`) can be included in the array. +tags | [[Tag Object](#tagObject)] | A list of tags used by the document with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](#operationObject) must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation. + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### Info Object + +The object provides metadata about the API. +The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +title | `string` | **REQUIRED**. The title of the API. +summary | `string` | A short summary of the API. +description | `string` | A description of the API. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +termsOfService | `string` | A URL to the Terms of Service for the API. This MUST be in the form of a URL. +contact | [Contact Object](#contactObject) | The contact information for the exposed API. +license | [License Object](#licenseObject) | The license information for the exposed API. +version | `string` | **REQUIRED**. The version of the OpenAPI document (which is distinct from the [OpenAPI Specification version](#oasVersion) or the API implementation version). + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Info Object Example + +```json +{ + "title": "Sample Pet Store App", + "summary": "A pet store manager.", + "description": "This is a sample server for a pet store.", + "termsOfService": "https://example.com/terms/", + "contact": { + "name": "API Support", + "url": "https://www.example.com/support", + "email": "support@example.com" + }, + "license": { + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.1" +} +``` + +```yaml +title: Sample Pet Store App +summary: A pet store manager. +description: This is a sample server for a pet store. +termsOfService: https://example.com/terms/ +contact: + name: API Support + url: https://www.example.com/support + email: support@example.com +license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +version: 1.0.1 +``` + +#### Contact Object + +Contact information for the exposed API. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +name | `string` | The identifying name of the contact person/organization. +url | `string` | The URL pointing to the contact information. This MUST be in the form of a URL. +email | `string` | The email address of the contact person/organization. This MUST be in the form of an email address. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Contact Object Example + +```json +{ + "name": "API Support", + "url": "https://www.example.com/support", + "email": "support@example.com" +} +``` + +```yaml +name: API Support +url: https://www.example.com/support +email: support@example.com +``` + +#### License Object + +License information for the exposed API. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The license name used for the API. +identifier | `string` | An [SPDX](https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60) license expression for the API. The `identifier` field is mutually exclusive of the `url` field. +url | `string` | A URL to the license used for the API. This MUST be in the form of a URL. The `url` field is mutually exclusive of the `identifier` field. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### License Object Example + +```json +{ + "name": "Apache 2.0", + "identifier": "Apache-2.0" +} +``` + +```yaml +name: Apache 2.0 +identifier: Apache-2.0 +``` + +#### Server Object + +An object representing a Server. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +url | `string` | **REQUIRED**. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{`brackets`}`. +description | `string` | An optional string describing the host designated by the URL. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +variables | Map[`string`, [Server Variable Object](#serverVariableObject)] | A map between a variable name and its value. The value is used for substitution in the server's URL template. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Server Object Example + +A single server would be described as: + +```json +{ + "url": "https://development.gigantic-server.com/v1", + "description": "Development server" +} +``` + +```yaml +url: https://development.gigantic-server.com/v1 +description: Development server +``` + +The following shows how multiple servers can be described, for example, at the OpenAPI Object's [`servers`](#oasServers): + +```json +{ + "servers": [ + { + "url": "https://development.gigantic-server.com/v1", + "description": "Development server" + }, + { + "url": "https://staging.gigantic-server.com/v1", + "description": "Staging server" + }, + { + "url": "https://api.gigantic-server.com/v1", + "description": "Production server" + } + ] +} +``` + +```yaml +servers: +- url: https://development.gigantic-server.com/v1 + description: Development server +- url: https://staging.gigantic-server.com/v1 + description: Staging server +- url: https://api.gigantic-server.com/v1 + description: Production server +``` + +The following shows how variables can be used for a server configuration: + +```json +{ + "servers": [ + { + "url": "https://{username}.gigantic-server.com:{port}/{basePath}", + "description": "The production API server", + "variables": { + "username": { + "default": "demo", + "description": "this value is assigned by the service provider, in this example `gigantic-server.com`" + }, + "port": { + "enum": [ + "8443", + "443" + ], + "default": "8443" + }, + "basePath": { + "default": "v2" + } + } + } + ] +} +``` + +```yaml +servers: +- url: https://{username}.gigantic-server.com:{port}/{basePath} + description: The production API server + variables: + username: + # note! no enum here means it is an open value + default: demo + description: this value is assigned by the service provider, in this example `gigantic-server.com` + port: + enum: + - '8443' + - '443' + default: '8443' + basePath: + # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2` + default: v2 +``` + + +#### Server Variable Object + +An object representing a Server Variable for server URL template substitution. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +enum | [`string`] | An enumeration of string values to be used if the substitution options are from a limited set. The array MUST NOT be empty. +default | `string` | **REQUIRED**. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. Note this behavior is different than the [Schema Object's](#schemaObject) treatment of default values, because in those cases parameter values are optional. If the [`enum`](#serverVariableEnum) is defined, the value MUST exist in the enum's values. +description | `string` | An optional description for the server variable. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### Components Object + +Holds a set of reusable objects for different aspects of the OAS. +All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. + + +##### Fixed Fields + +Field Name | Type | Description +---|:---|--- + schemas | Map[`string`, [Schema Object](#schemaObject)] | An object to hold reusable [Schema Objects](#schemaObject). + responses | Map[`string`, [Response Object](#responseObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Response Objects](#responseObject). + parameters | Map[`string`, [Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Parameter Objects](#parameterObject). + examples | Map[`string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Example Objects](#exampleObject). + requestBodies | Map[`string`, [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Request Body Objects](#requestBodyObject). + headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Header Objects](#headerObject). + securitySchemes| Map[`string`, [Security Scheme Object](#securitySchemeObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Security Scheme Objects](#securitySchemeObject). + links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Link Objects](#linkObject). + callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Callback Objects](#callbackObject). + pathItems | Map[`string`, [Path Item Object](#pathItemObject) \| [Reference Object](#referenceObject)] | An object to hold reusable [Path Item Object](#pathItemObject). + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`. + +Field Name Examples: + +``` +User +User_1 +User_Name +user-name +my.org.User +``` + +##### Components Object Example + +```json +"components": { + "schemas": { + "GeneralError": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + } + }, + "parameters": { + "skipParam": { + "name": "skip", + "in": "query", + "description": "number of items to skip", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + } + }, + "limitParam": { + "name": "limit", + "in": "query", + "description": "max records to return", + "required": true, + "schema" : { + "type": "integer", + "format": "int32" + } + } + }, + "responses": { + "NotFound": { + "description": "Entity not found." + }, + "IllegalInput": { + "description": "Illegal input for operation." + }, + "GeneralError": { + "description": "General Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GeneralError" + } + } + } + } + }, + "securitySchemes": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.org/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } + } + } +} +``` + +```yaml +components: + schemas: + GeneralError: + type: object + properties: + code: + type: integer + format: int32 + message: + type: string + Category: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + parameters: + skipParam: + name: skip + in: query + description: number of items to skip + required: true + schema: + type: integer + format: int32 + limitParam: + name: limit + in: query + description: max records to return + required: true + schema: + type: integer + format: int32 + responses: + NotFound: + description: Entity not found. + IllegalInput: + description: Illegal input for operation. + GeneralError: + description: General Error + content: + application/json: + schema: + $ref: '#/components/schemas/GeneralError' + securitySchemes: + api_key: + type: apiKey + name: api_key + in: header + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: https://example.org/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### Paths Object + +Holds the relative paths to the individual endpoints and their operations. +The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. The Paths MAY be empty, due to [Access Control List (ACL) constraints](#securityFiltering). + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +/{path} | [Path Item Object](#pathItemObject) | A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is **appended** (no relative URL resolution) to the expanded URL from the [`Server Object`](#serverObject)'s `url` field in order to construct the full URL. [Path templating](#pathTemplating) is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Path Templating Matching + +Assuming the following paths, the concrete definition, `/pets/mine`, will be matched first if used: + +``` + /pets/{petId} + /pets/mine +``` + +The following paths are considered identical and invalid: + +``` + /pets/{petId} + /pets/{name} +``` + +The following may lead to ambiguous resolution: + +``` + /{entity}/me + /books/{id} +``` + +##### Paths Object Example + +```json +{ + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "responses": { + "200": { + "description": "A list of pets.", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/pet" + } + } + } + } + } + } + } + } +} +``` + +```yaml +/pets: + get: + description: Returns all pets from the system that the user has access to + responses: + '200': + description: A list of pets. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/pet' +``` + +#### Path Item Object + +Describes the operations available on a single path. +A Path Item MAY be empty, due to [ACL constraints](#securityFiltering). +The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +$ref | `string` | Allows for a referenced definition of this path item. The referenced structure MUST be in the form of a [Path Item Object](#pathItemObject). In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. See the rules for resolving [Relative References](#relativeReferencesURI). +summary| `string` | An optional, string summary, intended to apply to all operations in this path. +description | `string` | An optional, string description, intended to apply to all operations in this path. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +get | [Operation Object](#operationObject) | A definition of a GET operation on this path. +put | [Operation Object](#operationObject) | A definition of a PUT operation on this path. +post | [Operation Object](#operationObject) | A definition of a POST operation on this path. +delete | [Operation Object](#operationObject) | A definition of a DELETE operation on this path. +options | [Operation Object](#operationObject) | A definition of a OPTIONS operation on this path. +head | [Operation Object](#operationObject) | A definition of a HEAD operation on this path. +patch | [Operation Object](#operationObject) | A definition of a PATCH operation on this path. +trace | [Operation Object](#operationObject) | A definition of a TRACE operation on this path. +servers | [[Server Object](#serverObject)] | An alternative `server` array to service all operations in this path. +parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Path Item Object Example + +```json +{ + "get": { + "description": "Returns pets based on ID", + "summary": "Find pets by ID", + "operationId": "getPetsById", + "responses": { + "200": { + "description": "pet response", + "content": { + "*/*": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Pet" + } + } + } + } + }, + "default": { + "description": "error payload", + "content": { + "text/html": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to use", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "simple" + } + ] +} +``` + +```yaml +get: + description: Returns pets based on ID + summary: Find pets by ID + operationId: getPetsById + responses: + '200': + description: pet response + content: + '*/*' : + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + default: + description: error payload + content: + 'text/html': + schema: + $ref: '#/components/schemas/ErrorModel' +parameters: +- name: id + in: path + description: ID of pet to use + required: true + schema: + type: array + items: + type: string + style: simple +``` + +#### Operation Object + +Describes a single API operation on a path. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +tags | [`string`] | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. +summary | `string` | A short summary of what the operation does. +description | `string` | A verbose explanation of the operation behavior. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this operation. +operationId | `string` | Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is **case-sensitive**. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. +parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for this operation. If a parameter is already defined at the [Path Item](#pathItemParameters), the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). +requestBody | [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject) | The request body applicable for this operation. The `requestBody` is fully supported in HTTP methods where the HTTP 1.1 specification [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague (such as [GET](https://tools.ietf.org/html/rfc7231#section-4.3.1), [HEAD](https://tools.ietf.org/html/rfc7231#section-4.3.2) and [DELETE](https://tools.ietf.org/html/rfc7231#section-4.3.5)), `requestBody` is permitted but does not have well-defined semantics and SHOULD be avoided if possible. +responses | [Responses Object](#responsesObject) | The list of possible responses as they are returned from executing this operation. +callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a [Callback Object](#callbackObject) that describes a request that may be initiated by the API provider and the expected responses. +deprecated | `boolean` | Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`. +security | [[Security Requirement Object](#securityRequirementObject)] | A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level [`security`](#oasSecurity). To remove a top-level security declaration, an empty array can be used. +servers | [[Server Object](#serverObject)] | An alternative `server` array to service this operation. If an alternative `server` object is specified at the Path Item Object or Root level, it will be overridden by this value. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Operation Object Example + +```json +{ + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "operationId": "updatePetWithForm", + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "Updated name of the pet", + "type": "string" + }, + "status": { + "description": "Updated status of the pet", + "type": "string" + } + }, + "required": ["status"] + } + } + } + }, + "responses": { + "200": { + "description": "Pet updated.", + "content": { + "application/json": {}, + "application/xml": {} + } + }, + "405": { + "description": "Method Not Allowed", + "content": { + "application/json": {}, + "application/xml": {} + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] +} +``` + +```yaml +tags: +- pet +summary: Updates a pet in the store with form data +operationId: updatePetWithForm +parameters: +- name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: string +requestBody: + content: + 'application/x-www-form-urlencoded': + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + required: + - status +responses: + '200': + description: Pet updated. + content: + 'application/json': {} + 'application/xml': {} + '405': + description: Method Not Allowed + content: + 'application/json': {} + 'application/xml': {} +security: +- petstore_auth: + - write:pets + - read:pets +``` + + +#### External Documentation Object + +Allows referencing an external resource for extended documentation. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +description | `string` | A description of the target documentation. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +url | `string` | **REQUIRED**. The URL for the target documentation. This MUST be in the form of a URL. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### External Documentation Object Example + +```json +{ + "description": "Find more info here", + "url": "https://example.com" +} +``` + +```yaml +description: Find more info here +url: https://example.com +``` + +#### Parameter Object + +Describes a single operation parameter. + +A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). + +##### Parameter Locations +There are four possible parameter locations specified by the `in` field: +* path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. +* query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. +* header - Custom headers that are expected as part of the request. Note that [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. +* cookie - Used to pass a specific cookie value to the API. + + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The name of the parameter. Parameter names are *case sensitive*.
  • If [`in`](#parameterIn) is `"path"`, the `name` field MUST correspond to a template expression occurring within the [path](#pathsPath) field in the [Paths Object](#pathsObject). See [Path Templating](#pathTemplating) for further information.
  • If [`in`](#parameterIn) is `"header"` and the `name` field is `"Accept"`, `"Content-Type"` or `"Authorization"`, the parameter definition SHALL be ignored.
  • For all other cases, the `name` corresponds to the parameter name used by the [`in`](#parameterIn) property.
+in | `string` | **REQUIRED**. The location of the parameter. Possible values are `"query"`, `"header"`, `"path"` or `"cookie"`. +description | `string` | A brief description of the parameter. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +required | `boolean` | Determines whether this parameter is mandatory. If the [parameter location](#parameterIn) is `"path"`, this property is **REQUIRED** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. + deprecated | `boolean` | Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`. + allowEmptyValue | `boolean` | Sets the ability to pass empty-valued parameters. This is valid only for `query` parameters and allows sending a parameter with an empty value. Default value is `false`. If [`style`](#parameterStyle) is used, and if behavior is `n/a` (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision. + +The rules for serialization of the parameter are specified in one of two ways. +For simpler scenarios, a [`schema`](#parameterSchema) and [`style`](#parameterStyle) can describe the structure and syntax of the parameter. + +Field Name | Type | Description +---|:---:|--- +style | `string` | Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `query` - `form`; for `path` - `simple`; for `header` - `simple`; for `cookie` - `form`. +explode | `boolean` | When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this property has no effect. When [`style`](#parameterStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. +allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. This property only applies to parameters with an `in` value of `query`. The default value is `false`. +schema | [Schema Object](#schemaObject) | The schema defining the type used for the parameter. +example | Any | Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` that contains an example, the `example` value SHALL _override_ the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary. +examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` that contains an example, the `examples` value SHALL _override_ the example provided by the schema. + +For more complex scenarios, the [`content`](#parameterContent) property can define the media type and schema of the parameter. +A parameter MUST contain either a `schema` property, or a `content` property, but not both. +When `example` or `examples` are provided in conjunction with the `schema` object, the example MUST follow the prescribed serialization strategy for the parameter. + + +Field Name | Type | Description +---|:---:|--- +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. + +##### Style Values + +In order to support common ways of serializing simple parameters, a set of `style` values are defined. + +`style` | [`type`](#dataTypes) | `in` | Comments +----------- | ------ | -------- | -------- +matrix | `primitive`, `array`, `object` | `path` | Path-style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7) +label | `primitive`, `array`, `object` | `path` | Label style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.5) +form | `primitive`, `array`, `object` | `query`, `cookie` | Form style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.8). This option replaces `collectionFormat` with a `csv` (when `explode` is false) or `multi` (when `explode` is true) value from OpenAPI 2.0. +simple | `array` | `path`, `header` | Simple style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.2). This option replaces `collectionFormat` with a `csv` value from OpenAPI 2.0. +spaceDelimited | `array`, `object` | `query` | Space separated array or object values. This option replaces `collectionFormat` equal to `ssv` from OpenAPI 2.0. +pipeDelimited | `array`, `object` | `query` | Pipe separated array or object values. This option replaces `collectionFormat` equal to `pipes` from OpenAPI 2.0. +deepObject | `object` | `query` | Provides a simple way of rendering nested objects using form parameters. + + +##### Style Examples + +Assume a parameter named `color` has one of the following values: + +``` + string -> "blue" + array -> ["blue","black","brown"] + object -> { "R": 100, "G": 200, "B": 150 } +``` +The following table shows examples of rendering differences for each value. + +[`style`](#styleValues) | `explode` | `empty` | `string` | `array` | `object` +----------- | ------ | -------- | -------- | -------- | ------- +matrix | false | ;color | ;color=blue | ;color=blue,black,brown | ;color=R,100,G,200,B,150 +matrix | true | ;color | ;color=blue | ;color=blue;color=black;color=brown | ;R=100;G=200;B=150 +label | false | . | .blue | .blue.black.brown | .R.100.G.200.B.150 +label | true | . | .blue | .blue.black.brown | .R=100.G=200.B=150 +form | false | color= | color=blue | color=blue,black,brown | color=R,100,G,200,B,150 +form | true | color= | color=blue | color=blue&color=black&color=brown | R=100&G=200&B=150 +simple | false | n/a | blue | blue,black,brown | R,100,G,200,B,150 +simple | true | n/a | blue | blue,black,brown | R=100,G=200,B=150 +spaceDelimited | false | n/a | n/a | blue%20black%20brown | R%20100%20G%20200%20B%20150 +pipeDelimited | false | n/a | n/a | blue\|black\|brown | R\|100\|G\|200\|B\|150 +deepObject | true | n/a | n/a | n/a | color[R]=100&color[G]=200&color[B]=150 + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Parameter Object Examples + +A header parameter with an array of 64 bit integer numbers: + +```json +{ + "name": "token", + "in": "header", + "description": "token to be passed as a header", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int64" + } + }, + "style": "simple" +} +``` + +```yaml +name: token +in: header +description: token to be passed as a header +required: true +schema: + type: array + items: + type: integer + format: int64 +style: simple +``` + +A path parameter of a string value: +```json +{ + "name": "username", + "in": "path", + "description": "username to fetch", + "required": true, + "schema": { + "type": "string" + } +} +``` + +```yaml +name: username +in: path +description: username to fetch +required: true +schema: + type: string +``` + +An optional query parameter of a string value, allowing multiple values by repeating the query parameter: +```json +{ + "name": "id", + "in": "query", + "description": "ID of the object to fetch", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "form", + "explode": true +} +``` + +```yaml +name: id +in: query +description: ID of the object to fetch +required: false +schema: + type: array + items: + type: string +style: form +explode: true +``` + +A free-form query parameter, allowing undefined parameters of a specific type: +```json +{ + "in": "query", + "name": "freeForm", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer" + }, + }, + "style": "form" +} +``` + +```yaml +in: query +name: freeForm +schema: + type: object + additionalProperties: + type: integer +style: form +``` + +A complex parameter using `content` to define serialization: + +```json +{ + "in": "query", + "name": "coordinates", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "lat", + "long" + ], + "properties": { + "lat": { + "type": "number" + }, + "long": { + "type": "number" + } + } + } + } + } +} +``` + +```yaml +in: query +name: coordinates +content: + application/json: + schema: + type: object + required: + - lat + - long + properties: + lat: + type: number + long: + type: number +``` + +#### Request Body Object + +Describes a single request body. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +description | `string` | A brief description of the request body. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | **REQUIRED**. The content of the request body. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* +required | `boolean` | Determines if the request body is required in the request. Defaults to `false`. + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Request Body Examples + +A request body with a referenced model definition. +```json +{ + "description": "user to add to the system", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + }, + "examples": { + "user" : { + "summary": "User Example", + "externalValue": "https://foo.bar/examples/user-example.json" + } + } + }, + "application/xml": { + "schema": { + "$ref": "#/components/schemas/User" + }, + "examples": { + "user" : { + "summary": "User example in XML", + "externalValue": "https://foo.bar/examples/user-example.xml" + } + } + }, + "text/plain": { + "examples": { + "user" : { + "summary": "User example in Plain text", + "externalValue": "https://foo.bar/examples/user-example.txt" + } + } + }, + "*/*": { + "examples": { + "user" : { + "summary": "User example in other format", + "externalValue": "https://foo.bar/examples/user-example.whatever" + } + } + } + } +} +``` + +```yaml +description: user to add to the system +content: + 'application/json': + schema: + $ref: '#/components/schemas/User' + examples: + user: + summary: User Example + externalValue: 'https://foo.bar/examples/user-example.json' + 'application/xml': + schema: + $ref: '#/components/schemas/User' + examples: + user: + summary: User example in XML + externalValue: 'https://foo.bar/examples/user-example.xml' + 'text/plain': + examples: + user: + summary: User example in Plain text + externalValue: 'https://foo.bar/examples/user-example.txt' + '*/*': + examples: + user: + summary: User example in other format + externalValue: 'https://foo.bar/examples/user-example.whatever' +``` + +A body parameter that is an array of string values: +```json +{ + "description": "user to add to the system", + "required": true, + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + } +} +``` + +```yaml +description: user to add to the system +required: true +content: + text/plain: + schema: + type: array + items: + type: string +``` + + +#### Media Type Object +Each Media Type Object provides schema and examples for the media type identified by its key. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +schema | [Schema Object](#schemaObject) | The schema defining the content of the request, response, or parameter. +example | Any | Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` which contains an example, the `example` value SHALL _override_ the example provided by the schema. +examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` which contains an example, the `examples` value SHALL _override_ the example provided by the schema. +encoding | Map[`string`, [Encoding Object](#encodingObject)] | A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to `requestBody` objects when the media type is `multipart` or `application/x-www-form-urlencoded`. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Media Type Examples + +```json +{ + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pet" + }, + "examples": { + "cat" : { + "summary": "An example of a cat", + "value": + { + "name": "Fluffy", + "petType": "Cat", + "color": "White", + "gender": "male", + "breed": "Persian" + } + }, + "dog": { + "summary": "An example of a dog with a cat's name", + "value" : { + "name": "Puma", + "petType": "Dog", + "color": "Black", + "gender": "Female", + "breed": "Mixed" + }, + "frog": { + "$ref": "#/components/examples/frog-example" + } + } + } + } +} +``` + +```yaml +application/json: + schema: + $ref: "#/components/schemas/Pet" + examples: + cat: + summary: An example of a cat + value: + name: Fluffy + petType: Cat + color: White + gender: male + breed: Persian + dog: + summary: An example of a dog with a cat's name + value: + name: Puma + petType: Dog + color: Black + gender: Female + breed: Mixed + frog: + $ref: "#/components/examples/frog-example" +``` + +##### Considerations for File Uploads + +In contrast with the 2.0 specification, `file` input/output content in OpenAPI is described with the same semantics as any other schema type. + +In contrast with the 3.0 specification, the `format` keyword has no effect on the content-encoding of the schema. JSON Schema offers a `contentEncoding` keyword, which may be used to specify the `Content-Encoding` for the schema. The `contentEncoding` keyword supports all encodings defined in [RFC4648](https://tools.ietf.org/html/rfc4648), including "base64" and "base64url", as well as "quoted-printable" from [RFC2045](https://tools.ietf.org/html/rfc2045#section-6.7). The encoding specified by the `contentEncoding` keyword is independent of an encoding specified by the `Content-Type` header in the request or response or metadata of a multipart body -- when both are present, the encoding specified in the `contentEncoding` is applied first and then the encoding specified in the `Content-Type` header. + +JSON Schema also offers a `contentMediaType` keyword. However, when the media type is already specified by the Media Type Object's key, or by the `contentType` field of an [Encoding Object](#encodingObject), the `contentMediaType` keyword SHALL be ignored if present. + +Examples: + +Content transferred in binary (octet-stream) MAY omit `schema`: + +```yaml +# a PNG image as a binary file: +content: + image/png: {} +``` + +```yaml +# an arbitrary binary file: +content: + application/octet-stream: {} +``` + +Binary content transferred with base64 encoding: + +```yaml +content: + image/png: + schema: + type: string + contentMediaType: image/png + contentEncoding: base64 +``` + +Note that the `Content-Type` remains `image/png`, describing the semantics of the payload. The JSON Schema `type` and `contentEncoding` fields explain that the payload is transferred as text. The JSON Schema `contentMediaType` is technically redundant, but can be used by JSON Schema tools that may not be aware of the OpenAPI context. + +These examples apply to either input payloads of file uploads or response payloads. + +A `requestBody` for submitting a file in a `POST` operation may look like the following example: + +```yaml +requestBody: + content: + application/octet-stream: {} +``` + +In addition, specific media types MAY be specified: + +```yaml +# multiple, specific media types may be specified: +requestBody: + content: + # a binary file of type png or jpeg + image/jpeg: {} + image/png: {} +``` + +To upload multiple files, a `multipart` media type MUST be used: + +```yaml +requestBody: + content: + multipart/form-data: + schema: + properties: + # The property name 'file' will be used for all files. + file: + type: array + items: {} +``` + +As seen in the section on `multipart/form-data` below, the empty schema for `items` indicates a media type of `application/octet-stream`. + +##### Support for x-www-form-urlencoded Request Bodies + +To submit content using form url encoding via [RFC1866](https://tools.ietf.org/html/rfc1866), the following +definition may be used: + +```yaml +requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + # complex types are stringified to support RFC 1866 + type: object + properties: {} +``` + +In this example, the contents in the `requestBody` MUST be stringified per [RFC1866](https://tools.ietf.org/html/rfc1866/) when passed to the server. In addition, the `address` field complex object will be stringified. + +When passing complex objects in the `application/x-www-form-urlencoded` content type, the default serialization strategy of such properties is described in the [`Encoding Object`](#encodingObject)'s [`style`](#encodingStyle) property as `form`. + +##### Special Considerations for `multipart` Content + +It is common to use `multipart/form-data` as a `Content-Type` when transferring request bodies to operations. In contrast to 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content. This supports complex structures as well as supporting mechanisms for multiple file uploads. + +In a `multipart/form-data` request body, each schema property, or each element of a schema array property, takes a section in the payload with an internal header as defined by [RFC7578](https://tools.ietf.org/html/rfc7578). The serialization strategy for each property of a `multipart/form-data` request body can be specified in an associated [`Encoding Object`](#encodingObject). + +When passing in `multipart` types, boundaries MAY be used to separate sections of the content being transferred – thus, the following default `Content-Type`s are defined for `multipart`: + +* If the property is a primitive, or an array of primitive values, the default Content-Type is `text/plain` +* If the property is complex, or an array of complex values, the default Content-Type is `application/json` +* If the property is a `type: string` with a `contentEncoding`, the default Content-Type is `application/octet-stream` + +Per the JSON Schema specification, `contentMediaType` without `contentEncoding` present is treated as if `contentEncoding: identity` were present. While useful for embedding text documents such as `text/html` into JSON strings, it is not useful for a `multipart/form-data` part, as it just causes the document to be treated as `text/plain` instead of its actual media type. Use the Encoding Object without `contentMediaType` if no `contentEncoding` is required. + +Examples: + +```yaml +requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + # default Content-Type for objects is `application/json` + type: object + properties: {} + profileImage: + # Content-Type for application-level encoded resource is `text/plain` + type: string + contentMediaType: image/png + contentEncoding: base64 + children: + # default Content-Type for arrays is based on the _inner_ type (`text/plain` here) + type: array + items: + type: string + addresses: + # default Content-Type for arrays is based on the _inner_ type (object shown, so `application/json` in this example) + type: array + items: + type: object + $ref: '#/components/schemas/Address' +``` + +An `encoding` attribute is introduced to give you control over the serialization of parts of `multipart` request bodies. This attribute is _only_ applicable to `multipart` and `application/x-www-form-urlencoded` request bodies. + +#### Encoding Object + +A single encoding definition applied to a single schema property. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +contentType | `string` | The Content-Type for encoding a specific property. Default value depends on the property type: for `object` - `application/json`; for `array` – the default is defined based on the inner type; for all other cases the default is `application/octet-stream`. The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or a comma-separated list of the two types. +headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | A map allowing additional information to be provided as headers, for example `Content-Disposition`. `Content-Type` is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a `multipart`. +style | `string` | Describes how a specific property value will be serialized depending on its type. See [Parameter Object](#parameterObject) for details on the [`style`](#parameterStyle) property. The behavior follows the same values as `query` parameters, including default values. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of [`contentType`](#encodingContentType) (implicit or explicit) SHALL be ignored. +explode | `boolean` | When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When [`style`](#encodingStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of [`contentType`](#encodingContentType) (implicit or explicit) SHALL be ignored. +allowReserved | `boolean` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded` or `multipart/form-data`. If a value is explicitly defined, then the value of [`contentType`](#encodingContentType) (implicit or explicit) SHALL be ignored. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Encoding Object Example + +```yaml +requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + id: + # default is text/plain + type: string + format: uuid + address: + # default is application/json + type: object + properties: {} + historyMetadata: + # need to declare XML format! + description: metadata in XML format + type: object + properties: {} + profileImage: {} + encoding: + historyMetadata: + # require XML Content-Type in utf-8 encoding + contentType: application/xml; charset=utf-8 + profileImage: + # only accept png/jpeg + contentType: image/png, image/jpeg + headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer +``` + +#### Responses Object + +A container for the expected responses of an operation. +The container maps a HTTP response code to the expected response. + +The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. +However, documentation is expected to cover a successful operation response and any known errors. + +The `default` MAY be used as a default response object for all HTTP codes +that are not covered individually by the `Responses Object`. + +The `Responses Object` MUST contain at least one response code, and if only one +response code is provided it SHOULD be the response for a successful operation +call. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +default | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +[HTTP Status Code](#httpCodes) | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | Any [HTTP status code](#httpCodes) can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `[200-299]`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Responses Object Example + +A 200 response for a successful operation and a default response for others (implying an error): + +```json +{ + "200": { + "description": "a pet to be returned", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pet" + } + } + } + }, + "default": { + "description": "Unexpected error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } +} +``` + +```yaml +'200': + description: a pet to be returned + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +default: + description: Unexpected error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorModel' +``` + +#### Response Object +Describes a single response from an API Operation, including design-time, static +`links` to operations based on the response. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +description | `string` | **REQUIRED**. A description of the response. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | Maps a header name to its definition. [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL be ignored. +content | Map[`string`, [Media Type Object](#mediaTypeObject)] | A map containing descriptions of potential response payloads. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* +links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for [Component Objects](#componentsObject). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Response Object Examples + +Response of an array of a complex type: + +```json +{ + "description": "A complex object array response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VeryComplexType" + } + } + } + } +} +``` + +```yaml +description: A complex object array response +content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/VeryComplexType' +``` + +Response with a string type: + +```json +{ + "description": "A simple string response", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + +} +``` + +```yaml +description: A simple string response +content: + text/plain: + schema: + type: string +``` + +Plain text response with headers: + +```json +{ + "description": "A simple string response", + "content": { + "text/plain": { + "schema": { + "type": "string", + "example": "whoa!" + } + } + }, + "headers": { + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Remaining": { + "description": "The number of remaining requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Reset": { + "description": "The number of seconds left in the current period", + "schema": { + "type": "integer" + } + } + } +} +``` + +```yaml +description: A simple string response +content: + text/plain: + schema: + type: string + example: 'whoa!' +headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer + X-Rate-Limit-Remaining: + description: The number of remaining requests in the current period + schema: + type: integer + X-Rate-Limit-Reset: + description: The number of seconds left in the current period + schema: + type: integer +``` + +Response with no return value: + +```json +{ + "description": "object created" +} +``` + +```yaml +description: object created +``` + +#### Callback Object + +A map of possible out-of band callbacks related to the parent operation. +Each value in the map is a [Path Item Object](#pathItemObject) that describes a set of requests that may be initiated by the API provider and the expected responses. +The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. + +To describe incoming requests from the API provider independent from another API call, use the [`webhooks`](#oasWebhooks) field. + +##### Patterned Fields +Field Pattern | Type | Description +---|:---:|--- +{expression} | [Path Item Object](#pathItemObject) \| [Reference Object](#referenceObject) | A Path Item Object, or a reference to one, used to define a callback request and expected responses. A [complete example](../examples/v3.0/callback-example.yaml) is available. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Key Expression + +The key that identifies the [Path Item Object](#pathItemObject) is a [runtime expression](#runtimeExpression) that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. +A simple example might be `$request.body#/url`. +However, using a [runtime expression](#runtimeExpression) the complete HTTP message can be accessed. +This includes accessing any part of a body that a JSON Pointer [RFC6901](https://tools.ietf.org/html/rfc6901) can reference. + +For example, given the following HTTP request: + +```http +POST /subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning HTTP/1.1 +Host: example.org +Content-Type: application/json +Content-Length: 187 + +{ + "failedUrl" : "https://clientdomain.com/failed", + "successUrls" : [ + "https://clientdomain.com/fast", + "https://clientdomain.com/medium", + "https://clientdomain.com/slow" + ] +} + +201 Created +Location: https://example.org/subscription/1 +``` + +The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named `eventType` and a query parameter named `queryUrl`. + +Expression | Value +---|:--- +$url | https://example.org/subscribe/myevent?queryUrl=https://clientdomain.com/stillrunning +$method | POST +$request.path.eventType | myevent +$request.query.queryUrl | https://clientdomain.com/stillrunning +$request.header.content-Type | application/json +$request.body#/failedUrl | https://clientdomain.com/failed +$request.body#/successUrls/2 | https://clientdomain.com/medium +$response.header.Location | https://example.org/subscription/1 + + +##### Callback Object Examples + +The following example uses the user provided `queryUrl` query string parameter to define the callback URL. This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook. + +```yaml +myCallback: + '{$request.query.queryUrl}': + post: + requestBody: + description: Callback payload + content: + 'application/json': + schema: + $ref: '#/components/schemas/SomePayload' + responses: + '200': + description: callback successfully processed +``` + +The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the `id` and `email` property in the request body. + +```yaml +transactionCallback: + 'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}': + post: + requestBody: + description: Callback payload + content: + 'application/json': + schema: + $ref: '#/components/schemas/SomePayload' + responses: + '200': + description: callback successfully processed +``` + +#### Example Object + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +summary | `string` | Short description for the example. +description | `string` | Long description for the example. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +value | Any | Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary. +externalValue | `string` | A URI that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. See the rules for resolving [Relative References](#relativeReferencesURI). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +In all cases, the example value is expected to be compatible with the type schema +of its associated value. Tooling implementations MAY choose to +validate compatibility automatically, and reject the example value(s) if incompatible. + +##### Example Object Examples + +In a request body: + +```yaml +requestBody: + content: + 'application/json': + schema: + $ref: '#/components/schemas/Address' + examples: + foo: + summary: A foo example + value: {"foo": "bar"} + bar: + summary: A bar example + value: {"bar": "baz"} + 'application/xml': + examples: + xmlExample: + summary: This is an example in XML + externalValue: 'https://example.org/examples/address-example.xml' + 'text/plain': + examples: + textExample: + summary: This is a text example + externalValue: 'https://foo.bar/examples/address-example.txt' +``` + +In a parameter: + +```yaml +parameters: + - name: 'zipCode' + in: 'query' + schema: + type: 'string' + format: 'zip-code' + examples: + zip-example: + $ref: '#/components/examples/zip-example' +``` + +In a response: + +```yaml +responses: + '200': + description: your car appointment has been booked + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessResponse' + examples: + confirmation-success: + $ref: '#/components/examples/confirmation-success' +``` + + +#### Link Object + +The `Link object` represents a possible design-time link for a response. +The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. + +Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. + +For computing links, and providing instructions to execute them, a [runtime expression](#runtimeExpression) is used for accessing values in an operation and using them as parameters while invoking the linked operation. + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +operationRef | `string` | A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an [Operation Object](#operationObject). Relative `operationRef` values MAY be used to locate an existing [Operation Object](#operationObject) in the OpenAPI definition. See the rules for resolving [Relative References](#relativeReferencesURI). +operationId | `string` | The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field. +parameters | Map[`string`, Any \| [{expression}](#runtimeExpression)] | A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the [parameter location](#parameterIn) `[{in}.]{name}` for operations that use the same parameter name in different locations (e.g. path.id). +requestBody | Any \| [{expression}](#runtimeExpression) | A literal value or [{expression}](#runtimeExpression) to use as a request body when calling the target operation. +description | `string` | A description of the link. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +server | [Server Object](#serverObject) | A server object to be used by the target operation. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +A linked operation MUST be identified using either an `operationRef` or `operationId`. +In the case of an `operationId`, it MUST be unique and resolved in the scope of the OAS document. +Because of the potential for name clashes, the `operationRef` syntax is preferred +for OpenAPI documents with external references. + +##### Examples + +Computing a link from a request operation where the `$request.path.id` is used to pass a request parameter to the linked operation. + +```yaml +paths: + /users/{id}: + parameters: + - name: id + in: path + required: true + description: the user identifier, as userId + schema: + type: string + get: + responses: + '200': + description: the user being returned + content: + application/json: + schema: + type: object + properties: + uuid: # the unique user id + type: string + format: uuid + links: + address: + # the target link operationId + operationId: getUserAddress + parameters: + # get the `id` field from the request path parameter named `id` + userId: $request.path.id + # the path item of the linked operation + /users/{userid}/address: + parameters: + - name: userid + in: path + required: true + description: the user identifier, as userId + schema: + type: string + # linked operation + get: + operationId: getUserAddress + responses: + '200': + description: the user's address +``` + +When a runtime expression fails to evaluate, no parameter value is passed to the target operation. + +Values from the response body can be used to drive a linked operation. + +```yaml +links: + address: + operationId: getUserAddressByUUID + parameters: + # get the `uuid` field from the `uuid` field in the response body + userUuid: $response.body#/uuid +``` + +Clients follow all links at their discretion. +Neither permissions, nor the capability to make a successful call to that link, is guaranteed +solely by the existence of a relationship. + + +##### OperationRef Examples + +As references to `operationId` MAY NOT be possible (the `operationId` is an optional +field in an [Operation Object](#operationObject)), references MAY also be made through a relative `operationRef`: + +```yaml +links: + UserRepositories: + # returns array of '#/components/schemas/repository' + operationRef: '#/paths/~12.0~1repositories~1{username}/get' + parameters: + username: $response.body#/username +``` + +or an absolute `operationRef`: + +```yaml +links: + UserRepositories: + # returns array of '#/components/schemas/repository' + operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get' + parameters: + username: $response.body#/username +``` + +Note that in the use of `operationRef`, the _escaped forward-slash_ is necessary when +using JSON references. + + +##### Runtime Expressions + +Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. +This mechanism is used by [Link Objects](#linkObject) and [Callback Objects](#callbackObject). + +The runtime expression is defined by the following [ABNF](https://tools.ietf.org/html/rfc5234) syntax + +```abnf + expression = ( "$url" / "$method" / "$statusCode" / "$request." source / "$response." source ) + source = ( header-reference / query-reference / path-reference / body-reference ) + header-reference = "header." token + query-reference = "query." name + path-reference = "path." name + body-reference = "body" ["#" json-pointer ] + json-pointer = *( "/" reference-token ) + reference-token = *( unescaped / escaped ) + unescaped = %x00-2E / %x30-7D / %x7F-10FFFF + ; %x2F ('/') and %x7E ('~') are excluded from 'unescaped' + escaped = "~" ( "0" / "1" ) + ; representing '~' and '/', respectively + name = *( CHAR ) + token = 1*tchar + tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / + "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA +``` + +Here, `json-pointer` is taken from [RFC6901](https://tools.ietf.org/html/rfc6901), `char` from [RFC7159](https://tools.ietf.org/html/rfc7159#section-7) and `token` from [RFC7230](https://tools.ietf.org/html/rfc7230#section-3.2.6). + +The `name` identifier is case-sensitive, whereas `token` is not. + +The table below provides examples of runtime expressions and examples of their use in a value: + +##### Examples + +Source Location | example expression | notes +---|:---|:---| +HTTP Method | `$method` | The allowable values for the `$method` will be those for the HTTP operation. +Requested media type | `$request.header.accept` | +Request parameter | `$request.path.id` | Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated. This includes request headers. +Request body property | `$request.body#/user/uuid` | In operations which accept payloads, references may be made to portions of the `requestBody` or the entire body. +Request URL | `$url` | +Response value | `$response.body#/status` | In operations which return payloads, references may be made to portions of the response body or the entire body. +Response header | `$response.header.Server` | Single header values only are available + +Runtime expressions preserve the type of the referenced value. +Expressions can be embedded into string values by surrounding the expression with `{}` curly braces. + +#### Header Object + +The Header Object follows the structure of the [Parameter Object](#parameterObject) with the following changes: + +1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. +1. `in` MUST NOT be specified, it is implicitly in `header`. +1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, [`style`](#parameterStyle)). + +##### Header Object Example + +A simple header of type `integer`: + +```json +{ + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } +} +``` + +```yaml +description: The number of allowed requests in the current period +schema: + type: integer +``` + +#### Tag Object + +Adds metadata to a single tag that is used by the [Operation Object](#operationObject). +It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | **REQUIRED**. The name of the tag. +description | `string` | A description for the tag. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this tag. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Tag Object Example + +```json +{ + "name": "pet", + "description": "Pets operations" +} +``` + +```yaml +name: pet +description: Pets operations +``` + + +#### Reference Object + +A simple object to allow referencing other components in the OpenAPI document, internally and externally. + +The `$ref` string value contains a URI [RFC3986](https://tools.ietf.org/html/rfc3986), which identifies the location of the value being referenced. + +See the rules for resolving [Relative References](#relativeReferencesURI). + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +$ref | `string` | **REQUIRED**. The reference identifier. This MUST be in the form of a URI. +summary | `string` | A short summary which by default SHOULD override that of the referenced component. If the referenced object-type does not allow a `summary` field, then this field has no effect. +description | `string` | A description which by default SHOULD override that of the referenced component. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. If the referenced object-type does not allow a `description` field, then this field has no effect. + +This object cannot be extended with additional properties and any properties added SHALL be ignored. + +Note that this restriction on additional properties is a difference between Reference Objects and [`Schema Objects`](#schemaObject) that contain a `$ref` keyword. + +##### Reference Object Example + +```json +{ + "$ref": "#/components/schemas/Pet" +} +``` + +```yaml +$ref: '#/components/schemas/Pet' +``` + +##### Relative Schema Document Example +```json +{ + "$ref": "Pet.json" +} +``` + +```yaml +$ref: Pet.yaml +``` + +##### Relative Documents With Embedded Schema Example +```json +{ + "$ref": "definitions.json#/Pet" +} +``` + +```yaml +$ref: definitions.yaml#/Pet +``` + +#### Schema Object + +The Schema Object allows the definition of input and output data types. +These types can be objects, but also primitives and arrays. This object is a superset of the [JSON Schema Specification Draft 2020-12](https://tools.ietf.org/html/draft-bhutton-json-schema-00). + +For more information about the properties, see [JSON Schema Core](https://tools.ietf.org/html/draft-bhutton-json-schema-00) and [JSON Schema Validation](https://tools.ietf.org/html/draft-bhutton-json-schema-validation-00). + +Unless stated otherwise, the property definitions follow those of JSON Schema and do not add any additional semantics. +Where JSON Schema indicates that behavior is defined by the application (e.g. for annotations), OAS also defers the definition of semantics to the application consuming the OpenAPI document. + +##### Properties + +The OpenAPI Schema Object [dialect](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-4.3.3) is defined as requiring the [OAS base vocabulary](#baseVocabulary), in addition to the vocabularies as specified in the JSON Schema draft 2020-12 [general purpose meta-schema](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-8). + +The OpenAPI Schema Object dialect for this version of the specification is identified by the URI `https://spec.openapis.org/oas/3.1/dialect/base` (the "OAS dialect schema id"). + +The following properties are taken from the JSON Schema specification but their definitions have been extended by the OAS: + +- description - [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +- 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. + +In addition to the JSON Schema properties comprising the OAS dialect, the Schema Object supports keywords from any other vocabularies, or entirely arbitrary properties. + +The OpenAPI Specification's base vocabulary is comprised of the following keywords: + +##### Fixed Fields + +Field Name | Type | Description +---|:---:|--- +discriminator | [Discriminator Object](#discriminatorObject) | Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See [Composition and Inheritance](#schemaComposition) for more details. +xml | [XML Object](#xmlObject) | This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property. +externalDocs | [External Documentation Object](#externalDocumentationObject) | Additional external documentation for this schema. +example | Any | A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary.

**Deprecated:** The `example` property has been deprecated in favor of the JSON Schema `examples` keyword. Use of `example` is discouraged, and later versions of this specification may remove it. + +This object MAY be extended with [Specification Extensions](#specificationExtensions), though as noted, additional properties MAY omit the `x-` prefix within this object. + +###### Composition and Inheritance (Polymorphism) + +The OpenAPI Specification allows combining and extending model definitions using the `allOf` property of JSON Schema, in effect offering model composition. +`allOf` takes an array of object definitions that are validated *independently* but together compose a single object. + +While composition offers model extensibility, it does not imply a hierarchy between the models. +To support polymorphism, the OpenAPI Specification adds the `discriminator` field. +When used, the `discriminator` will be the name of the property that decides which schema definition validates the structure of the model. +As such, the `discriminator` field MUST be a required field. +There are two ways to define the value of a discriminator for an inheriting instance. +- Use the schema name. +- Override the schema name by overriding the property with a new value. If a new value exists, this takes precedence over the schema name. +As such, inline schema definitions, which do not have a given id, *cannot* be used in polymorphism. + +###### XML Modeling + +The [xml](#schemaXml) property allows extra definitions when translating the JSON definition to XML. +The [XML Object](#xmlObject) contains additional information about the available options. + +###### Specifying Schema Dialects + +It is important for tooling to be able to determine which dialect or meta-schema any given resource wishes to be processed with: JSON Schema Core, JSON Schema Validation, OpenAPI Schema dialect, or some custom meta-schema. + +The `$schema` keyword MAY be present in any root Schema Object, and if present MUST be used to determine which dialect should be used when processing the schema. This allows use of Schema Objects which comply with other drafts of JSON Schema than the default Draft 2020-12 support. Tooling MUST support the OAS dialect schema id, and MAY support additional values of `$schema`. + +To allow use of a different default `$schema` value for all Schema Objects contained within an OAS document, a `jsonSchemaDialect` value may be set within the OpenAPI Object. If this default is not set, then the OAS dialect schema id MUST be used for these Schema Objects. The value of `$schema` within a Schema Object always overrides any default. + +When a Schema Object is referenced from an external resource which is not an OAS document (e.g. a bare JSON Schema resource), then the value of the `$schema` keyword for schemas within that resource MUST follow [JSON Schema rules](https://tools.ietf.org/html/draft-bhutton-json-schema-00#section-8.1.1). + +##### Schema Object Examples + +###### Primitive Sample + +```json +{ + "type": "string", + "format": "email" +} +``` + +```yaml +type: string +format: email +``` + +###### Simple Model + +```json +{ + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "address": { + "$ref": "#/components/schemas/Address" + }, + "age": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } +} +``` + +```yaml +type: object +required: +- name +properties: + name: + type: string + address: + $ref: '#/components/schemas/Address' + age: + type: integer + format: int32 + minimum: 0 +``` + +###### Model with Map/Dictionary Properties + +For a simple string to string mapping: + +```json +{ + "type": "object", + "additionalProperties": { + "type": "string" + } +} +``` + +```yaml +type: object +additionalProperties: + type: string +``` + +For a string to model mapping: + +```json +{ + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ComplexModel" + } +} +``` + +```yaml +type: object +additionalProperties: + $ref: '#/components/schemas/ComplexModel' +``` + +###### Model with Example + +```json +{ + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name" + ], + "example": { + "name": "Puma", + "id": 1 + } +} +``` + +```yaml +type: object +properties: + id: + type: integer + format: int64 + name: + type: string +required: +- name +example: + name: Puma + id: 1 +``` + +###### Models with Composition + +```json +{ + "components": { + "schemas": { + "ErrorModel": { + "type": "object", + "required": [ + "message", + "code" + ], + "properties": { + "message": { + "type": "string" + }, + "code": { + "type": "integer", + "minimum": 100, + "maximum": 600 + } + } + }, + "ExtendedErrorModel": { + "allOf": [ + { + "$ref": "#/components/schemas/ErrorModel" + }, + { + "type": "object", + "required": [ + "rootCause" + ], + "properties": { + "rootCause": { + "type": "string" + } + } + } + ] + } + } + } +} +``` + +```yaml +components: + schemas: + ErrorModel: + type: object + required: + - message + - code + properties: + message: + type: string + code: + type: integer + minimum: 100 + maximum: 600 + ExtendedErrorModel: + allOf: + - $ref: '#/components/schemas/ErrorModel' + - type: object + required: + - rootCause + properties: + rootCause: + type: string +``` + +###### Models with Polymorphism Support + +```json +{ + "components": { + "schemas": { + "Pet": { + "type": "object", + "discriminator": { + "propertyName": "petType" + }, + "properties": { + "name": { + "type": "string" + }, + "petType": { + "type": "string" + } + }, + "required": [ + "name", + "petType" + ] + }, + "Cat": { + "description": "A representation of a cat. Note that `Cat` will be used as the discriminator value.", + "allOf": [ + { + "$ref": "#/components/schemas/Pet" + }, + { + "type": "object", + "properties": { + "huntingSkill": { + "type": "string", + "description": "The measured skill for hunting", + "default": "lazy", + "enum": [ + "clueless", + "lazy", + "adventurous", + "aggressive" + ] + } + }, + "required": [ + "huntingSkill" + ] + } + ] + }, + "Dog": { + "description": "A representation of a dog. Note that `Dog` will be used as the discriminator value.", + "allOf": [ + { + "$ref": "#/components/schemas/Pet" + }, + { + "type": "object", + "properties": { + "packSize": { + "type": "integer", + "format": "int32", + "description": "the size of the pack the dog is from", + "default": 0, + "minimum": 0 + } + }, + "required": [ + "packSize" + ] + } + ] + } + } + } +} +``` + +```yaml +components: + schemas: + Pet: + type: object + discriminator: + propertyName: petType + properties: + name: + type: string + petType: + type: string + required: + - name + - petType + Cat: ## "Cat" will be used as the discriminator value + description: A representation of a cat + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + properties: + huntingSkill: + type: string + description: The measured skill for hunting + enum: + - clueless + - lazy + - adventurous + - aggressive + required: + - huntingSkill + Dog: ## "Dog" will be used as the discriminator value + description: A representation of a dog + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + properties: + packSize: + type: integer + format: int32 + description: the size of the pack the dog is from + default: 0 + minimum: 0 + required: + - packSize +``` + +#### Discriminator Object + +When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the document of an alternative schema based on the value associated with it. + +When using the discriminator, _inline_ schemas will not be considered. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +propertyName | `string` | **REQUIRED**. The name of the property in the payload that will hold the discriminator value. + mapping | Map[`string`, `string`] | An object to hold mappings between payload values and schema names or references. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +The discriminator object is legal only when using one of the composite keywords `oneOf`, `anyOf`, `allOf`. + +In OAS 3.0, a response payload MAY be described to be exactly one of any number of types: + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' +``` + +which means the payload _MUST_, by validation, match exactly one of the schemas described by `Cat`, `Dog`, or `Lizard`. In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use: + + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' + discriminator: + propertyName: petType +``` + +The expectation now is that a property with name `petType` _MUST_ be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload: + +```json +{ + "id": 12345, + "petType": "Cat" +} +``` + +Will indicate that the `Cat` schema be used in conjunction with this payload. + +In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used: + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' + - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json' + discriminator: + propertyName: petType + mapping: + dog: '#/components/schemas/Dog' + monster: 'https://gigantic-server.com/schemas/Monster/schema.json' +``` + +Here the discriminator _value_ of `dog` will map to the schema `#/components/schemas/Dog`, rather than the default (implicit) value of `Dog`. If the discriminator _value_ does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison. + +When used in conjunction with the `anyOf` construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload. + +In both the `oneOf` and `anyOf` use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an `allOf` construct may be used as an alternate schema. + +For example: + +```yaml +components: + schemas: + Pet: + type: object + required: + - petType + properties: + petType: + type: string + discriminator: + propertyName: petType + mapping: + dog: Dog + Cat: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Cat` + properties: + name: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Dog` + properties: + bark: + type: string + Lizard: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Lizard` + properties: + lovesRocks: + type: boolean +``` + +a payload like this: + +```json +{ + "petType": "Cat", + "name": "misty" +} +``` + +will indicate that the `Cat` schema be used. Likewise this schema: + +```json +{ + "petType": "dog", + "bark": "soft" +} +``` + +will map to `Dog` because of the definition in the `mapping` element. + + +#### XML Object + +A metadata object that allows for more fine-tuned XML model definitions. + +When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. +See examples for expected behavior. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +name | `string` | Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. +namespace | `string` | The URI of the namespace definition. This MUST be in the form of an absolute URI. +prefix | `string` | The prefix to be used for the [name](#xmlName). +attribute | `boolean` | Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. +wrapped | `boolean` | MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### XML Object Examples + +The examples of the XML object definitions are included inside a property definition of a [Schema Object](#schemaObject) with a sample of the XML representation of it. + +###### No XML Element + +Basic string property: + +```json +{ + "animals": { + "type": "string" + } +} +``` + +```yaml +animals: + type: string +``` + +```xml +... +``` + +Basic string array property ([`wrapped`](#xmlWrapped) is `false` by default): + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string +``` + +```xml +... +... +... +``` + +###### XML Name Replacement + +```json +{ + "animals": { + "type": "string", + "xml": { + "name": "animal" + } + } +} +``` + +```yaml +animals: + type: string + xml: + name: animal +``` + +```xml +... +``` + + +###### XML Attribute, Prefix and Namespace + +In this example, a full model definition is shown. + +```json +{ + "Person": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32", + "xml": { + "attribute": true + } + }, + "name": { + "type": "string", + "xml": { + "namespace": "https://example.com/schema/sample", + "prefix": "sample" + } + } + } + } +} +``` + +```yaml +Person: + type: object + properties: + id: + type: integer + format: int32 + xml: + attribute: true + name: + type: string + xml: + namespace: https://example.com/schema/sample + prefix: sample +``` + +```xml + + example + +``` + +###### XML Arrays + +Changing the element names: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal +``` + +```xml +value +value +``` + +The external `name` property has no effect on the XML: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens +``` + +```xml +value +value +``` + +Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + wrapped: true +``` + +```xml + + value + value + +``` + +To overcome the naming problem in the example above, the following definition can be used: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + wrapped: true +``` + +```xml + + value + value + +``` + +Affecting both internal and external names: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens + wrapped: true +``` + +```xml + + value + value + +``` + +If we change the external element but not the internal ones: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: aliens + wrapped: true +``` + +```xml + + value + value + +``` + +#### Security Scheme Object + +Defines a security scheme that can be used by the operations. + +Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), mutual TLS (use of a client certificate), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749](https://tools.ietf.org/html/rfc6749), and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06). +Please note that as of 2020, the implicit flow is about to be deprecated by [OAuth 2.0 Security Best Current Practice](https://tools.ietf.org/html/draft-ietf-oauth-security-topics). Recommended for most use case is Authorization Code Grant flow with PKCE. + +##### Fixed Fields +Field Name | Type | Applies To | Description +---|:---:|---|--- +type | `string` | Any | **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"mutualTLS"`, `"oauth2"`, `"openIdConnect"`. +description | `string` | Any | A description for security scheme. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. +name | `string` | `apiKey` | **REQUIRED**. The name of the header, query or cookie parameter to be used. +in | `string` | `apiKey` | **REQUIRED**. The location of the API key. Valid values are `"query"`, `"header"` or `"cookie"`. +scheme | `string` | `http` | **REQUIRED**. The name of the HTTP Authorization scheme to be used in the [Authorization header as defined in RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1). The values used SHOULD be registered in the [IANA Authentication Scheme registry](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml). +bearerFormat | `string` | `http` (`"bearer"`) | A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. +flows | [OAuth Flows Object](#oauthFlowsObject) | `oauth2` | **REQUIRED**. An object containing configuration information for the flow types supported. +openIdConnectUrl | `string` | `openIdConnect` | **REQUIRED**. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL. The OpenID Connect standard requires the use of TLS. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Security Scheme Object Example + +###### Basic Authentication Sample + +```json +{ + "type": "http", + "scheme": "basic" +} +``` + +```yaml +type: http +scheme: basic +``` + +###### API Key Sample + +```json +{ + "type": "apiKey", + "name": "api_key", + "in": "header" +} +``` + +```yaml +type: apiKey +name: api_key +in: header +``` + +###### JWT Bearer Sample + +```json +{ + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT", +} +``` + +```yaml +type: http +scheme: bearer +bearerFormat: JWT +``` + +###### Implicit OAuth2 Sample + +```json +{ + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } +} +``` + +```yaml +type: oauth2 +flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### OAuth Flows Object + +Allows configuration of the supported OAuth Flows. + +##### Fixed Fields +Field Name | Type | Description +---|:---:|--- +implicit| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Implicit flow +password| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Resource Owner Password flow +clientCredentials| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0. +authorizationCode| [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### OAuth Flow Object + +Configuration details for a supported OAuth Flow + +##### Fixed Fields +Field Name | Type | Applies To | Description +---|:---:|---|--- +authorizationUrl | `string` | `oauth2` (`"implicit"`, `"authorizationCode"`) | **REQUIRED**. The authorization URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. +tokenUrl | `string` | `oauth2` (`"password"`, `"clientCredentials"`, `"authorizationCode"`) | **REQUIRED**. The token URL to be used for this flow. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. +refreshUrl | `string` | `oauth2` | The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. The OAuth2 standard requires the use of TLS. +scopes | Map[`string`, `string`] | `oauth2` | **REQUIRED**. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty. + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### OAuth Flow Object Examples + +```JSON +{ + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "authorizationCode": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "tokenUrl": "https://example.com/api/oauth/token", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } +} +``` + +```yaml +type: oauth2 +flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + authorizationCode: + authorizationUrl: https://example.com/api/oauth/dialog + tokenUrl: https://example.com/api/oauth/token + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### Security Requirement Object + +Lists the required security schemes to execute this operation. +The name used for each property MUST correspond to a security scheme declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). + +Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. +This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. + +When a list of Security Requirement Objects is defined on the [OpenAPI Object](#oasObject) or [Operation Object](#operationObject), only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. + +##### Patterned Fields + +Field Pattern | Type | Description +---|:---:|--- +{name} | [`string`] | Each name MUST correspond to a security scheme which is declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). If the security scheme is of type `"oauth2"` or `"openIdConnect"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MAY contain a list of role names which are required for the execution, but are not otherwise defined or exchanged in-band. + +##### Security Requirement Object Examples + +###### Non-OAuth2 Security Requirement + +```json +{ + "api_key": [] +} +``` + +```yaml +api_key: [] +``` + +###### OAuth2 Security Requirement + +```json +{ + "petstore_auth": [ + "write:pets", + "read:pets" + ] +} +``` + +```yaml +petstore_auth: +- write:pets +- read:pets +``` + +###### Optional OAuth2 Security + +Optional OAuth2 security as would be defined in an OpenAPI Object or an Operation Object: + +```json +{ + "security": [ + {}, + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] +} +``` + +```yaml +security: + - {} + - petstore_auth: + - write:pets + - read:pets +``` + +### Specification Extensions + +While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points. + +The extensions properties are implemented as patterned fields that are always prefixed by `"x-"`. + +Field Pattern | Type | Description +---|:---:|--- +^x- | Any | Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. Field names beginning `x-oai-` and `x-oas-` are reserved for uses defined by the [OpenAPI Initiative](https://www.openapis.org/). The value can be `null`, a primitive, an array or an object. + +The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced). + +### Security Filtering + +Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation. + +The reasoning is to allow an additional layer of access control over the documentation. +While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization. + +Two examples of this: + +1. The [Paths Object](#pathsObject) MAY be present but empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They would still have access to at least the [Info Object](#infoObject) which may contain additional information regarding authentication. +2. The [Path Item Object](#pathItemObject) MAY be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different from hiding the path itself from the [Paths Object](#pathsObject), because the user will be aware of its existence. This allows the documentation provider to finely control what the viewer can see. + + +## Appendix A: Revision History + +Version | Date | Notes +--- | --- | --- +3.1.0 | 2021-02-15 | Release of the OpenAPI Specification 3.1.0 +3.1.0-rc1 | 2020-10-08 | rc1 of the 3.1 specification +3.1.0-rc0 | 2020-06-18 | rc0 of the 3.1 specification +3.0.3 | 2020-02-20 | Patch release of the OpenAPI Specification 3.0.3 +3.0.2 | 2018-10-08 | Patch release of the OpenAPI Specification 3.0.2 +3.0.1 | 2017-12-06 | Patch release of the OpenAPI Specification 3.0.1 +3.0.0 | 2017-07-26 | Release of the OpenAPI Specification 3.0.0 +3.0.0-rc2 | 2017-06-16 | rc2 of the 3.0 specification +3.0.0-rc1 | 2017-04-27 | rc1 of the 3.0 specification +3.0.0-rc0 | 2017-02-28 | Implementer's Draft of the 3.0 specification +2.0 | 2015-12-31 | Donation of Swagger 2.0 to the OpenAPI Initiative +2.0 | 2014-09-08 | Release of Swagger 2.0 +1.2 | 2014-03-14 | Initial release of the formal document. +1.1 | 2012-08-22 | Release of Swagger 1.1 +1.0 | 2011-08-10 | First release of the Swagger Specification diff --git a/openapi_python_client/schema/data_type.py b/openapi_python_client/schema/data_type.py index ee597000a..1c104142e 100644 --- a/openapi_python_client/schema/data_type.py +++ b/openapi_python_client/schema/data_type.py @@ -6,6 +6,7 @@ class DataType(str, Enum): References: - https://swagger.io/docs/specification/data-models/data-types/ + - https://json-schema.org/draft/2020-12/json-schema-validation.html#name-type """ STRING = "string" @@ -14,3 +15,4 @@ class DataType(str, Enum): BOOLEAN = "boolean" ARRAY = "array" OBJECT = "object" + NULL = "null" diff --git a/openapi_python_client/schema/openapi_schema_pydantic/open_api.py b/openapi_python_client/schema/openapi_schema_pydantic/open_api.py index 822c42626..6a1b5ae12 100644 --- a/openapi_python_client/schema/openapi_schema_pydantic/open_api.py +++ b/openapi_python_client/schema/openapi_schema_pydantic/open_api.py @@ -1,6 +1,6 @@ -from typing import List, Literal, Optional, Union +from typing import List, Optional -from pydantic import BaseModel, ConfigDict +from pydantic import BaseModel, ConfigDict, field_validator from .components import Components from .external_documentation import ExternalDocumentation @@ -13,6 +13,8 @@ from .server import Server from .tag import Tag +NUM_SEMVER_PARTS = 3 + class OpenAPI(BaseModel): """This is the root document object of the OpenAPI document. @@ -29,8 +31,21 @@ class OpenAPI(BaseModel): security: Optional[List[SecurityRequirement]] = None tags: Optional[List[Tag]] = None externalDocs: Optional[ExternalDocumentation] = None - openapi: Union[Literal["3.0.0"], Literal["3.0.1"], Literal["3.0.2"], Literal["3.0.3"]] + openapi: str model_config = ConfigDict(extra="allow") + @field_validator("openapi") + @classmethod + def check_openapi_version(cls, value: str) -> str: + """Validates that the declared OpenAPI version is a supported one""" + parts = value.split(".") + if len(parts) != NUM_SEMVER_PARTS: + raise ValueError(f"Invalid OpenAPI version {value}") + if parts[0] != "3": + raise ValueError(f"Only OpenAPI versions 3.* are supported, got {value}") + if int(parts[1]) > 1: + raise ValueError(f"Only OpenAPI versions 3.1.* are supported, got {value}") + return value + OpenAPI.model_rebuild() diff --git a/openapi_python_client/schema/openapi_schema_pydantic/schema.py b/openapi_python_client/schema/openapi_schema_pydantic/schema.py index 58cc81e67..b83fa0144 100644 --- a/openapi_python_client/schema/openapi_schema_pydantic/schema.py +++ b/openapi_python_client/schema/openapi_schema_pydantic/schema.py @@ -1,6 +1,6 @@ from typing import Any, Dict, List, Optional, Union -from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, model_validator from ..data_type import DataType from .discriminator import Discriminator @@ -36,7 +36,8 @@ class Schema(BaseModel): minProperties: Optional[int] = Field(default=None, ge=0) required: Optional[List[str]] = Field(default=None, min_length=1) enum: Union[None, List[Optional[StrictInt]], List[Optional[StrictStr]]] = Field(default=None, min_length=1) - type: Optional[DataType] = Field(default=None) + const: Union[None, StrictStr, StrictInt] = None + type: Union[DataType, List[DataType], None] = Field(default=None) allOf: List[Union[Reference, "Schema"]] = Field(default_factory=list) oneOf: List[Union[Reference, "Schema"]] = Field(default_factory=list) anyOf: List[Union[Reference, "Schema"]] = Field(default_factory=list) @@ -47,7 +48,7 @@ class Schema(BaseModel): description: Optional[str] = None schema_format: Optional[str] = Field(default=None, alias="format") default: Optional[Any] = None - nullable: bool = False + nullable: bool = Field(default=False) discriminator: Optional[Discriminator] = None readOnly: Optional[bool] = None writeOnly: Optional[bool] = None @@ -71,10 +72,16 @@ class Schema(BaseModel): }, }, {"type": "object", "additionalProperties": {"type": "string"}}, - {"type": "object", "additionalProperties": {"$ref": "#/components/schemas/ComplexModel"}}, { "type": "object", - "properties": {"id": {"type": "integer", "format": "int64"}, "name": {"type": "string"}}, + "additionalProperties": {"$ref": "#/components/schemas/ComplexModel"}, + }, + { + "type": "object", + "properties": { + "id": {"type": "integer", "format": "int64"}, + "name": {"type": "string"}, + }, "required": ["name"], "example": {"name": "Puma", "id": 1}, }, @@ -89,13 +96,20 @@ class Schema(BaseModel): { "allOf": [ {"$ref": "#/components/schemas/ErrorModel"}, - {"type": "object", "required": ["rootCause"], "properties": {"rootCause": {"type": "string"}}}, + { + "type": "object", + "required": ["rootCause"], + "properties": {"rootCause": {"type": "string"}}, + }, ] }, { "type": "object", "discriminator": {"propertyName": "petType"}, - "properties": {"name": {"type": "string"}, "petType": {"type": "string"}}, + "properties": { + "name": {"type": "string"}, + "petType": {"type": "string"}, + }, "required": ["name", "petType"], }, { @@ -110,7 +124,12 @@ class Schema(BaseModel): "type": "string", "description": "The measured skill for hunting", "default": "lazy", - "enum": ["clueless", "lazy", "adventurous", "aggressive"], + "enum": [ + "clueless", + "lazy", + "adventurous", + "aggressive", + ], } }, "required": ["huntingSkill"], @@ -141,5 +160,24 @@ class Schema(BaseModel): }, ) + @model_validator(mode="after") + def handle_nullable(self) -> "Schema": + """Convert the old 3.0 `nullable` property into the new 3.1 style""" + if not self.nullable: + return self + if isinstance(self.type, str): + self.type = [self.type, DataType.NULL] + elif isinstance(self.type, list): + if DataType.NULL not in self.type: + self.type.append(DataType.NULL) + elif len(self.oneOf) > 0: + self.oneOf.append(Schema(type=DataType.NULL)) + elif len(self.anyOf) > 0: + self.anyOf.append(Schema(type=DataType.NULL)) + elif len(self.allOf) > 0: # Nullable allOf is basically oneOf[null, allOf] + self.oneOf = [Schema(type=DataType.NULL), Schema(allOf=self.allOf)] + self.allOf = [] + return self + Schema.model_rebuild() diff --git a/openapi_python_client/templates/endpoint_macros.py.jinja b/openapi_python_client/templates/endpoint_macros.py.jinja index 000f2c368..f5904a509 100644 --- a/openapi_python_client/templates/endpoint_macros.py.jinja +++ b/openapi_python_client/templates/endpoint_macros.py.jinja @@ -32,6 +32,7 @@ cookies["{{ parameter.name}}"] = {{ parameter.python_name }} if {{ parameter.python_name }} is not UNSET: cookies["{{ parameter.name}}"] = {{ parameter.python_name }} {% endif %} + {% endfor %} {% endif %} {% endmacro %} @@ -40,6 +41,7 @@ if {{ parameter.python_name }} is not UNSET: {% macro query_params(endpoint) %} {% if endpoint.query_parameters %} params: Dict[str, Any] = {} + {% for property in endpoint.query_parameters.values() %} {% set destination = property.python_name %} {% import "property_templates/" + property.template as prop_template %} @@ -53,7 +55,6 @@ params["{{ property.name }}"] = {{ destination }} {{ guarded_statement(property, destination, "params.update(" + destination + ")") }} {% endif %} - {% endfor %} params = {k: v for k, v in params.items() if v is not UNSET and v is not None} diff --git a/openapi_python_client/templates/errors.py.jinja b/openapi_python_client/templates/errors.py.jinja index 514d3c1b9..4042ff730 100644 --- a/openapi_python_client/templates/errors.py.jinja +++ b/openapi_python_client/templates/errors.py.jinja @@ -1,7 +1,7 @@ """ Contains shared errors types that can be raised from API functions """ class UnexpectedStatus(Exception): - """ Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True """ + """Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True""" def __init__(self, status_code: int, content: bytes): self.status_code = status_code diff --git a/openapi_python_client/templates/model.py.jinja b/openapi_python_client/templates/model.py.jinja index 3d5b55515..f8864b343 100644 --- a/openapi_python_client/templates/model.py.jinja +++ b/openapi_python_client/templates/model.py.jinja @@ -87,6 +87,7 @@ class {{ class_name }}: {% else %} {{ property.python_name }} = self.{{ property.python_name }} {% endif %} + {% endfor %} field_dict: Dict[str, Any] = {} diff --git a/openapi_python_client/templates/property_templates/date_property.py.jinja b/openapi_python_client/templates/property_templates/date_property.py.jinja index 2107c5cb5..c1f8b668f 100644 --- a/openapi_python_client/templates/property_templates/date_property.py.jinja +++ b/openapi_python_client/templates/property_templates/date_property.py.jinja @@ -16,8 +16,8 @@ isoparse({{ source }}).date() {% set transformed = transformed + ".encode()" %} {% endif %} {% if property.required %} -{{ destination }} = {{ transformed }} {% if property.nullable %}if {{ source }} else None {%endif%} -{% else %} +{{ destination }} = {{ transformed }} +{%- else %} {% if declare_type %} {% set type_annotation = property.get_type_string(json=True) %} {% if multipart %}{% set type_annotation = type_annotation | replace("str", "bytes") %}{% endif %} @@ -26,10 +26,6 @@ isoparse({{ source }}).date() {{ destination }} = UNSET {% endif %} if not isinstance({{ source }}, Unset): -{% if property.nullable %} - {{ destination }} = {{ transformed }} if {{ source }} else None -{% else %} {{ destination }} = {{ transformed }} -{% endif %} -{% endif %} +{%- endif %} {% endmacro %} diff --git a/openapi_python_client/templates/property_templates/datetime_property.py.jinja b/openapi_python_client/templates/property_templates/datetime_property.py.jinja index 29a2b417d..18673087e 100644 --- a/openapi_python_client/templates/property_templates/datetime_property.py.jinja +++ b/openapi_python_client/templates/property_templates/datetime_property.py.jinja @@ -16,12 +16,8 @@ isoparse({{ source }}) {% set transformed = transformed + ".encode()" %} {% endif %} {% if property.required %} -{% if property.nullable %} -{{ destination }} = {{ transformed }} if {{ source }} else None -{% else %} {{ destination }} = {{ transformed }} -{% endif %} -{% else %} +{%- else %} {% if declare_type %} {% set type_annotation = property.get_type_string(json=True) %} {% if multipart %}{% set type_annotation = type_annotation | replace("str", "bytes") %}{% endif %} @@ -30,10 +26,6 @@ isoparse({{ source }}) {{ destination }} = UNSET {% endif %} if not isinstance({{ source }}, Unset): -{% if property.nullable %} - {{ destination }} = {{ transformed }} if {{ source }} else None -{% else %} {{ destination }} = {{ transformed }} -{% endif %} -{% endif %} +{%- endif %} {% endmacro %} diff --git a/openapi_python_client/templates/property_templates/enum_property.py.jinja b/openapi_python_client/templates/property_templates/enum_property.py.jinja index 2e9a55520..08744ee90 100644 --- a/openapi_python_client/templates/property_templates/enum_property.py.jinja +++ b/openapi_python_client/templates/property_templates/enum_property.py.jinja @@ -18,20 +18,12 @@ {% set type_string = "Union[Unset, Tuple[None, bytes, str]]" %} {% endif %} {% if property.required %} -{% if property.nullable %} -{{ destination }} = {{ transformed }} if {{ source }} else None -{% else %} {{ destination }} = {{ transformed }} -{% endif %} -{% else %} +{%- else %} {{ destination }}{% if declare_type %}: {{ type_string }}{% endif %} = UNSET if not isinstance({{ source }}, Unset): -{% if property.nullable %} - {{ destination }} = {{ transformed }} if {{ source }} else None -{% else %} {{ destination }} = {{ transformed }} {% endif %} -{% endif %} {% endmacro %} {% macro transform_header(source) %} diff --git a/openapi_python_client/templates/property_templates/file_property.py.jinja b/openapi_python_client/templates/property_templates/file_property.py.jinja index b2fec1fa8..f9d6f3ed1 100644 --- a/openapi_python_client/templates/property_templates/file_property.py.jinja +++ b/openapi_python_client/templates/property_templates/file_property.py.jinja @@ -14,18 +14,10 @@ File( {% macro transform(property, source, destination, declare_type=True, multipart=False) %} {% if property.required %} -{% if property.nullable %} -{{ destination }} = {{ source }}.to_tuple() if {{ source }} else None -{% else %} {{ destination }} = {{ source }}.to_tuple() -{% endif %} {% else %} {{ destination }}{% if declare_type %}: {{ property.get_type_string(json=True) }}{% endif %} = UNSET if not isinstance({{ source }}, Unset): -{% if property.nullable %} - {{ destination }} = {{ source }}.to_tuple() if {{ source }} else None -{% else %} {{ destination }} = {{ source }}.to_tuple() {% endif %} -{% endif %} {% endmacro %} diff --git a/openapi_python_client/templates/property_templates/helpers.jinja b/openapi_python_client/templates/property_templates/helpers.jinja index 33c753df5..3f238f696 100644 --- a/openapi_python_client/templates/property_templates/helpers.jinja +++ b/openapi_python_client/templates/property_templates/helpers.jinja @@ -1,18 +1,10 @@ {% macro guarded_statement(property, source, statement) %} {# If the property can be UNSET or None, this macro returns the provided statement guarded by an if which will check for those invalid values. Otherwise, it returns the statement unmodified. #} -{% if property.required and not property.nullable %} +{% if property.required %} {{ statement }} {% else %} - {% if property.nullable and not property.required %} -if not isinstance({{ source }}, Unset) and {{ source }} is not None: - {{ statement }} - {% elif property.nullable %} -if {{ source }} is not None: - {{ statement }} - {% else %} if not isinstance({{ source }}, Unset): {{ statement }} - {% endif %} {% endif %} {% endmacro %} diff --git a/openapi_python_client/templates/property_templates/list_property.py.jinja b/openapi_python_client/templates/property_templates/list_property.py.jinja index 9686f6930..075160cf9 100644 --- a/openapi_python_client/templates/property_templates/list_property.py.jinja +++ b/openapi_python_client/templates/property_templates/list_property.py.jinja @@ -5,7 +5,7 @@ {% set inner_source = inner_property.python_name + "_data" %} {{ property.python_name }} = {{ initial_value }} _{{ property.python_name }} = {{ source }} -{% if property.required and not property.nullable %} +{% if property.required %} for {{ inner_source }} in (_{{ property.python_name }}): {% else %} for {{ inner_source }} in (_{{ property.python_name }} or []): @@ -48,26 +48,12 @@ for {{ inner_source }} in {{ source }}: {% set type_string = property.get_type_string(json=True) %} {% endif %} {% if property.required %} -{% if property.nullable %} -if {{ source }} is None: - {{ destination }} = None -else: - {{ _transform(property, source, destination, multipart, transform_method) | indent(4) }} -{% else %} {{ _transform(property, source, destination, multipart, transform_method) }} -{% endif %} {% else %} {{ destination }}{% if declare_type %}: {{ type_string }}{% endif %} = UNSET if not isinstance({{ source }}, Unset): -{% if property.nullable %} - if {{ source }} is None: - {{ destination }} = None - else: - {{ _transform(property, source, destination, multipart, transform_method) | indent(8)}} -{% else %} {{ _transform(property, source, destination, multipart, transform_method) | indent(4)}} {% endif %} -{% endif %} {% endmacro %} diff --git a/openapi_python_client/templates/property_templates/model_property.py.jinja b/openapi_python_client/templates/property_templates/model_property.py.jinja index 903aeefaa..bdfd3cca5 100644 --- a/openapi_python_client/templates/property_templates/model_property.py.jinja +++ b/openapi_python_client/templates/property_templates/model_property.py.jinja @@ -14,25 +14,17 @@ {% set transformed = source + "." + transform_method + "()" %} {% if multipart %} {% set transformed = "(None, json.dumps(" + transformed + ").encode(), 'application/json')" %} - {% set type_string = "Union[Unset, Tuple[None, bytes, str]]" %} + {% set type_string = property.get_type_string(multipart=True) %} {% else %} {% set type_string = property.get_type_string(json=True) %} {% endif %} {% if property.required %} -{% if property.nullable %} -{{ destination }} = {{ transformed }} if {{ source }} else None -{% else %} {{ destination }} = {{ transformed }} -{% endif %} -{% else %} +{%- else %} {{ destination }}{% if declare_type %}: {{ type_string }}{% endif %} = UNSET if not isinstance({{ source }}, Unset): -{% if property.nullable %} - {{ destination }} = {{ transformed }} if {{ source }} else None -{% else %} {{ destination }} = {{ transformed }} -{% endif %} -{% endif %} +{%- endif %} {% endmacro %} {% macro transform_multipart(property, source, destination) %} diff --git a/openapi_python_client/templates/property_templates/property_macros.py.jinja b/openapi_python_client/templates/property_templates/property_macros.py.jinja index d578d1d4f..43adf4c06 100644 --- a/openapi_python_client/templates/property_templates/property_macros.py.jinja +++ b/openapi_python_client/templates/property_templates/property_macros.py.jinja @@ -1,16 +1,11 @@ {% macro construct_template(construct_function, property, source, initial_value=None) %} -{% if property.required and not property.nullable %} +{% if property.required %} {{ property.python_name }} = {{ construct_function(property, source) }} -{% else %}{# Must be nullable OR non-required #} +{% else %}{# Must be non-required #} _{{ property.python_name }} = {{ source }} {{ property.python_name }}: {{ property.get_type_string() }} - {% if property.nullable %} -if _{{ property.python_name }} is None: - {{ property.python_name }} = {% if initial_value != None %}{{ initial_value }}{% else %}None{% endif %} - - {% endif %} {% if not property.required %} -{% if property.nullable %}elif{% else %}if{% endif %} isinstance(_{{ property.python_name }}, Unset): +if isinstance(_{{ property.python_name }}, Unset): {{ property.python_name }} = {% if initial_value != None %}{{ initial_value }}{% else %}UNSET{% endif %} {% endif %} diff --git a/openapi_python_client/templates/property_templates/union_property.py.jinja b/openapi_python_client/templates/property_templates/union_property.py.jinja index 4d43fafc0..df77be05b 100644 --- a/openapi_python_client/templates/property_templates/union_property.py.jinja +++ b/openapi_python_client/templates/property_templates/union_property.py.jinja @@ -1,10 +1,10 @@ {% macro construct(property, source, initial_value=None) %} def _parse_{{ property.python_name }}(data: object) -> {{ property.get_type_string() }}: - {% if "None" in property.get_type_strings_in_union(json=True) %} + {% if "None" in property.get_type_strings_in_union(json=True, multipart=False) %} if data is None: return data {% endif %} - {% if "Unset" in property.get_type_strings_in_union(json=True) %} + {% if "Unset" in property.get_type_strings_in_union(json=True, multipart=False) %} if isinstance(data, Unset): return data {% endif %} @@ -41,23 +41,13 @@ def _parse_{{ property.python_name }}(data: object) -> {{ property.get_type_stri {% macro transform(property, source, destination, declare_type=True, multipart=False) %} {% set ns = namespace(contains_properties_without_transform = false, contains_modified_properties = not property.required, has_if = false) %} -{% if declare_type %}{{ destination }}: {{ property.get_type_string(json=True) }}{% endif %} +{% if declare_type %}{{ destination }}: {{ property.get_type_string(json=not multipart, multipart=multipart) }}{% endif %} {% if not property.required %} if isinstance({{ source }}, Unset): {{ destination }} = UNSET {% set ns.has_if = true %} {% endif %} -{% if property.nullable %} - {% if ns.has_if %} -elif {{ source }} is None: - {% else %} -if {{ source }} is None: - {% set ns.has_if = true %} - {% endif %} - {{ destination }} = None -{% endif %} - {% for inner_property in property.inner_properties %} {% import "property_templates/" + inner_property.template as inner_template %} {% if not inner_template.transform %} @@ -79,8 +69,7 @@ else: {% if ns.contains_properties_without_transform and ns.contains_modified_properties %} else: {{ destination }} = {{ source }} -{% elif ns.contains_properties_without_transform %} +{%- elif ns.contains_properties_without_transform %} {{ destination }} = {{ source }} -{% endif %} - +{%- endif %} {% endmacro %} diff --git a/tests/conftest.py b/tests/conftest.py index 21428eaee..a8a45cf0e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -14,7 +14,6 @@ ListProperty, ModelProperty, NoneProperty, - Property, StringProperty, UnionProperty, ) @@ -74,21 +73,6 @@ def _factory(**kwargs): return _factory -@pytest.fixture -def property_factory() -> Callable[..., Property]: - """ - This fixture surfaces in the test as a function which manufactures Properties with defaults. - - You can pass the same params into this as the Property constructor to override defaults. - """ - - def _factory(**kwargs): - kwargs = _common_kwargs(kwargs) - return Property(**kwargs) - - return _factory - - @pytest.fixture def any_property_factory() -> Callable[..., AnyProperty]: """ @@ -266,7 +250,6 @@ def _common_kwargs(kwargs: Dict[str, Any]) -> Dict[str, Any]: kwargs = { "name": "test", "required": True, - "nullable": False, "default": None, "description": None, "example": None, diff --git a/tests/test_parser/test_openapi.py b/tests/test_parser/test_openapi.py index 8932b2f6f..b304271d7 100644 --- a/tests/test_parser/test_openapi.py +++ b/tests/test_parser/test_openapi.py @@ -625,7 +625,10 @@ def test_add_parameters_parse_error(self, mocker): config=config, ) assert (result, schemas, parameters) == ( - ParseError(data=parse_error.data, detail=f"cannot parse parameter of endpoint {endpoint.name}"), + ParseError( + data=parse_error.data, + detail=f"cannot parse parameter of endpoint {endpoint.name}: {parse_error.detail}", + ), initial_schemas, initial_parameters, ) @@ -690,15 +693,15 @@ def test_validation_error_when_location_not_supported(self, mocker): with pytest.raises(pydantic.ValidationError): oai.Parameter(name="test", required=True, param_schema=mocker.MagicMock(), param_in="error_location") - def test__add_parameters_with_location_postfix_conflict1(self, mocker, property_factory): + def test__add_parameters_with_location_postfix_conflict1(self, mocker, any_property_factory): """Checks when the PythonIdentifier of new parameter already used.""" from openapi_python_client.parser.openapi import Endpoint endpoint = self.make_endpoint() - path_prop_conflicted = property_factory(name="prop_name_path", required=True, nullable=False, default=None) - query_prop = property_factory(name="prop_name", required=True, nullable=False, default=None) - path_prop = property_factory(name="prop_name", required=True, nullable=False, default=None) + path_prop_conflicted = any_property_factory(name="prop_name_path", required=True, default=None) + query_prop = any_property_factory(name="prop_name", required=True, default=None) + path_prop = any_property_factory(name="prop_name", required=True, default=None) schemas_1 = mocker.MagicMock() schemas_2 = mocker.MagicMock() @@ -740,14 +743,14 @@ def test__add_parameters_with_location_postfix_conflict1(self, mocker, property_ assert isinstance(result, ParseError) assert result.detail == "Parameters with same Python identifier `prop_name_path` detected" - def test__add_parameters_with_location_postfix_conflict2(self, mocker, property_factory): + def test__add_parameters_with_location_postfix_conflict2(self, mocker, any_property_factory): """Checks when an existing parameter has a conflicting PythonIdentifier after renaming.""" from openapi_python_client.parser.openapi import Endpoint endpoint = self.make_endpoint() - path_prop_conflicted = property_factory(name="prop_name_path", required=True, nullable=False, default=None) - path_prop = property_factory(name="prop_name", required=True, nullable=False, default=None) - query_prop = property_factory(name="prop_name", required=True, nullable=False, default=None) + path_prop_conflicted = any_property_factory(name="prop_name_path", required=True, default=None) + path_prop = any_property_factory(name="prop_name", required=True, default=None) + query_prop = any_property_factory(name="prop_name", required=True, default=None) schemas_1 = mocker.MagicMock() schemas_2 = mocker.MagicMock() schemas_3 = mocker.MagicMock() @@ -815,7 +818,7 @@ def test__add_parameters_resolves_references(self, mocker, param_factory): ) parameters = mocker.MagicMock() - new_param = param_factory(name="blah", schema=oai.Schema.model_construct(nullable=False, type="string")) + new_param = param_factory(name="blah", schema=oai.Schema.model_construct(type="string")) parameters.classes_by_name = { "blah": new_param, } @@ -854,19 +857,19 @@ def test__add_parameters_same_identifier_conflict(self): oai.Parameter.model_construct( name="param", param_in="path", - param_schema=oai.Schema.model_construct(nullable=False, type="string"), + param_schema=oai.Schema.model_construct(type="string"), required=True, ), oai.Parameter.model_construct( name="param_path", param_in="path", - param_schema=oai.Schema.model_construct(nullable=False, type="string"), + param_schema=oai.Schema.model_construct(type="string"), required=True, ), oai.Parameter.model_construct( name="param", param_in="query", - param_schema=oai.Schema.model_construct(nullable=False, type="string"), + param_schema=oai.Schema.model_construct(type="string"), ), ] ) @@ -883,27 +886,15 @@ def test__add_parameters_query_optionality(self): data = oai.Operation.model_construct( parameters=[ oai.Parameter.model_construct( - name="not_null_not_required", - required=False, - param_schema=oai.Schema.model_construct(nullable=False, type="string"), - param_in="query", - ), - oai.Parameter.model_construct( - name="not_null_required", - required=True, - param_schema=oai.Schema.model_construct(nullable=False, type="string"), - param_in="query", - ), - oai.Parameter.model_construct( - name="null_not_required", + name="not_required", required=False, - param_schema=oai.Schema.model_construct(nullable=True, type="string"), + param_schema=oai.Schema.model_construct(type="string"), param_in="query", ), oai.Parameter.model_construct( - name="null_required", + name="required", required=True, - param_schema=oai.Schema.model_construct(nullable=True, type="string"), + param_schema=oai.Schema.model_construct(type="string"), param_in="query", ), ] @@ -913,13 +904,11 @@ def test__add_parameters_query_optionality(self): endpoint=endpoint, data=data, schemas=Schemas(), parameters=Parameters(), config=Config() ) - assert len(endpoint.query_parameters) == 4, "Not all query params were added" # noqa: PLR2004 + assert len(endpoint.query_parameters) == 2, "Not all query params were added" # noqa: PLR2004 for param in endpoint.query_parameters.values(): - if param.name == "not_null_required": - assert not param.nullable + if param.name == "required": assert param.required else: - assert param.nullable assert not param.required def test_add_parameters_duplicate_properties(self): diff --git a/tests/test_parser/test_properties/test_any.py b/tests/test_parser/test_properties/test_any.py new file mode 100644 index 000000000..7738a24f9 --- /dev/null +++ b/tests/test_parser/test_properties/test_any.py @@ -0,0 +1,12 @@ +from openapi_python_client.parser.properties import AnyProperty + + +def test_default(): + AnyProperty.build( + name="test", + required=True, + default=42, + python_name="test", + description="test", + example="test", + ) diff --git a/tests/test_parser/test_properties/test_boolean.py b/tests/test_parser/test_properties/test_boolean.py new file mode 100644 index 000000000..0c4abf0f3 --- /dev/null +++ b/tests/test_parser/test_properties/test_boolean.py @@ -0,0 +1,54 @@ +import pytest + +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import BooleanProperty + + +def test_invalid_default_value(): + err = BooleanProperty.build( + default="not a boolean", + description=None, + example=None, + required=False, + python_name="not_a_boolean", + name="not_a_boolean", + ) + + assert isinstance(err, PropertyError) + + +@pytest.mark.parametrize( + ("value", "expected"), + ( + ("true", "True"), + ("True", "True"), + ("false", "False"), + ("False", "False"), + ), +) +def test_string_default(value, expected): + prop = BooleanProperty.build( + default=value, + description=None, + example=None, + required=False, + python_name="not_a_boolean", + name="not_a_boolean", + ) + + assert isinstance(prop, BooleanProperty) + assert prop.default == expected + + +def test_bool_default(): + prop = BooleanProperty.build( + default=True, + description=None, + example=None, + required=False, + python_name="not_a_boolean", + name="not_a_boolean", + ) + + assert isinstance(prop, BooleanProperty) + assert prop.default == "True" diff --git a/tests/test_parser/test_properties/test_const.py b/tests/test_parser/test_properties/test_const.py new file mode 100644 index 000000000..6d2ad0bfe --- /dev/null +++ b/tests/test_parser/test_properties/test_const.py @@ -0,0 +1,55 @@ +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import ConstProperty +from openapi_python_client.parser.properties.protocol import Value + + +def test_default_doesnt_match_const(): + err = ConstProperty.build( + name="test", + required=True, + default="not the value", + python_name="test", + description=None, + const="the value", + ) + + assert isinstance(err, PropertyError) + + +def test_non_string_const(): + prop = ConstProperty.build( + name="test", + required=True, + default=123, + python_name="test", + description=None, + const=123, + ) + + assert isinstance(prop, ConstProperty) + + +def test_const_already_converted(): + prop = ConstProperty.build( + name="test", + required=True, + default=123, + python_name="test", + description=None, + const=Value("123"), + ) + + assert isinstance(prop, ConstProperty) + + +def test_default_already_converted(): + prop = ConstProperty.build( + name="test", + required=True, + default=Value("123"), + python_name="test", + description=None, + const=123, + ) + + assert isinstance(prop, ConstProperty) diff --git a/tests/test_parser/test_properties/test_converter.py b/tests/test_parser/test_properties/test_converter.py deleted file mode 100644 index 07ca1cbf3..000000000 --- a/tests/test_parser/test_properties/test_converter.py +++ /dev/null @@ -1,41 +0,0 @@ -import pytest - -from openapi_python_client.parser.errors import ValidationError -from openapi_python_client.parser.properties.converter import convert, convert_chain - - -def test_convert_none(): - assert convert("blah", None) is None - - -def test_convert_bad_type(): - with pytest.raises(ValidationError): - assert convert("blah", "blah") - - -def test_convert_exception(): - with pytest.raises(ValidationError): - assert convert("datetime.datetime", "blah") - - -def test_convert_str(): - # This looks ugly, but it outputs in jinja as '\\"str\\"' - # The extra escape of " is not necessary but the code is overly cautious - assert convert("str", '"str"') == "'\\\\\"str\\\\\"'" - - -def test_convert_datetime(): - assert convert("datetime.datetime", "2021-01-20") == "isoparse('2021-01-20')" - - -def test_convert_date(): - assert convert("datetime.date", "2021-01-20") == "isoparse('2021-01-20').date()" - - -def test_convert_chain_no_valid(): - with pytest.raises(ValidationError): - convert_chain(("int",), "a") - - -def test_convert_chain(): - assert convert_chain(("int", "bool"), "a") diff --git a/tests/test_parser/test_properties/test_date.py b/tests/test_parser/test_properties/test_date.py new file mode 100644 index 000000000..0c70b5c30 --- /dev/null +++ b/tests/test_parser/test_properties/test_date.py @@ -0,0 +1,33 @@ +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import DateProperty +from openapi_python_client.parser.properties.protocol import Value + + +def test_invalid_default_value(): + err = DateProperty.build( + default="not a date", + description=None, + example=None, + required=False, + python_name="not_a_date", + name="not_a_date", + ) + + assert isinstance(err, PropertyError) + + +def test_default_with_bad_type(): + err = DateProperty.build( + default=123, + description=None, + example=None, + required=False, + python_name="not_a_date", + name="not_a_date", + ) + + assert isinstance(err, PropertyError) + + +def test_dont_recheck_value(): + DateProperty.convert_value(Value("not a date but trust me")) diff --git a/tests/test_parser/test_properties/test_datetime.py b/tests/test_parser/test_properties/test_datetime.py new file mode 100644 index 000000000..7853208d7 --- /dev/null +++ b/tests/test_parser/test_properties/test_datetime.py @@ -0,0 +1,33 @@ +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import DateTimeProperty +from openapi_python_client.parser.properties.protocol import Value + + +def test_invalid_default_value(): + err = DateTimeProperty.build( + default="not a date", + description=None, + example=None, + required=False, + python_name="not_a_date", + name="not_a_date", + ) + + assert isinstance(err, PropertyError) + + +def test_default_with_bad_type(): + err = DateTimeProperty.build( + default=123, + description=None, + example=None, + required=False, + python_name="not_a_date", + name="not_a_date", + ) + + assert isinstance(err, PropertyError) + + +def test_dont_recheck_value(): + DateTimeProperty.convert_value(Value("not a date but trust me")) diff --git a/tests/test_parser/test_properties/test_enum_property.py b/tests/test_parser/test_properties/test_enum_property.py new file mode 100644 index 000000000..dc41a9f51 --- /dev/null +++ b/tests/test_parser/test_properties/test_enum_property.py @@ -0,0 +1,61 @@ +import openapi_python_client.schema as oai +from openapi_python_client import Config +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import EnumProperty, Schemas + + +def test_conflict(): + data = oai.Schema() + schemas = Schemas() + + _, schemas = EnumProperty.build( + data=data, name="Existing", required=True, schemas=schemas, enum=["a"], parent_name="", config=Config() + ) + err, new_schemas = EnumProperty.build( + data=data, + name="Existing", + required=True, + schemas=schemas, + enum=["a", "b"], + parent_name="", + config=Config(), + ) + + assert schemas == new_schemas + assert err == PropertyError(detail="Found conflicting enums named Existing with incompatible values.", data=data) + + +def test_no_values(): + data = oai.Schema() + schemas = Schemas() + + err, new_schemas = EnumProperty.build( + data=data, name="Existing", required=True, schemas=schemas, enum=[], parent_name=None, config=Config() + ) + + assert schemas == new_schemas + assert err == PropertyError(detail="No values provided for Enum", data=data) + + +def test_bad_default_value(): + data = oai.Schema(default="B") + schemas = Schemas() + + err, new_schemas = EnumProperty.build( + data=data, name="Existing", required=True, schemas=schemas, enum=["A"], parent_name=None, config=Config() + ) + + assert schemas == new_schemas + assert err == PropertyError(detail="Value B is not valid for enum Existing", data=data) + + +def test_bad_default_type(): + data = oai.Schema(default=123) + schemas = Schemas() + + err, new_schemas = EnumProperty.build( + data=data, name="Existing", required=True, schemas=schemas, enum=["A"], parent_name=None, config=Config() + ) + + assert schemas == new_schemas + assert isinstance(err, PropertyError) diff --git a/tests/test_parser/test_properties/test_file.py b/tests/test_parser/test_properties/test_file.py new file mode 100644 index 000000000..87298ba03 --- /dev/null +++ b/tests/test_parser/test_properties/test_file.py @@ -0,0 +1,15 @@ +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import FileProperty + + +def test_no_default_allowed(): + err = FileProperty.build( + default="not none", + description=None, + example=None, + required=False, + python_name="not_none", + name="not_none", + ) + + assert isinstance(err, PropertyError) diff --git a/tests/test_parser/test_properties/test_float.py b/tests/test_parser/test_properties/test_float.py new file mode 100644 index 000000000..9d1159409 --- /dev/null +++ b/tests/test_parser/test_properties/test_float.py @@ -0,0 +1,43 @@ +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import FloatProperty +from openapi_python_client.parser.properties.protocol import Value + + +def test_invalid_default(): + err = FloatProperty.build( + default="not a float", + description=None, + example=None, + required=False, + python_name="not_a_float", + name="not_a_float", + ) + + assert isinstance(err, PropertyError) + + +def test_convert_from_string(): + val = FloatProperty.convert_value("1.0") + assert isinstance(val, Value) + assert val == "1.0" + assert FloatProperty.convert_value("1") == "1.0" + + +def test_convert_from_float(): + val = FloatProperty.convert_value(1.0) + assert isinstance(val, Value) + assert val == "1.0" + assert FloatProperty.convert_value(1) == "1.0" + + +def test_invalid_type_default(): + err = FloatProperty.build( + default=True, + description=None, + example=None, + required=False, + python_name="not_a_float", + name="not_a_float", + ) + + assert isinstance(err, PropertyError) diff --git a/tests/test_parser/test_properties/test_init.py b/tests/test_parser/test_properties/test_init.py index ac1d65f91..50f3559e0 100644 --- a/tests/test_parser/test_properties/test_init.py +++ b/tests/test_parser/test_properties/test_init.py @@ -1,4 +1,3 @@ -from typing import Type from unittest.mock import MagicMock, call import attr @@ -6,8 +5,14 @@ import openapi_python_client.schema as oai from openapi_python_client import Config -from openapi_python_client.parser.errors import ParameterError, PropertyError, ValidationError -from openapi_python_client.parser.properties import BooleanProperty, FloatProperty, IntProperty, Property, Schemas +from openapi_python_client.parser.errors import ParameterError, PropertyError +from openapi_python_client.parser.properties import ( + ListProperty, + Schemas, + StringProperty, + UnionProperty, +) +from openapi_python_client.schema import DataType MODULE_NAME = "openapi_python_client.parser.properties" @@ -17,16 +22,14 @@ def test_is_base_type(self, string_property_factory): assert string_property_factory().is_base_type is True @pytest.mark.parametrize( - "required, nullable, expected", + "required, expected", ( - (True, False, "str"), - (True, True, "Optional[str]"), - (False, True, "Union[Unset, None, str]"), - (False, False, "Union[Unset, str]"), + (True, "str"), + (False, "Union[Unset, str]"), ), ) - def test_get_type_string(self, string_property_factory, required, nullable, expected): - p = string_property_factory(required=required, nullable=nullable) + def test_get_type_string(self, string_property_factory, required, expected): + p = string_property_factory(required=required) assert p.get_type_string() == expected @@ -36,17 +39,14 @@ def test_is_base_type(self, date_time_property_factory): assert date_time_property_factory().is_base_type is True @pytest.mark.parametrize("required", (True, False)) - @pytest.mark.parametrize("nullable", (True, False)) - def test_get_imports(self, date_time_property_factory, required, nullable): - p = date_time_property_factory(required=required, nullable=nullable) + def test_get_imports(self, date_time_property_factory, required): + p = date_time_property_factory(required=required) expected = { "import datetime", "from typing import cast", "from dateutil.parser import isoparse", } - if nullable: - expected.add("from typing import Optional") if not required: expected |= { "from typing import Union", @@ -61,17 +61,14 @@ def test_is_base_type(self, date_property_factory): assert date_property_factory().is_base_type is True @pytest.mark.parametrize("required", (True, False)) - @pytest.mark.parametrize("nullable", (True, False)) - def test_get_imports(self, date_property_factory, required, nullable): - p = date_property_factory(required=required, nullable=nullable) + def test_get_imports(self, date_property_factory, required): + p = date_property_factory(required=required) expected = { "import datetime", "from typing import cast", "from dateutil.parser import isoparse", } - if nullable: - expected.add("from typing import Optional") if not required: expected |= { "from typing import Union", @@ -86,16 +83,13 @@ def test_is_base_type(self, file_property_factory): assert file_property_factory().is_base_type is True @pytest.mark.parametrize("required", (True, False)) - @pytest.mark.parametrize("nullable", (True, False)) - def test_get_imports(self, file_property_factory, required, nullable): - p = file_property_factory(required=required, nullable=nullable) + def test_get_imports(self, file_property_factory, required): + p = file_property_factory(required=required) expected = { "from io import BytesIO", "from ...types import File, FileJsonType", } - if nullable: - expected.add("from typing import Optional") if not required: expected |= { "from typing import Union", @@ -150,33 +144,27 @@ def test_get_lazy_import_model_inner(self, list_property_factory, model_property assert p.get_lazy_imports(prefix="..") == {"from ..models.my_module import MyClass"} @pytest.mark.parametrize( - "required, nullable, expected", + "required, expected", ( - (True, False, "List[str]"), - (True, True, "Optional[List[str]]"), - (False, False, "Union[Unset, List[str]]"), - (False, True, "Union[Unset, None, List[str]]"), + (True, "List[str]"), + (False, "Union[Unset, List[str]]"), ), ) - def test_get_type_string_base_inner(self, list_property_factory, required, nullable, expected): - p = list_property_factory(required=required, nullable=nullable) + def test_get_type_string_base_inner(self, list_property_factory, required, expected): + p = list_property_factory(required=required) assert p.get_type_string() == expected @pytest.mark.parametrize( - "required, nullable, expected", + "required, expected", ( - (True, False, "List['MyClass']"), - (True, True, "Optional[List['MyClass']]"), - (False, False, "Union[Unset, List['MyClass']]"), - (False, True, "Union[Unset, None, List['MyClass']]"), + (True, "List['MyClass']"), + (False, "Union[Unset, List['MyClass']]"), ), ) - def test_get_type_string_model_inner( - self, list_property_factory, model_property_factory, required, nullable, expected - ): + def test_get_type_string_model_inner(self, list_property_factory, model_property_factory, required, expected): m = model_property_factory() - p = list_property_factory(required=required, nullable=nullable, inner_property=m) + p = list_property_factory(required=required, inner_property=m) assert p.get_type_string() == expected @@ -204,18 +192,15 @@ def test_get_base_type_string_model_inner(self, list_property_factory, model_pro assert p.get_base_type_string(quoted=quoted) == expected @pytest.mark.parametrize("required", (True, False)) - @pytest.mark.parametrize("nullable", (True, False)) - def test_get_type_imports(self, list_property_factory, date_time_property_factory, required, nullable): + def test_get_type_imports(self, list_property_factory, date_time_property_factory, required): inner_property = date_time_property_factory() - p = list_property_factory(inner_property=inner_property, required=required, nullable=nullable) + p = list_property_factory(inner_property=inner_property, required=required) expected = { "import datetime", "from typing import cast", "from dateutil.parser import isoparse", "from typing import cast, List", } - if nullable: - expected.add("from typing import Optional") if not required: expected |= { "from typing import Union", @@ -239,24 +224,16 @@ def test_get_lazy_import_model_inner(self, union_property_factory, model_propert assert p.get_lazy_imports(prefix="..") == {"from ..models.my_module import MyClass"} @pytest.mark.parametrize( - "nullable,required,no_optional,json,expected", + "required,no_optional,json,expected", [ - (False, False, False, False, "Union[Unset, datetime.datetime, str]"), - (False, False, True, False, "Union[datetime.datetime, str]"), - (False, True, False, False, "Union[datetime.datetime, str]"), - (False, True, True, False, "Union[datetime.datetime, str]"), - (True, False, False, False, "Union[None, Unset, datetime.datetime, str]"), - (True, False, True, False, "Union[datetime.datetime, str]"), - (True, True, False, False, "Union[None, datetime.datetime, str]"), - (True, True, True, False, "Union[datetime.datetime, str]"), - (False, False, False, True, "Union[Unset, str]"), - (False, False, True, True, "str"), - (False, True, False, True, "str"), - (False, True, True, True, "str"), - (True, False, False, True, "Union[None, Unset, str]"), - (True, False, True, True, "str"), - (True, True, False, True, "Union[None, str]"), - (True, True, True, True, "str"), + (False, False, False, "Union[Unset, datetime.datetime, str]"), + (False, True, False, "Union[datetime.datetime, str]"), + (True, False, False, "Union[datetime.datetime, str]"), + (True, True, False, "Union[datetime.datetime, str]"), + (False, False, True, "Union[Unset, str]"), + (False, True, True, "str"), + (True, False, True, "str"), + (True, True, True, "str"), ], ) def test_get_type_string( @@ -264,7 +241,6 @@ def test_get_type_string( union_property_factory, date_time_property_factory, string_property_factory, - nullable, required, no_optional, json, @@ -272,7 +248,6 @@ def test_get_type_string( ): p = union_property_factory( required=required, - nullable=nullable, inner_properties=[date_time_property_factory(), string_property_factory()], ) @@ -316,10 +291,10 @@ def test_get_base_json_type_string(self, union_property_factory, date_time_prope assert p.get_base_json_type_string() == "str" @pytest.mark.parametrize("required", (True, False)) - @pytest.mark.parametrize("nullable", (True, False)) - def test_get_type_imports(self, union_property_factory, date_time_property_factory, required, nullable): + def test_get_type_imports(self, union_property_factory, date_time_property_factory, required): p = union_property_factory( - inner_properties=[date_time_property_factory()], required=required, nullable=nullable + inner_properties=[date_time_property_factory()], + required=required, ) expected = { "import datetime", @@ -327,8 +302,6 @@ def test_get_type_imports(self, union_property_factory, date_time_property_facto "from dateutil.parser import isoparse", "from typing import cast, Union", } - if nullable: - expected.add("from typing import Optional") if not required: expected |= { "from typing import Union", @@ -343,19 +316,17 @@ def test_is_base_type(self, enum_property_factory): assert enum_property_factory().is_base_type is True @pytest.mark.parametrize( - "required, nullable, expected", + "required, expected", ( - (False, False, "Union[Unset, {}]"), - (True, False, "{}"), - (False, True, "Union[Unset, None, {}]"), - (True, True, "Optional[{}]"), + (False, "Union[Unset, {}]"), + (True, "{}"), ), ) - def test_get_type_string(self, mocker, enum_property_factory, required, nullable, expected): + def test_get_type_string(self, mocker, enum_property_factory, required, expected): fake_class = mocker.MagicMock() fake_class.name = "MyTestEnum" - p = enum_property_factory(class_info=fake_class, required=required, nullable=nullable) + p = enum_property_factory(class_info=fake_class, required=required) assert p.get_type_string() == expected.format(fake_class.name) assert p.get_type_string(no_optional=True) == fake_class.name @@ -407,7 +378,7 @@ def test_property_from_data_str_enum(self, enum_property_factory): from openapi_python_client.schema import Schema existing = enum_property_factory() - data = Schema(title="AnEnum", enum=["A", "B", "C"], nullable=False, default="B") + data = Schema(title="AnEnum", enum=["A", "B", "C"], default="B") name = "my_enum" required = True @@ -431,12 +402,14 @@ def test_property_from_data_str_enum(self, enum_property_factory): "ParentAnEnum": prop, } - def test_property_from_data_str_enum_with_null(self, enum_property_factory): + def test_property_from_data_str_enum_with_null( + self, enum_property_factory, union_property_factory, none_property_factory + ): from openapi_python_client.parser.properties import Class, Schemas, property_from_data from openapi_python_client.schema import Schema existing = enum_property_factory() - data = Schema(title="AnEnum", enum=["A", "B", "C", None], nullable=False, default="B") + data = Schema(title="AnEnum", enum=["A", "B", "C", None], default="B") name = "my_enum" required = True @@ -447,27 +420,30 @@ def test_property_from_data_str_enum_with_null(self, enum_property_factory): ) # None / null is removed from enum, and property is now nullable - assert prop == enum_property_factory( - name=name, + assert isinstance(prop, UnionProperty), "Enums with None should be converted to UnionProperties" + enum_prop = enum_property_factory( + name="my_enum_type_1", required=required, - nullable=True, values={"A": "A", "B": "B", "C": "C"}, class_info=Class(name="ParentAnEnum", module_name="parent_an_enum"), value_type=str, default="ParentAnEnum.B", ) - assert prop.nullable is True + none_property = none_property_factory(name="my_enum_type_0", required=required) + assert prop == union_property_factory( + name=name, default="ParentAnEnum.B", inner_properties=[none_property, enum_prop] + ) assert schemas != new_schemas, "Provided Schemas was mutated" assert new_schemas.classes_by_name == { "AnEnum": existing, - "ParentAnEnum": prop, + "ParentAnEnum": enum_prop, } def test_property_from_data_null_enum(self, enum_property_factory, none_property_factory): from openapi_python_client.parser.properties import Schemas, property_from_data from openapi_python_client.schema import Schema - data = Schema(title="AnEnumWithOnlyNull", enum=[None], nullable=False, default=None) + data = Schema(title="AnEnumWithOnlyNull", enum=[None], default=None) name = "my_enum" required = True @@ -477,7 +453,7 @@ def test_property_from_data_null_enum(self, enum_property_factory, none_property name=name, required=required, data=data, schemas=schemas, parent_name="parent", config=Config() ) - assert prop == none_property_factory(name="my_enum", required=required, nullable=False, default="None") + assert prop == none_property_factory(name="my_enum", required=required, default="None") def test_property_from_data_int_enum(self, enum_property_factory): from openapi_python_client.parser.properties import Class, Schemas, property_from_data @@ -485,8 +461,7 @@ def test_property_from_data_int_enum(self, enum_property_factory): name = "my_enum" required = True - nullable = False - data = Schema.model_construct(title="anEnum", enum=[1, 2, 3], nullable=nullable, default=3) + data = Schema.model_construct(title="anEnum", enum=[1, 2, 3], default=3) existing = enum_property_factory() schemas = Schemas(classes_by_name={"AnEnum": existing}) @@ -498,7 +473,6 @@ def test_property_from_data_int_enum(self, enum_property_factory): assert prop == enum_property_factory( name=name, required=required, - nullable=nullable, values={"VALUE_1": 1, "VALUE_2": 2, "VALUE_3": 3}, class_info=Class(name="ParentAnEnum", module_name="parent_an_enum"), value_type=int, @@ -586,7 +560,7 @@ def test_property_from_data_ref_enum_with_invalid_default(self, enum_property_fa ) assert schemas == new_schemas - assert prop == PropertyError(data=data, detail="x is an invalid default for enum MyEnum") + assert prop == PropertyError(data=data, detail="Value x is not valid for enum an_enum") def test_property_from_data_ref_model(self, model_property_factory): from openapi_python_client.parser.properties import Class, Schemas, property_from_data @@ -631,7 +605,7 @@ def test_property_from_data_ref_not_found(self, mocker): assert schemas.dependencies == {} @pytest.mark.parametrize("references_exist", (True, False)) - def test_property_from_data_ref(self, property_factory, references_exist): + def test_property_from_data_ref(self, any_property_factory, references_exist): from openapi_python_client.parser.properties import Schemas, property_from_data name = "new_name" @@ -640,7 +614,7 @@ def test_property_from_data_ref(self, property_factory, references_exist): data = oai.Reference.model_construct(ref=f"#{ref_path}") roots = {"new_root"} - existing_property = property_factory(name="old_name") + existing_property = any_property_factory(name="old_name") references = {ref_path: {"old_root"}} if references_exist else {} schemas = Schemas(classes_by_reference={ref_path: existing_property}, dependencies=references) @@ -648,7 +622,7 @@ def test_property_from_data_ref(self, property_factory, references_exist): name=name, required=required, data=data, schemas=schemas, parent_name="", config=Config(), roots=roots ) - assert prop == property_factory(name=name, required=required) + assert prop == any_property_factory(name=name, required=required) assert schemas == new_schemas assert schemas.dependencies == {ref_path: {*roots, *references.get(ref_path, set())}} @@ -671,78 +645,17 @@ def test_property_from_data_invalid_ref(self, mocker): assert prop == PropertyError(data=data, detail="bad stuff") assert schemas == new_schemas - @pytest.mark.parametrize( - "openapi_type,prop_type,python_type", - [ - ("number", FloatProperty, float), - ("integer", IntProperty, int), - ("boolean", BooleanProperty, bool), - ], - ) - def test_property_from_data_simple_types(self, openapi_type: str, prop_type: Type[Property], python_type): + def test_property_from_data_array(self): from openapi_python_client.parser.properties import Schemas, property_from_data - name = "test_prop" + name = "a_list_prop" required = True - description = "a description" - example = "an example" - data = oai.Schema.model_construct(type=openapi_type, default=1, description=description, example=example) - schemas = Schemas() - - p, new_schemas = property_from_data( - name=name, required=required, data=data, schemas=schemas, parent_name="parent", config=MagicMock() - ) - - assert p == prop_type( - name=name, - required=required, - default=python_type(data.default), - nullable=False, - python_name=name, - description=description, - example=example, - ) - assert new_schemas == schemas - - # Test nullable values - data.default = 0 - data.nullable = True - - p, _ = property_from_data( - name=name, required=required, data=data, schemas=schemas, parent_name="parent", config=MagicMock() - ) - assert p == prop_type( - name=name, - required=required, - default=python_type(data.default), - nullable=True, - python_name=name, - description=description, - example=example, - ) - - # Test bad default value - data.default = "a" - p, _ = property_from_data( - name=name, required=required, data=data, schemas=schemas, parent_name="parent", config=MagicMock() - ) - assert python_type is bool or isinstance(p, PropertyError) - - def test_property_from_data_array(self, mocker): - from openapi_python_client.parser.properties import Schemas, property_from_data - - name = mocker.MagicMock() - required = mocker.MagicMock() data = oai.Schema( - type="array", - items={"type": "number", "default": "0.0"}, + type=DataType.ARRAY, + items=oai.Schema(type=DataType.STRING), ) - build_list_property = mocker.patch(f"{MODULE_NAME}.build_list_property") - mocker.patch("openapi_python_client.utils.remove_string_escapes", return_value=name) schemas = Schemas() - config = MagicMock() - roots = {"root"} - process_properties = False + config = Config() response = property_from_data( name=name, @@ -751,107 +664,68 @@ def test_property_from_data_array(self, mocker): schemas=schemas, parent_name="parent", config=config, - roots=roots, - process_properties=process_properties, - ) + )[0] - assert response == build_list_property.return_value - build_list_property.assert_called_once_with( - data=data, - name=name, - required=required, - schemas=schemas, - parent_name="parent", - config=config, - process_properties=process_properties, - roots=roots, - ) + assert isinstance(response, ListProperty) + assert isinstance(response.inner_property, StringProperty) - def test_property_from_data_object(self, mocker): + def test_property_from_data_union(self): from openapi_python_client.parser.properties import Schemas, property_from_data - name = mocker.MagicMock() - required = mocker.MagicMock() + name = "union_prop" + required = True data = oai.Schema( - type="object", + anyOf=[oai.Schema(type=DataType.NUMBER)], + oneOf=[ + oai.Schema(type=DataType.INTEGER), + ], ) - build_model_property = mocker.patch(f"{MODULE_NAME}.build_model_property") - mocker.patch("openapi_python_client.utils.remove_string_escapes", return_value=name) schemas = Schemas() - config = MagicMock() - roots = {"root"} - process_properties = False + config = Config() response = property_from_data( - name=name, - required=required, - data=data, - schemas=schemas, - parent_name="parent", - config=config, - process_properties=process_properties, - roots=roots, - ) + name=name, required=required, data=data, schemas=schemas, parent_name="parent", config=config + )[0] - assert response == build_model_property.return_value - build_model_property.assert_called_once_with( - data=data, - name=name, - required=required, - schemas=schemas, - parent_name="parent", - config=config, - process_properties=process_properties, - roots=roots, - ) + assert isinstance(response, UnionProperty) + assert len(response.inner_properties) == 2 # noqa: PLR2004 - def test_property_from_data_union(self, mocker): + def test_property_from_data_list_of_types(self): from openapi_python_client.parser.properties import Schemas, property_from_data - name = mocker.MagicMock() - required = mocker.MagicMock() - data = oai.Schema.model_construct( - anyOf=[{"type": "number", "default": "0.0"}], - oneOf=[ - {"type": "integer", "default": "0"}, - ], + name = "union_prop" + required = True + data = oai.Schema( + type=[DataType.NUMBER, DataType.NULL], ) - build_union_property = mocker.patch(f"{MODULE_NAME}.build_union_property") - mocker.patch("openapi_python_client.utils.remove_string_escapes", return_value=name) schemas = Schemas() - config = MagicMock() + config = Config() response = property_from_data( name=name, required=required, data=data, schemas=schemas, parent_name="parent", config=config - ) + )[0] - assert response == build_union_property.return_value - build_union_property.assert_called_once_with( - data=data, name=name, required=required, schemas=schemas, parent_name="parent", config=config - ) + assert isinstance(response, UnionProperty) + assert len(response.inner_properties) == 2 # noqa: PLR2004 - def test_property_from_data_union_of_one_element(self, mocker, model_property_factory): + def test_property_from_data_union_of_one_element(self, model_property_factory): from openapi_python_client.parser.properties import Schemas, property_from_data name = "new_name" required = False class_name = "MyModel" - nullable = True existing_model = model_property_factory() schemas = Schemas(classes_by_reference={f"/{class_name}": existing_model}) data = oai.Schema.model_construct( allOf=[oai.Reference.model_construct(ref=f"#/{class_name}")], - nullable=nullable, ) - build_union_property = mocker.patch(f"{MODULE_NAME}.build_union_property") prop, schemas = property_from_data( name=name, required=required, data=data, schemas=schemas, parent_name="parent", config=Config() ) - assert prop == attr.evolve(existing_model, name=name, required=required, nullable=nullable, python_name=name) - build_union_property.assert_not_called() + assert prop == attr.evolve(existing_model, name=name, required=required, python_name=name) def test_property_from_data_no_valid_props_in_data(self, any_property_factory): from openapi_python_client.parser.properties import Schemas, property_from_data @@ -864,181 +738,24 @@ def test_property_from_data_no_valid_props_in_data(self, any_property_factory): name=name, required=True, data=data, schemas=schemas, parent_name="parent", config=MagicMock() ) - assert prop == any_property_factory(name=name, required=True, nullable=False, default=None) - assert new_schemas == schemas - - def test_property_from_data_validation_error(self, mocker): - from openapi_python_client.parser.errors import PropertyError - from openapi_python_client.parser.properties import Schemas, property_from_data - - mocker.patch(f"{MODULE_NAME}._property_from_data").side_effect = ValidationError() - schemas = Schemas() - - data = oai.Schema() - err, new_schemas = property_from_data( - name="blah", required=True, data=data, schemas=schemas, parent_name="parent", config=MagicMock() - ) - assert err == PropertyError(detail="Failed to validate default value", data=data) - assert new_schemas == schemas - - -class TestBuildListProperty: - def test_build_list_property_no_items(self, mocker): - from openapi_python_client.parser import properties - - name = mocker.MagicMock() - required = mocker.MagicMock() - data = oai.Schema.model_construct(type="array") - property_from_data = mocker.patch.object(properties, "property_from_data") - schemas = properties.Schemas() - - p, new_schemas = properties.build_list_property( - name=name, - required=required, - data=data, - schemas=schemas, - parent_name="parent", - config=MagicMock(), - process_properties=True, - roots={"root"}, - ) - - assert p == PropertyError(data=data, detail="type array must have items defined") + assert prop == any_property_factory(name=name, required=True, default=None) assert new_schemas == schemas - property_from_data.assert_not_called() - - def test_build_list_property_invalid_items(self, mocker): - from openapi_python_client.parser import properties - - name = "name" - required = mocker.MagicMock() - data = oai.Schema( - type="array", - items={}, - ) - schemas = properties.Schemas() - second_schemas = properties.Schemas(errors=["error"]) - property_from_data = mocker.patch.object( - properties, "property_from_data", return_value=(properties.PropertyError(data="blah"), second_schemas) - ) - config = MagicMock() - process_properties = False - roots = {"root"} - - p, new_schemas = properties.build_list_property( - name=name, - required=required, - data=data, - schemas=schemas, - parent_name="parent", - config=config, - roots=roots, - process_properties=process_properties, - ) - - assert isinstance(p, PropertyError) - assert p.data == "blah" - assert p.header.startswith(f"invalid data in items of array {name}") - assert new_schemas == second_schemas - assert schemas != new_schemas, "Schema was mutated" - property_from_data.assert_called_once_with( - name=f"{name}_item", - required=True, - data=data.items, - schemas=schemas, - parent_name="parent", - config=config, - process_properties=process_properties, - roots=roots, - ) - - def test_build_list_property(self, any_property_factory): - from openapi_python_client.parser import properties - - name = "prop" - data = oai.Schema( - type="array", - items={}, - ) - schemas = properties.Schemas(errors=["error"]) - config = Config() - - p, new_schemas = properties.build_list_property( - name=name, - required=True, - data=data, - schemas=schemas, - parent_name="parent", - config=config, - roots={"root"}, - process_properties=True, - ) - - assert isinstance(p, properties.ListProperty) - assert p.inner_property == any_property_factory(name=f"{name}_item") - assert new_schemas == schemas - - -class TestBuildUnionProperty: - def test_property_from_data_union( - self, union_property_factory, date_time_property_factory, string_property_factory - ): - from openapi_python_client.parser.properties import Schemas, property_from_data - - name = "union_prop" - required = True - data = oai.Schema( - anyOf=[{"type": "string", "default": "a"}], - oneOf=[ - {"type": "string", "format": "date-time"}, - ], - ) - expected = union_property_factory( - name=name, - required=required, - inner_properties=[ - string_property_factory(name=f"{name}_type_0", default="'a'"), - date_time_property_factory(name=f"{name}_type_1"), - ], - ) - - p, s = property_from_data( - name=name, required=required, data=data, schemas=Schemas(), parent_name="parent", config=MagicMock() - ) - - assert p == expected - assert s == Schemas() - - def test_build_union_property_invalid_property(self, mocker): - name = "bad_union" - required = mocker.MagicMock() - reference = oai.Reference.model_construct(ref="#/components/schema/NotExist") - data = oai.Schema(anyOf=[reference]) - mocker.patch("openapi_python_client.utils.remove_string_escapes", return_value=name) - - from openapi_python_client.parser.properties import Schemas, build_union_property - - p, s = build_union_property( - name=name, required=required, data=data, schemas=Schemas(), parent_name="parent", config=MagicMock() - ) - assert p == PropertyError(detail=f"Invalid property in union {name}", data=reference) class TestStringBasedProperty: - @pytest.mark.parametrize("nullable", (True, False)) @pytest.mark.parametrize("required", (True, False)) - def test_no_format(self, string_property_factory, nullable, required): + def test_no_format(self, string_property_factory, required): from openapi_python_client.parser.properties import property_from_data name = "some_prop" - data = oai.Schema.model_construct(type="string", nullable=nullable, default='"hello world"', pattern="abcdef") + data = oai.Schema.model_construct(type="string", default='"hello world"', pattern="abcdef") p, _ = property_from_data( name=name, required=required, data=data, parent_name=None, config=Config(), schemas=Schemas() ) assert p == string_property_factory( - name=name, required=required, nullable=nullable, default="'\\\\\"hello world\\\\\"'", pattern=data.pattern + name=name, required=required, default="'\\\\\"hello world\\\\\"'", pattern=data.pattern ) def test_datetime_format(self, date_time_property_factory): @@ -1046,89 +763,81 @@ def test_datetime_format(self, date_time_property_factory): name = "datetime_prop" required = True - data = oai.Schema.model_construct( - type="string", schema_format="date-time", nullable=True, default="2020-11-06T12:00:00" - ) + data = oai.Schema.model_construct(type="string", schema_format="date-time", default="2020-11-06T12:00:00") p, _ = property_from_data( name=name, required=required, data=data, schemas=Schemas(), config=Config(), parent_name=None ) - assert p == date_time_property_factory( - name=name, required=required, nullable=True, default=f"isoparse('{data.default}')" - ) + assert p == date_time_property_factory(name=name, required=required, default=f"isoparse('{data.default}')") def test_datetime_bad_default(self): from openapi_python_client.parser.properties import property_from_data name = "datetime_prop" required = True - data = oai.Schema.model_construct(type="string", schema_format="date-time", nullable=True, default="a") + data = oai.Schema.model_construct(type="string", schema_format="date-time", default="a") result, _ = property_from_data( name=name, required=required, data=data, schemas=Schemas(), config=Config(), parent_name=None ) - assert result == PropertyError(detail="Failed to validate default value", data=data) + assert isinstance(result, PropertyError) + assert result.detail.startswith("Invalid datetime") def test_date_format(self, date_property_factory): from openapi_python_client.parser.properties import property_from_data name = "date_prop" required = True - nullable = True - data = oai.Schema.model_construct(type="string", schema_format="date", nullable=nullable, default="2020-11-06") + data = oai.Schema.model_construct(type="string", schema_format="date", default="2020-11-06") p, _ = property_from_data( name=name, required=required, data=data, schemas=Schemas(), config=Config(), parent_name=None ) - assert p == date_property_factory( - name=name, required=required, nullable=nullable, default=f"isoparse('{data.default}').date()" - ) + assert p == date_property_factory(name=name, required=required, default=f"isoparse('{data.default}').date()") def test_date_format_bad_default(self): from openapi_python_client.parser.properties import property_from_data name = "date_prop" required = True - nullable = True - data = oai.Schema.model_construct(type="string", schema_format="date", nullable=nullable, default="a") + data = oai.Schema.model_construct(type="string", schema_format="date", default="a") p, _ = property_from_data( name=name, required=required, data=data, schemas=Schemas(), config=Config(), parent_name=None ) - assert p == PropertyError(detail="Failed to validate default value", data=data) + assert isinstance(p, PropertyError) + assert p.detail.startswith("Invalid date") def test__string_based_property_binary_format(self, file_property_factory): from openapi_python_client.parser.properties import property_from_data name = "file_prop" required = True - nullable = True - data = oai.Schema.model_construct(type="string", schema_format="binary", nullable=nullable, default="a") + data = oai.Schema.model_construct(type="string", schema_format="binary", default="a") p, _ = property_from_data( name=name, required=required, data=data, schemas=Schemas(), config=Config(), parent_name=None ) - assert p == file_property_factory(name=name, required=required, nullable=nullable) + assert p == file_property_factory(name=name, required=required) def test__string_based_property_unsupported_format(self, string_property_factory): from openapi_python_client.parser.properties import property_from_data name = "unknown" required = True - nullable = True - data = oai.Schema.model_construct(type="string", schema_format="blah", nullable=nullable) + data = oai.Schema.model_construct(type="string", schema_format="blah") p, _ = property_from_data( name=name, required=required, data=data, schemas=Schemas, config=Config(), parent_name=None ) - assert p == string_property_factory(name=name, required=required, nullable=nullable) + assert p == string_property_factory(name=name, required=required) class TestCreateSchemas: @@ -1207,7 +916,7 @@ def test_retries_failing_properties_while_making_progress(self, mocker): class TestProcessModels: - def test_retries_failing_models_while_making_progress(self, mocker, model_property_factory, property_factory): + def test_retries_failing_models_while_making_progress(self, mocker, model_property_factory, any_property_factory): from openapi_python_client.parser.properties import _process_models first_model = model_property_factory() @@ -1215,7 +924,7 @@ def test_retries_failing_models_while_making_progress(self, mocker, model_proper classes_by_name={ "first": first_model, "second": model_property_factory(), - "non-model": property_factory(), + "non-model": any_property_factory(), } ) process_model = mocker.patch( @@ -1447,57 +1156,6 @@ def test_retries_failing_parameters_while_making_progress(self, mocker): assert result.errors == [ParameterError()] -def test_build_enum_property_conflict(): - from openapi_python_client.parser.properties import Schemas, build_enum_property - - data = oai.Schema() - schemas = Schemas() - - _, schemas = build_enum_property( - data=data, name="Existing", required=True, schemas=schemas, enum=["a"], parent_name=None, config=Config() - ) - err, new_schemas = build_enum_property( - data=data, - name="Existing", - required=True, - schemas=schemas, - enum=["a", "b"], - parent_name=None, - config=Config(), - ) - - assert schemas == new_schemas - assert err == PropertyError(detail="Found conflicting enums named Existing with incompatible values.", data=data) - - -def test_build_enum_property_no_values(): - from openapi_python_client.parser.properties import Schemas, build_enum_property - - data = oai.Schema() - schemas = Schemas() - - err, new_schemas = build_enum_property( - data=data, name="Existing", required=True, schemas=schemas, enum=[], parent_name=None, config=Config() - ) - - assert schemas == new_schemas - assert err == PropertyError(detail="No values provided for Enum", data=data) - - -def test_build_enum_property_bad_default(): - from openapi_python_client.parser.properties import Schemas, build_enum_property - - data = oai.Schema(default="B") - schemas = Schemas() - - err, new_schemas = build_enum_property( - data=data, name="Existing", required=True, schemas=schemas, enum=["A"], parent_name=None, config=Config() - ) - - assert schemas == new_schemas - assert err == PropertyError(detail="B is an invalid default for enum Existing", data=data) - - def test_build_schemas(mocker): from openapi_python_client.parser.properties import Schemas, build_schemas from openapi_python_client.schema import Reference, Schema diff --git a/tests/test_parser/test_properties/test_int.py b/tests/test_parser/test_properties/test_int.py new file mode 100644 index 000000000..e50166e4a --- /dev/null +++ b/tests/test_parser/test_properties/test_int.py @@ -0,0 +1,35 @@ +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import IntProperty +from openapi_python_client.parser.properties.protocol import Value + + +def test_invalid_default(): + err = IntProperty.build( + default="not a float", + description=None, + example=None, + required=False, + python_name="not_a_float", + name="not_a_float", + ) + + assert isinstance(err, PropertyError) + + +def test_convert_from_string(): + val = IntProperty.convert_value("1") + assert isinstance(val, Value) + assert val == "1" + + +def test_invalid_type_default(): + err = IntProperty.build( + default=True, + description=None, + example=None, + required=False, + python_name="not_a_float", + name="not_a_float", + ) + + assert isinstance(err, PropertyError) diff --git a/tests/test_parser/test_properties/test_list_property.py b/tests/test_parser/test_properties/test_list_property.py new file mode 100644 index 000000000..cbed9dfd2 --- /dev/null +++ b/tests/test_parser/test_properties/test_list_property.py @@ -0,0 +1,88 @@ +import attr + +import openapi_python_client.schema as oai +from openapi_python_client import Config +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import ListProperty +from openapi_python_client.schema import DataType + + +def test_build_list_property_no_items(): + from openapi_python_client.parser import properties + + name = "list_prop" + required = True + data = oai.Schema(type=DataType.ARRAY) + schemas = properties.Schemas() + + p, new_schemas = ListProperty.build( + name=name, + required=required, + data=data, + schemas=schemas, + parent_name="parent", + config=Config(), + process_properties=True, + roots={"root"}, + ) + + assert p == PropertyError(data=data, detail="type array must have items defined") + assert new_schemas == schemas + + +def test_build_list_property_invalid_items(): + from openapi_python_client.parser import properties + + name = "name" + required = True + data = oai.Schema( + type=DataType.ARRAY, + items=oai.Reference(ref="doesnt exist"), + ) + schemas = properties.Schemas(errors=["error"]) + config = Config() + process_properties = False + roots = {"root"} + + p, new_schemas = ListProperty.build( + name=name, + required=required, + data=data, + schemas=attr.evolve(schemas), + parent_name="parent", + config=config, + roots=roots, + process_properties=process_properties, + ) + + assert isinstance(p, PropertyError) + assert p.data == data.items + assert p.header.startswith(f"invalid data in items of array {name}") + assert new_schemas == schemas + + +def test_build_list_property(any_property_factory): + from openapi_python_client.parser import properties + + name = "prop" + data = oai.Schema( + type=DataType.ARRAY, + items=oai.Schema(), + ) + schemas = properties.Schemas(errors=["error"]) + config = Config() + + p, new_schemas = ListProperty.build( + name=name, + required=True, + data=data, + schemas=schemas, + parent_name="parent", + config=config, + roots={"root"}, + process_properties=True, + ) + + assert isinstance(p, properties.ListProperty) + assert p.inner_property == any_property_factory(name=f"{name}_item") + assert new_schemas == schemas diff --git a/tests/test_parser/test_properties/test_model_property.py b/tests/test_parser/test_properties/test_model_property.py index 7d3a431d9..f92a94de3 100644 --- a/tests/test_parser/test_properties/test_model_property.py +++ b/tests/test_parser/test_properties/test_model_property.py @@ -13,41 +13,31 @@ class TestModelProperty: @pytest.mark.parametrize( - "no_optional,nullable,required,json,quoted,expected", + "no_optional,required,json,quoted,expected", [ - (False, False, False, False, False, "Union[Unset, MyClass]"), - (False, False, True, False, False, "MyClass"), - (False, True, False, False, False, "Union[Unset, None, MyClass]"), - (False, True, True, False, False, "Optional[MyClass]"), - (True, False, False, False, False, "MyClass"), - (True, False, True, False, False, "MyClass"), - (True, True, False, False, False, "MyClass"), - (True, True, True, False, False, "MyClass"), - (False, False, True, True, False, "Dict[str, Any]"), - (False, False, False, False, True, "Union[Unset, 'MyClass']"), - (False, False, True, False, True, "'MyClass'"), - (False, True, False, False, True, "Union[Unset, None, 'MyClass']"), - (False, True, True, False, True, "Optional['MyClass']"), - (True, False, False, False, True, "'MyClass'"), - (True, False, True, False, True, "'MyClass'"), - (True, True, False, False, True, "'MyClass'"), - (True, True, True, False, True, "'MyClass'"), - (False, False, True, True, True, "Dict[str, Any]"), + (False, False, False, False, "Union[Unset, MyClass]"), + (False, True, False, False, "MyClass"), + (True, False, False, False, "MyClass"), + (True, True, False, False, "MyClass"), + (False, True, True, False, "Dict[str, Any]"), + (False, False, False, True, "Union[Unset, 'MyClass']"), + (False, True, False, True, "'MyClass'"), + (True, False, False, True, "'MyClass'"), + (True, True, False, True, "'MyClass'"), + (False, True, True, True, "Dict[str, Any]"), ], ) - def test_get_type_string(self, no_optional, nullable, required, json, expected, model_property_factory, quoted): + def test_get_type_string(self, no_optional, required, json, expected, model_property_factory, quoted): prop = model_property_factory( required=required, - nullable=nullable, ) assert prop.get_type_string(no_optional=no_optional, json=json, quoted=quoted) == expected def test_get_imports(self, model_property_factory): - prop = model_property_factory(required=False, nullable=True) + prop = model_property_factory(required=False) assert prop.get_imports(prefix="..") == { - "from typing import Optional", "from typing import Union", "from ..types import UNSET, Unset", "from typing import Dict", @@ -55,7 +45,7 @@ def test_get_imports(self, model_property_factory): } def test_get_lazy_imports(self, model_property_factory): - prop = model_property_factory(required=False, nullable=True) + prop = model_property_factory(required=False) assert prop.get_lazy_imports(prefix="..") == { "from ..models.my_module import MyClass", @@ -76,7 +66,7 @@ def test_get_base_type_string(self, quoted, expected, model_property_factory): assert m.get_base_type_string(quoted=quoted) == expected -class TestBuildModelProperty: +class TestBuild: @pytest.mark.parametrize( "additional_properties_schema, expected_additional_properties", [ @@ -89,7 +79,6 @@ class TestBuildModelProperty: StringProperty( name="AdditionalProperty", required=True, - nullable=False, default=None, python_name="additional_property", description=None, @@ -99,13 +88,13 @@ class TestBuildModelProperty: ], ) def test_additional_schemas(self, additional_properties_schema, expected_additional_properties): - from openapi_python_client.parser.properties import Schemas, build_model_property + from openapi_python_client.parser.properties import ModelProperty, Schemas data = oai.Schema.model_construct( additionalProperties=additional_properties_schema, ) - model, _ = build_model_property( + model, _ = ModelProperty.build( data=data, name="prop", schemas=Schemas(), @@ -119,10 +108,9 @@ def test_additional_schemas(self, additional_properties_schema, expected_additio assert model.additional_properties == expected_additional_properties def test_happy_path(self, model_property_factory, string_property_factory, date_time_property_factory): - from openapi_python_client.parser.properties import Class, Schemas, build_model_property + from openapi_python_client.parser.properties import Class, ModelProperty, Schemas name = "prop" - nullable = False required = True data = oai.Schema.model_construct( @@ -133,13 +121,12 @@ def test_happy_path(self, model_property_factory, string_property_factory, date_ "opt": oai.Schema(type="string", format="date-time"), }, description="A class called MyModel", - nullable=nullable, ) schemas = Schemas(classes_by_reference={"OtherModel": None}, classes_by_name={"OtherModel": None}) class_info = Class(name="ParentMyModel", module_name="parent_my_model") roots = {"root"} - model, new_schemas = build_model_property( + model, new_schemas = ModelProperty.build( data=data, name=name, schemas=schemas, @@ -162,7 +149,6 @@ def test_happy_path(self, model_property_factory, string_property_factory, date_ assert model == model_property_factory( name=name, required=required, - nullable=nullable, roots={*roots, class_info.name}, data=data, class_info=class_info, @@ -181,12 +167,12 @@ def test_happy_path(self, model_property_factory, string_property_factory, date_ ) def test_model_name_conflict(self): - from openapi_python_client.parser.properties import Schemas, build_model_property + from openapi_python_client.parser.properties import ModelProperty, Schemas data = oai.Schema.model_construct() schemas = Schemas(classes_by_name={"OtherModel": None}) - err, new_schemas = build_model_property( + err, new_schemas = ModelProperty.build( data=data, name="OtherModel", schemas=schemas, @@ -222,13 +208,13 @@ def test_model_name_conflict(self): def test_model_naming( self, name: str, title: Optional[str], parent_name: Optional[str], use_title_prefixing: bool, expected: str ): - from openapi_python_client.parser.properties import Schemas, build_model_property + from openapi_python_client.parser.properties import ModelProperty, Schemas data = oai.Schema( title=title, properties={}, ) - result = build_model_property( + result = ModelProperty.build( data=data, name=name, schemas=Schemas(), @@ -241,14 +227,14 @@ def test_model_naming( assert result.class_info.name == expected def test_model_bad_properties(self): - from openapi_python_client.parser.properties import Schemas, build_model_property + from openapi_python_client.parser.properties import ModelProperty, Schemas data = oai.Schema( properties={ "bad": oai.Reference.model_construct(ref="#/components/schema/NotExist"), }, ) - result = build_model_property( + result = ModelProperty.build( data=data, name="prop", schemas=Schemas(), @@ -261,7 +247,7 @@ def test_model_bad_properties(self): assert isinstance(result, PropertyError) def test_model_bad_additional_properties(self): - from openapi_python_client.parser.properties import Schemas, build_model_property + from openapi_python_client.parser.properties import ModelProperty, Schemas additional_properties = oai.Schema( type="object", @@ -270,7 +256,7 @@ def test_model_bad_additional_properties(self): }, ) data = oai.Schema(additionalProperties=additional_properties) - result = build_model_property( + result = ModelProperty.build( data=data, name="prop", schemas=Schemas(), @@ -283,10 +269,9 @@ def test_model_bad_additional_properties(self): assert isinstance(result, PropertyError) def test_process_properties_false(self, model_property_factory): - from openapi_python_client.parser.properties import Class, Schemas, build_model_property + from openapi_python_client.parser.properties import Class, ModelProperty, Schemas name = "prop" - nullable = False required = True data = oai.Schema.model_construct( @@ -297,13 +282,12 @@ def test_process_properties_false(self, model_property_factory): "opt": oai.Schema(type="string", format="date-time"), }, description="A class called MyModel", - nullable=nullable, ) schemas = Schemas(classes_by_reference={"OtherModel": None}, classes_by_name={"OtherModel": None}) roots = {"root"} class_info = Class(name="ParentMyModel", module_name="parent_my_model") - model, new_schemas = build_model_property( + model, new_schemas = ModelProperty.build( data=data, name=name, schemas=schemas, @@ -325,7 +309,6 @@ def test_process_properties_false(self, model_property_factory): assert model == model_property_factory( name=name, required=required, - nullable=nullable, class_info=class_info, data=data, description=data.description, @@ -470,7 +453,7 @@ def test_allof_string_and_string_enum(self, model_property_factory, enum_propert classes_by_reference={ "/First": model_property_factory( required_properties=[], - optional_properties=[string_property_factory(required=False, nullable=True)], + optional_properties=[string_property_factory(required=False)], ), "/Second": model_property_factory(required_properties=[], optional_properties=[enum_property]), } @@ -488,7 +471,6 @@ def test_allof_string_enum_and_string(self, model_property_factory, enum_propert ) enum_property = enum_property_factory( required=False, - nullable=True, values={"foo": "foo"}, ) schemas = Schemas( @@ -496,7 +478,7 @@ def test_allof_string_enum_and_string(self, model_property_factory, enum_propert "/First": model_property_factory(required_properties=[], optional_properties=[enum_property]), "/Second": model_property_factory( required_properties=[], - optional_properties=[string_property_factory(required=False, nullable=True)], + optional_properties=[string_property_factory(required=False)], ), } ) @@ -634,7 +616,7 @@ def test_duplicate_properties(self, model_property_factory, string_property_fact data = oai.Schema.model_construct( allOf=[oai.Reference.model_construct(ref="#/First"), oai.Reference.model_construct(ref="#/Second")] ) - prop = string_property_factory(nullable=True) + prop = string_property_factory(required=False) schemas = Schemas( classes_by_reference={ "/First": model_property_factory(required_properties=[], optional_properties=[prop]), @@ -646,15 +628,11 @@ def test_duplicate_properties(self, model_property_factory, string_property_fact assert result.optional_props == [prop], "There should only be one copy of duplicate properties" - @pytest.mark.parametrize("first_nullable", [True, False]) - @pytest.mark.parametrize("second_nullable", [True, False]) @pytest.mark.parametrize("first_required", [True, False]) @pytest.mark.parametrize("second_required", [True, False]) def test_mixed_requirements( self, model_property_factory, - first_nullable, - second_nullable, first_required, second_required, string_property_factory, @@ -669,11 +647,11 @@ def test_mixed_requirements( classes_by_reference={ "/First": model_property_factory( required_properties=[], - optional_properties=[string_property_factory(required=first_required, nullable=first_nullable)], + optional_properties=[string_property_factory(required=first_required)], ), "/Second": model_property_factory( required_properties=[], - optional_properties=[string_property_factory(required=second_required, nullable=second_nullable)], + optional_properties=[string_property_factory(required=second_required)], ), } ) @@ -681,15 +659,13 @@ def test_mixed_requirements( result = _process_properties(data=data, schemas=schemas, class_name="", config=MagicMock(), roots=roots) - nullable = first_nullable and second_nullable required = first_required or second_required expected_prop = string_property_factory( - nullable=nullable, required=required, ) assert result.schemas.dependencies == {"/First": roots, "/Second": roots} - if nullable or not required: + if not required: assert result.optional_props == [expected_prop] else: assert result.required_props == [expected_prop] @@ -713,8 +689,8 @@ def test_direct_properties_non_ref(self, string_property_factory): result = _process_properties(data=data, schemas=schemas, class_name="", config=MagicMock(), roots={"root"}) - assert result.optional_props == [string_property_factory(name="second", required=False, nullable=False)] - assert result.required_props == [string_property_factory(name="first", required=True, nullable=False)] + assert result.optional_props == [string_property_factory(name="second", required=False)] + assert result.required_props == [string_property_factory(name="first", required=True)] class TestProcessModel: diff --git a/tests/test_parser/test_properties/test_none.py b/tests/test_parser/test_properties/test_none.py new file mode 100644 index 000000000..500d078e9 --- /dev/null +++ b/tests/test_parser/test_properties/test_none.py @@ -0,0 +1,29 @@ +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import NoneProperty +from openapi_python_client.parser.properties.protocol import Value + + +def test_default(): + err = NoneProperty.build( + default="not None", + description=None, + example=None, + required=False, + python_name="not_none", + name="not_none", + ) + + assert isinstance(err, PropertyError) + + +def test_dont_retest_values(): + prop = NoneProperty.build( + default=Value("not None"), + description=None, + example=None, + required=False, + python_name="not_none", + name="not_none", + ) + + assert isinstance(prop, NoneProperty) diff --git a/tests/test_parser/test_properties/test_property.py b/tests/test_parser/test_properties/test_property.py deleted file mode 100644 index aa1b3fb4f..000000000 --- a/tests/test_parser/test_properties/test_property.py +++ /dev/null @@ -1,95 +0,0 @@ -import pytest - - -class TestProperty: - def test_is_base_type(self, property_factory): - assert property_factory().is_base_type is True - - @pytest.mark.parametrize( - "nullable,required,no_optional,json,quoted,expected", - [ - (False, False, False, False, False, "Union[Unset, TestType]"), - (False, False, True, False, False, "TestType"), - (False, True, False, False, False, "TestType"), - (False, True, True, False, False, "TestType"), - (True, False, False, False, False, "Union[Unset, None, TestType]"), - (True, False, True, False, False, "TestType"), - (True, True, False, False, False, "Optional[TestType]"), - (True, True, True, False, False, "TestType"), - (False, False, False, True, False, "Union[Unset, str]"), - (False, False, True, True, False, "str"), - (False, True, False, True, False, "str"), - (False, True, True, True, False, "str"), - (True, False, False, True, False, "Union[Unset, None, str]"), - (True, False, False, True, True, "Union[Unset, None, str]"), - (True, False, True, True, False, "str"), - (True, True, False, True, False, "Optional[str]"), - (True, True, True, True, False, "str"), - (True, True, True, True, True, "str"), - ], - ) - def test_get_type_string(self, property_factory, mocker, nullable, required, no_optional, json, expected, quoted): - from openapi_python_client.parser.properties import Property - - mocker.patch.object(Property, "_type_string", "TestType") - mocker.patch.object(Property, "_json_type_string", "str") - p = property_factory(required=required, nullable=nullable) - assert p.get_type_string(no_optional=no_optional, json=json, quoted=quoted) == expected - - @pytest.mark.parametrize( - "default,required,expected", - [ - (None, False, "test: Union[Unset, TestType] = UNSET"), - (None, True, "test: TestType"), - ("Test", False, "test: Union[Unset, TestType] = Test"), - ("Test", True, "test: TestType = Test"), - ], - ) - def test_to_string(self, mocker, default, required, expected, property_factory): - name = "test" - mocker.patch("openapi_python_client.parser.properties.Property._type_string", "TestType") - p = property_factory(name=name, required=required, default=default) - - assert p.to_string() == expected - - def test_get_imports(self, property_factory): - p = property_factory() - assert p.get_imports(prefix="") == set() - - p = property_factory(name="test", required=False, default=None, nullable=False) - assert p.get_imports(prefix="") == {"from types import UNSET, Unset", "from typing import Union"} - - p = property_factory(name="test", required=False, default=None, nullable=True) - assert p.get_imports(prefix="") == { - "from types import UNSET, Unset", - "from typing import Optional", - "from typing import Union", - } - - @pytest.mark.parametrize( - "quoted,expected", - [ - (False, "TestType"), - (True, "TestType"), - ], - ) - def test_get_base_type_string(self, quoted, expected, property_factory, mocker): - from openapi_python_client.parser.properties import Property - - mocker.patch.object(Property, "_type_string", "TestType") - p = property_factory() - assert p.get_base_type_string(quoted=quoted) is expected - - @pytest.mark.parametrize( - "quoted,expected", - [ - (False, "str"), - (True, "str"), - ], - ) - def test_get_base_json_type_string(self, quoted, expected, property_factory, mocker): - from openapi_python_client.parser.properties import Property - - mocker.patch.object(Property, "_json_type_string", "str") - p = property_factory() - assert p.get_base_json_type_string(quoted=quoted) is expected diff --git a/tests/test_parser/test_properties/test_protocol.py b/tests/test_parser/test_properties/test_protocol.py new file mode 100644 index 000000000..a110f4ed9 --- /dev/null +++ b/tests/test_parser/test_properties/test_protocol.py @@ -0,0 +1,82 @@ +import pytest + + +def test_is_base_type(any_property_factory): + assert any_property_factory().is_base_type is True + + +@pytest.mark.parametrize( + "required,no_optional,json,quoted,expected", + [ + (False, False, False, False, "Union[Unset, TestType]"), + (False, True, False, False, "TestType"), + (True, False, False, False, "TestType"), + (True, True, False, False, "TestType"), + (False, False, True, False, "Union[Unset, str]"), + (False, True, True, False, "str"), + (True, False, True, False, "str"), + (True, True, True, False, "str"), + ], +) +def test_get_type_string(any_property_factory, mocker, required, no_optional, json, expected, quoted): + from openapi_python_client.parser.properties import AnyProperty + + mocker.patch.object(AnyProperty, "_type_string", "TestType") + mocker.patch.object(AnyProperty, "_json_type_string", "str") + p = any_property_factory(required=required) + assert p.get_type_string(no_optional=no_optional, json=json, quoted=quoted) == expected + + +@pytest.mark.parametrize( + "default,required,expected", + [ + (None, False, "test: Union[Unset, TestType] = UNSET"), + (None, True, "test: TestType"), + ("Test", False, "test: Union[Unset, TestType] = Test"), + ("Test", True, "test: TestType = Test"), + ], +) +def test_to_string(mocker, default, required, expected, any_property_factory): + name = "test" + mocker.patch("openapi_python_client.parser.properties.AnyProperty._type_string", "TestType") + p = any_property_factory(name=name, required=required, default=default) + + assert p.to_string() == expected + + +def test_get_imports(any_property_factory): + p = any_property_factory() + assert p.get_imports(prefix="") == set() + + p = any_property_factory(name="test", required=False, default=None) + assert p.get_imports(prefix="") == {"from types import UNSET, Unset", "from typing import Union"} + + +@pytest.mark.parametrize( + "quoted,expected", + [ + (False, "TestType"), + (True, "TestType"), + ], +) +def test_get_base_type_string(quoted, expected, any_property_factory, mocker): + from openapi_python_client.parser.properties import AnyProperty + + mocker.patch.object(AnyProperty, "_type_string", "TestType") + p = any_property_factory() + assert p.get_base_type_string(quoted=quoted) is expected + + +@pytest.mark.parametrize( + "quoted,expected", + [ + (False, "str"), + (True, "str"), + ], +) +def test_get_base_json_type_string(quoted, expected, any_property_factory, mocker): + from openapi_python_client.parser.properties import AnyProperty + + mocker.patch.object(AnyProperty, "_json_type_string", "str") + p = any_property_factory() + assert p.get_base_json_type_string(quoted=quoted) is expected diff --git a/tests/test_parser/test_properties/test_union.py b/tests/test_parser/test_properties/test_union.py new file mode 100644 index 000000000..621921f0c --- /dev/null +++ b/tests/test_parser/test_properties/test_union.py @@ -0,0 +1,99 @@ +import openapi_python_client.schema as oai +from openapi_python_client import Config +from openapi_python_client.parser.errors import ParseError, PropertyError +from openapi_python_client.parser.properties import Schemas, UnionProperty +from openapi_python_client.schema import DataType, ParameterLocation + + +def test_property_from_data_union(union_property_factory, date_time_property_factory, string_property_factory): + from openapi_python_client.parser.properties import Schemas, property_from_data + + name = "union_prop" + required = True + data = oai.Schema( + anyOf=[oai.Schema(type=DataType.STRING, default="a")], + oneOf=[ + oai.Schema(type=DataType.STRING, schema_format="date-time"), + ], + ) + expected = union_property_factory( + name=name, + required=required, + inner_properties=[ + string_property_factory(name=f"{name}_type_0", default="'a'"), + date_time_property_factory(name=f"{name}_type_1"), + ], + ) + + p, s = property_from_data( + name=name, required=required, data=data, schemas=Schemas(), parent_name="parent", config=Config() + ) + + assert p == expected + assert s == Schemas() + + +def test_build_union_property_invalid_property(): + name = "bad_union" + required = True + reference = oai.Reference.model_construct(ref="#/components/schema/NotExist") + data = oai.Schema(anyOf=[reference]) + + p, s = UnionProperty.build( + name=name, required=required, data=data, schemas=Schemas(), parent_name="parent", config=Config() + ) + assert p == PropertyError(detail=f"Invalid property in union {name}", data=reference) + + +def test_invalid_default(): + data = oai.Schema( + type=[DataType.NUMBER, DataType.INTEGER], + default="a", + ) + + err, _ = UnionProperty.build( + data=data, + required=True, + schemas=Schemas(), + parent_name="parent", + name="name", + config=Config(), + ) + + assert isinstance(err, PropertyError) + + +def test_invalid_location(): + data = oai.Schema( + type=[DataType.NUMBER, DataType.NULL], + ) + + prop, _ = UnionProperty.build( + data=data, + required=True, + schemas=Schemas(), + parent_name="parent", + name="name", + config=Config(), + ) + + err = prop.validate_location(ParameterLocation.PATH) + assert isinstance(err, ParseError) + + +def test_not_required_in_path(): + data = oai.Schema( + oneOf=[oai.Schema(type=DataType.NUMBER), oai.Schema(type=DataType.INTEGER)], + ) + + prop, _ = UnionProperty.build( + data=data, + required=False, + schemas=Schemas(), + parent_name="parent", + name="name", + config=Config(), + ) + + err = prop.validate_location(ParameterLocation.PATH) + assert isinstance(err, ParseError) diff --git a/tests/test_parser/test_responses.py b/tests/test_parser/test_responses.py index 8a0836fd0..c60b23a72 100644 --- a/tests/test_parser/test_responses.py +++ b/tests/test_parser/test_responses.py @@ -24,7 +24,6 @@ def test_response_from_data_no_content(any_property_factory): prop=any_property_factory( name="response_200", default=None, - nullable=False, required=True, description="", ), @@ -48,7 +47,6 @@ def test_response_from_data_reference(any_property_factory): prop=any_property_factory( name="response_200", default=None, - nullable=False, required=True, ), source=NONE_SOURCE, @@ -90,7 +88,6 @@ def test_response_from_data_no_content_schema(any_property_factory): prop=any_property_factory( name="response_200", default=None, - nullable=False, required=True, description=data.description, ), @@ -127,10 +124,10 @@ def test_response_from_data_property_error(mocker): ) -def test_response_from_data_property(mocker, property_factory): +def test_response_from_data_property(mocker, any_property_factory): from openapi_python_client.parser import responses - prop = property_factory() + prop = any_property_factory() property_from_data = mocker.patch.object(responses, "property_from_data", return_value=(prop, Schemas())) data = oai.Response.model_construct( description="", diff --git a/tests/test_schema/test_open_api.py b/tests/test_schema/test_open_api.py index 86d219b97..bdab19eba 100644 --- a/tests/test_schema/test_open_api.py +++ b/tests/test_schema/test_open_api.py @@ -5,7 +5,16 @@ @pytest.mark.parametrize( - "version, valid", [("abc", False), ("1", False), ("2.0", False), ("3.0.0", True), ("3.1.0-b.3", False), (1, False)] + "version, valid", + [ + ("abc", False), + ("1", False), + ("2.0", False), + ("3.0.0", True), + ("3.1.1", True), + ("3.2.0", False), + ("4.0.0", False), + ], ) def test_validate_version(version, valid): data = {"openapi": version, "info": {"title": "test", "version": ""}, "paths": {}} diff --git a/tests/test_schema/test_schema.py b/tests/test_schema/test_schema.py new file mode 100644 index 000000000..4b93f2c42 --- /dev/null +++ b/tests/test_schema/test_schema.py @@ -0,0 +1,27 @@ +from openapi_python_client.schema import DataType, Schema + + +def test_nullable_with_simple_type(): + schema = Schema.model_validate_json('{"type": "string", "nullable": true}') + assert schema.type == [DataType.STRING, DataType.NULL] + + +def test_nullable_with_allof(): + schema = Schema.model_validate_json('{"allOf": [{"type": "string"}], "nullable": true}') + assert schema.oneOf == [Schema(type=DataType.NULL), Schema(allOf=[Schema(type=DataType.STRING)])] + assert schema.allOf == [] + + +def test_nullable_with_type_list(): + schema = Schema.model_validate_json('{"type": ["string", "number"], "nullable": true}') + assert schema.type == [DataType.STRING, DataType.NUMBER, DataType.NULL] + + +def test_nullable_with_any_of(): + schema = Schema.model_validate_json('{"anyOf": [{"type": "string"}], "nullable": true}') + assert schema.anyOf == [Schema(type=DataType.STRING), Schema(type=DataType.NULL)] + + +def test_nullable_with_one_of(): + schema = Schema.model_validate_json('{"oneOf": [{"type": "string"}], "nullable": true}') + assert schema.oneOf == [Schema(type=DataType.STRING), Schema(type=DataType.NULL)] diff --git a/tests/test_templates/test_property_templates/test_date_property/optional_nullable.py b/tests/test_templates/test_property_templates/test_date_property/optional_nullable.py deleted file mode 100644 index 23208c971..000000000 --- a/tests/test_templates/test_property_templates/test_date_property/optional_nullable.py +++ /dev/null @@ -1,19 +0,0 @@ -from datetime import date -from typing import cast, Union - -from dateutil.parser import isoparse -some_source = date(2020, 10, 12) -some_destination: Union[Unset, None, str] = UNSET -if not isinstance(some_source, Unset): - some_destination = some_source.isoformat() if some_source else None - -_a_prop = some_destination -a_prop: Union[Unset, None, datetime.date] -if _a_prop is None: - a_prop = None -elif isinstance(_a_prop, Unset): - a_prop = UNSET -else: - a_prop = isoparse(_a_prop).date() - - diff --git a/tests/test_templates/test_property_templates/test_date_property/required_not_null.py b/tests/test_templates/test_property_templates/test_date_property/required_not_null.py index 610ef38e3..ad4f380a4 100644 --- a/tests/test_templates/test_property_templates/test_date_property/required_not_null.py +++ b/tests/test_templates/test_property_templates/test_date_property/required_not_null.py @@ -3,7 +3,7 @@ from dateutil.parser import isoparse some_source = date(2020, 10, 12) -some_destination = some_source.isoformat() +some_destination = some_source.isoformat() a_prop = isoparse(some_destination).date() diff --git a/tests/test_templates/test_property_templates/test_date_property/required_nullable.py b/tests/test_templates/test_property_templates/test_date_property/required_nullable.py deleted file mode 100644 index 79dd66ba4..000000000 --- a/tests/test_templates/test_property_templates/test_date_property/required_nullable.py +++ /dev/null @@ -1,14 +0,0 @@ -from datetime import date -from typing import cast, Union - -from dateutil.parser import isoparse -some_source = date(2020, 10, 12) -some_destination = some_source.isoformat() if some_source else None -_a_prop = some_destination -a_prop: Optional[datetime.date] -if _a_prop is None: - a_prop = None -else: - a_prop = isoparse(_a_prop).date() - - diff --git a/tests/test_templates/test_property_templates/test_date_property/test_date_property.py b/tests/test_templates/test_property_templates/test_date_property/test_date_property.py index f5d4aa798..98999b910 100644 --- a/tests/test_templates/test_property_templates/test_date_property/test_date_property.py +++ b/tests/test_templates/test_property_templates/test_date_property/test_date_property.py @@ -5,11 +5,10 @@ from openapi_python_client.parser.properties import DateProperty -def date_property(required=True, nullable=True, default=None) -> DateProperty: +def date_property(required=True, default=None) -> DateProperty: return DateProperty( name="a_prop", required=required, - nullable=nullable, default=default, python_name="a_prop", description="", @@ -17,25 +16,7 @@ def date_property(required=True, nullable=True, default=None) -> DateProperty: ) -def test_required_not_nullable(): - prop = date_property(nullable=False) - here = Path(__file__).parent - templates_dir = here.parent.parent.parent.parent / "openapi_python_client" / "templates" - - env = jinja2.Environment( - loader=jinja2.ChoiceLoader([jinja2.FileSystemLoader(here), jinja2.FileSystemLoader(templates_dir)]), - trim_blocks=True, - lstrip_blocks=True - ) - - template = env.get_template("date_property_template.py") - content = template.render(property=prop) - expected = here / "required_not_null.py" - assert content == expected.read_text() - - -def test_required_nullable(): - +def test_required(): prop = date_property() here = Path(__file__).parent templates_dir = here.parent.parent.parent.parent / "openapi_python_client" / "templates" @@ -48,22 +29,5 @@ def test_required_nullable(): template = env.get_template("date_property_template.py") content = template.render(property=prop) - expected = here / "required_nullable.py" - assert content == expected.read_text() - - -def test_optional_nullable(): - prop = date_property(required=False) - here = Path(__file__).parent - templates_dir = here.parent.parent.parent.parent / "openapi_python_client" / "templates" - - env = jinja2.Environment( - loader=jinja2.ChoiceLoader([jinja2.FileSystemLoader(here), jinja2.FileSystemLoader(templates_dir)]), - trim_blocks=True, - lstrip_blocks=True - ) - - template = env.get_template("date_property_template.py") - content = template.render(property=prop) - expected = here / "optional_nullable.py" + expected = here / "required_not_null.py" assert content == expected.read_text() diff --git a/tests/test_templates/test_property_templates/test_datetime_property/datetime_property_template.py b/tests/test_templates/test_property_templates/test_datetime_property/datetime_property_template.py new file mode 100644 index 000000000..85fa1548d --- /dev/null +++ b/tests/test_templates/test_property_templates/test_datetime_property/datetime_property_template.py @@ -0,0 +1,8 @@ +from datetime import date +from typing import cast, Union + +from dateutil.parser import isoparse +{% from "property_templates/datetime_property.py.jinja" import transform, construct %} +some_source = date(2020, 10, 12) +{{ transform(property, "some_source", "some_destination") }} +{{ construct(property, "some_destination") }} diff --git a/tests/test_templates/test_property_templates/test_datetime_property/required_not_null.py b/tests/test_templates/test_property_templates/test_datetime_property/required_not_null.py new file mode 100644 index 000000000..8253828e3 --- /dev/null +++ b/tests/test_templates/test_property_templates/test_datetime_property/required_not_null.py @@ -0,0 +1,9 @@ +from datetime import date +from typing import cast, Union + +from dateutil.parser import isoparse +some_source = date(2020, 10, 12) +some_destination = some_source.isoformat() +a_prop = isoparse(some_destination) + + diff --git a/tests/test_templates/test_property_templates/test_datetime_property/test_datetime_property.py b/tests/test_templates/test_property_templates/test_datetime_property/test_datetime_property.py new file mode 100644 index 000000000..83d91ff3a --- /dev/null +++ b/tests/test_templates/test_property_templates/test_datetime_property/test_datetime_property.py @@ -0,0 +1,33 @@ +from pathlib import Path + +import jinja2 + +from openapi_python_client.parser.properties import DateTimeProperty + + +def datetime_property(required=True, default=None) -> DateTimeProperty: + return DateTimeProperty( + name="a_prop", + required=required, + default=default, + python_name="a_prop", + description="", + example="", + ) + + +def test_required(): + prop = datetime_property() + here = Path(__file__).parent + templates_dir = here.parent.parent.parent.parent / "openapi_python_client" / "templates" + + env = jinja2.Environment( + loader=jinja2.ChoiceLoader([jinja2.FileSystemLoader(here), jinja2.FileSystemLoader(templates_dir)]), + trim_blocks=True, + lstrip_blocks=True + ) + + template = env.get_template("datetime_property_template.py") + content = template.render(property=prop) + expected = here / "required_not_null.py" + assert content == expected.read_text()