From 5181c9b1455a8c32dc2c677139318b1beb7b1303 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Wed, 13 Sep 2023 19:40:06 -0600 Subject: [PATCH 01/30] Start adding 3.1.0 support --- .../{openapi.json => openapi_3.0.json} | 2 +- end_to_end_tests/openapi_3.1.yaml | 2451 ++++++++++++ end_to_end_tests/test_end_to_end.py | 13 +- openapi_python_client/parser/openapi.py | 7 +- .../parser/properties/__init__.py | 76 +- .../parser/properties/model_property.py | 17 +- .../parser/properties/property.py | 10 +- .../parser/properties/schemas.py | 1 + openapi_python_client/parser/responses.py | 1 - openapi_python_client/schema/3.0.3.md | 3454 ++++++++++++++++ openapi_python_client/schema/3.1.0.md | 3468 +++++++++++++++++ openapi_python_client/schema/data_type.py | 2 + .../openapi_schema_pydantic/open_api.py | 17 +- .../schema/openapi_schema_pydantic/schema.py | 22 +- .../property_templates/date_property.py.jinja | 6 +- .../datetime_property.py.jinja | 8 - .../property_templates/enum_property.py.jinja | 8 - .../property_templates/file_property.py.jinja | 8 - .../property_templates/helpers.jinja | 10 +- .../property_templates/list_property.py.jinja | 16 +- .../model_property.py.jinja | 8 - .../property_macros.py.jinja | 11 +- .../union_property.py.jinja | 9 - tests/conftest.py | 1 - tests/test_parser/test_openapi.py | 46 +- .../test_parser/test_properties/test_init.py | 184 +- .../test_properties/test_model_property.py | 68 +- .../test_properties/test_property.py | 41 +- tests/test_parser/test_responses.py | 3 - tests/test_schema/test_open_api.py | 11 +- .../test_date_property/optional_nullable.py | 19 - .../test_date_property/required_not_null.py | 3 +- .../test_date_property/required_nullable.py | 14 - .../test_date_property/test_date_property.py | 42 +- 34 files changed, 9611 insertions(+), 446 deletions(-) rename end_to_end_tests/{openapi.json => openapi_3.0.json} (99%) create mode 100644 end_to_end_tests/openapi_3.1.yaml create mode 100644 openapi_python_client/schema/3.0.3.md create mode 100644 openapi_python_client/schema/3.1.0.md delete mode 100644 tests/test_templates/test_property_templates/test_date_property/optional_nullable.py delete mode 100644 tests/test_templates/test_property_templates/test_date_property/required_nullable.py diff --git a/end_to_end_tests/openapi.json b/end_to_end_tests/openapi_3.0.json similarity index 99% rename from end_to_end_tests/openapi.json rename to end_to_end_tests/openapi_3.0.json index e57de9dca..cad08d4a2 100644 --- a/end_to_end_tests/openapi.json +++ b/end_to_end_tests/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", diff --git a/end_to_end_tests/openapi_3.1.yaml b/end_to_end_tests/openapi_3.1.yaml new file mode 100644 index 000000000..c21ac6dc6 --- /dev/null +++ b/end_to_end_tests/openapi_3.1.yaml @@ -0,0 +1,2451 @@ +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" + } + } + } + } + } + } + }, + "/tests/defaults": { + "post": { + "tags": [ + "tests" + ], + "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": "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", + "anyOf": [ + { + "type": "number" + }, + { + "type": "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" + } + } + } + } + } + } + }, + "/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" + } + ] + } + } + } + } + } + } + } + } + }, + "/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": "null" + }, + { + "type": "string", + "format": "date" + } + ] + }, + "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": { + "allOf": [ + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + }, + { + "type": "null" + } + ] + }, + "not_required_model": { + "allOf": [ + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + } + ] + }, + "not_required_nullable_model": { + "allOf": [ + { + "$ref": "#/components/schemas/ModelWithUnionProperty" + }, + { + "type": "null" + } + ] + } + }, + "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", + "oneOf": [ + { + "type": "object", + "properties": { + "bar": { + "type": "string" + } + } + }, + { + "type": "null" + } + ] + }, + "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": { + "type": "string" + } + }, + "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/test_end_to_end.py b/end_to_end_tests/test_end_to_end.py index 6ad49fcb9..5cdefd62d 100644 --- a/end_to_end_tests/test_end_to_end.py +++ b/end_to_end_tests/test_end_to_end.py @@ -58,9 +58,9 @@ def _compare_directories( 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]): 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" @@ -86,8 +86,12 @@ 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_end_to_end_3_0(): + run_e2e_test("openapi_3.0.json", [], {}) + + +def test_end_to_end_3_1(): + run_e2e_test("openapi_3.1.yaml", [], {}) def test_custom_templates(): @@ -112,6 +116,7 @@ def test_custom_templates(): expected_differences[relative_path] = expected_text run_e2e_test( + "openapi_3.0.json", extra_args=["--custom-template-path=end_to_end_tests/test_custom_templates/"], expected_differences=expected_differences, ) diff --git a/openapi_python_client/parser/openapi.py b/openapi_python_client/parser/openapi.py index 96fac02fd..79be3df07 100644 --- a/openapi_python_client/parser/openapi.py +++ b/openapi_python_client/parser/openapi.py @@ -353,8 +353,8 @@ def add_parameters( oai.ParameterLocation.HEADER: endpoint.header_parameters, oai.ParameterLocation.COOKIE: endpoint.cookie_parameters, "RESERVED": { # These can't be param names because codegen needs them as vars, the properties don't matter - "client": AnyProperty("client", True, False, None, PythonIdentifier("client", ""), None, None), - "url": AnyProperty("url", True, False, None, PythonIdentifier("url", ""), None, None), + "client": AnyProperty("client", True, None, PythonIdentifier("client", ""), None, None), + "url": AnyProperty("url", True, None, PythonIdentifier("url", ""), None, None), }, } @@ -440,9 +440,6 @@ def add_parameters( 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 981b586b6..141e7301c 100644 --- a/openapi_python_client/parser/properties/__init__.py +++ b/openapi_python_client/parser/properties/__init__.py @@ -19,6 +19,7 @@ from ... import Config from ... import schema as oai from ... import utils +from ...schema import DataType from ..errors import ParameterError, ParseError, PropertyError, ValidationError from .converter import convert, convert_chain from .enum_property import EnumProperty @@ -259,8 +260,6 @@ def get_type_strings_in_union(self, no_optional: bool = False, json: bool = Fals 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 @@ -312,7 +311,6 @@ def _string_based_property( name=name, required=required, default=convert("datetime.datetime", data.default), - nullable=data.nullable, python_name=python_name, description=data.description, example=data.example, @@ -322,7 +320,6 @@ def _string_based_property( name=name, required=required, default=convert("datetime.date", data.default), - nullable=data.nullable, python_name=python_name, description=data.description, example=data.example, @@ -332,7 +329,6 @@ def _string_based_property( name=name, required=required, default=None, - nullable=data.nullable, python_name=python_name, description=data.description, example=data.example, @@ -342,7 +338,6 @@ def _string_based_property( default=convert("str", data.default), required=required, pattern=data.pattern, - nullable=data.nullable, python_name=python_name, description=data.description, example=data.example, @@ -356,9 +351,9 @@ def build_enum_property( required: bool, schemas: Schemas, enum: Union[List[Optional[str]], List[Optional[int]]], - parent_name: Optional[str], + parent_name: str, config: Config, -) -> Tuple[Union[EnumProperty, NoneProperty, PropertyError], Schemas]: +) -> Tuple[Union[EnumProperty, NoneProperty, UnionProperty, PropertyError], Schemas]: """ Create an EnumProperty from schema data. @@ -378,25 +373,16 @@ def build_enum_property( 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, @@ -404,6 +390,22 @@ def build_enum_property( ), 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})] + data.enum = None + return build_union_property( + 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: @@ -421,7 +423,6 @@ def build_enum_property( prop = EnumProperty( name=name, required=required, - nullable=data.nullable, class_info=class_info, values=values, value_type=value_type, @@ -485,7 +486,12 @@ def build_union_property( """ sub_properties: List[Property] = [] - for i, sub_prop_data in enumerate(chain(data.anyOf, data.oneOf)): + type_list_data = [] + if isinstance(data.type, list): + for _type in data.type: + type_list_data.append(data.model_copy(update={"type": _type})) + + 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, @@ -505,7 +511,6 @@ def build_union_property( 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, @@ -561,7 +566,6 @@ def build_list_property( 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, @@ -593,13 +597,11 @@ def _property_from_ref( name=name, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), ) - 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) + if parent and 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 @@ -640,7 +642,7 @@ def _property_from_data( parent_name=parent_name, config=config, ) - if data.anyOf or data.oneOf: + if data.anyOf or data.oneOf or isinstance(data.type, list): return build_union_property( data=data, name=name, required=required, schemas=schemas, parent_name=parent_name, config=config ) @@ -652,7 +654,6 @@ def _property_from_data( name=name, default=convert("float", data.default), required=required, - nullable=data.nullable, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), description=data.description, example=data.example, @@ -665,7 +666,6 @@ def _property_from_data( name=name, default=convert("int", data.default), required=required, - nullable=data.nullable, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), description=data.description, example=data.example, @@ -678,7 +678,18 @@ def _property_from_data( name=name, required=required, default=convert("bool", data.default), - nullable=data.nullable, + 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, @@ -711,7 +722,6 @@ def _property_from_data( AnyProperty( name=name, required=required, - nullable=False, default=None, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), description=data.description, diff --git a/openapi_python_client/parser/properties/model_property.py b/openapi_python_client/parser/properties/model_property.py index 81284e15a..47078308a 100644 --- a/openapi_python_client/parser/properties/model_property.py +++ b/openapi_python_client/parser/properties/model_property.py @@ -110,13 +110,8 @@ 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}]" @@ -152,21 +147,20 @@ def _enum_subset(first: Property, second: Property) -> Optional[EnumProperty]: def _merge_properties(first: Property, second: Property) -> Union[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", @@ -256,7 +250,7 @@ def _add_if_no_conflict(new_prop: Property) -> Optional[PropertyError]: 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) @@ -433,7 +427,6 @@ def build_model_property( 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), diff --git a/openapi_python_client/parser/properties/property.py b/openapi_python_client/parser/properties/property.py index a7e4c1ae7..eac498a9c 100644 --- a/openapi_python_client/parser/properties/property.py +++ b/openapi_python_client/parser/properties/property.py @@ -32,7 +32,6 @@ class Property: 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]] = { @@ -92,13 +91,8 @@ def get_type_string( else: type_string = self.get_base_type_string(quoted=quoted) - 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}]" def get_instance_type_string(self) -> str: @@ -115,8 +109,6 @@ def get_imports(self, *, prefix: str) -> Set[str]: 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") diff --git a/openapi_python_client/parser/properties/schemas.py b/openapi_python_client/parser/properties/schemas.py index 9a774b6d7..8ca5491dc 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/responses.py b/openapi_python_client/parser/responses.py index 722614843..e9ee25e21 100644 --- a/openapi_python_client/parser/responses.py +++ b/openapi_python_client/parser/responses.py @@ -43,7 +43,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*. +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 ba54ec095..f7d78f556 100644 --- a/openapi_python_client/schema/openapi_schema_pydantic/open_api.py +++ b/openapi_python_client/schema/openapi_schema_pydantic/open_api.py @@ -1,7 +1,7 @@ # pylint: disable=W0611 from typing import List, Literal, Optional, Union -from pydantic import BaseModel, ConfigDict +from pydantic import BaseModel, ConfigDict, field_validator from .components import Components from .external_documentation import ExternalDocumentation @@ -30,8 +30,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) != 3: + 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..57edc7a00 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,7 @@ 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) + 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 +47,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 @@ -141,5 +141,21 @@ 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)) + return self + Schema.model_rebuild() 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..517b83b87 100644 --- a/openapi_python_client/templates/property_templates/date_property.py.jinja +++ b/openapi_python_client/templates/property_templates/date_property.py.jinja @@ -16,7 +16,7 @@ isoparse({{ source }}).date() {% set transformed = transformed + ".encode()" %} {% endif %} {% if property.required %} -{{ destination }} = {{ transformed }} {% if property.nullable %}if {{ source }} else None {%endif%} +{{ destination }} = {{ transformed }} {% else %} {% if declare_type %} {% set type_annotation = property.get_type_string(json=True) %} @@ -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 %} {% 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..ea6d100d8 100644 --- a/openapi_python_client/templates/property_templates/datetime_property.py.jinja +++ b/openapi_python_client/templates/property_templates/datetime_property.py.jinja @@ -16,11 +16,7 @@ isoparse({{ source }}) {% set transformed = transformed + ".encode()" %} {% endif %} {% if property.required %} -{% if property.nullable %} -{{ destination }} = {{ transformed }} if {{ source }} else None -{% else %} {{ destination }} = {{ transformed }} -{% endif %} {% else %} {% if declare_type %} {% set type_annotation = property.get_type_string(json=True) %} @@ -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 %} {% 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..07af39b12 100644 --- a/openapi_python_client/templates/property_templates/enum_property.py.jinja +++ b/openapi_python_client/templates/property_templates/enum_property.py.jinja @@ -18,19 +18,11 @@ {% 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 %} {{ 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 %} 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..24cdb82f7 100644 --- a/openapi_python_client/templates/property_templates/model_property.py.jinja +++ b/openapi_python_client/templates/property_templates/model_property.py.jinja @@ -19,20 +19,12 @@ {% 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 %} {{ 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_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..e1436eecd 100644 --- a/openapi_python_client/templates/property_templates/union_property.py.jinja +++ b/openapi_python_client/templates/property_templates/union_property.py.jinja @@ -48,15 +48,6 @@ 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 %} diff --git a/tests/conftest.py b/tests/conftest.py index 21428eaee..f6f7fc074 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -266,7 +266,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 79fe33567..ce006a204 100644 --- a/tests/test_parser/test_openapi.py +++ b/tests/test_parser/test_openapi.py @@ -649,9 +649,9 @@ def test__add_parameters_with_location_postfix_conflict1(self, mocker, property_ 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 = property_factory(name="prop_name_path", required=True, default=None) + query_prop = property_factory(name="prop_name", required=True, default=None) + path_prop = property_factory(name="prop_name", required=True, default=None) schemas_1 = mocker.MagicMock() schemas_2 = mocker.MagicMock() @@ -698,9 +698,9 @@ def test__add_parameters_with_location_postfix_conflict2(self, mocker, property_ 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 = property_factory(name="prop_name_path", required=True, default=None) + path_prop = property_factory(name="prop_name", required=True, default=None) + query_prop = property_factory(name="prop_name", required=True, default=None) schemas_1 = mocker.MagicMock() schemas_2 = mocker.MagicMock() schemas_3 = mocker.MagicMock() @@ -768,7 +768,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, } @@ -807,19 +807,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"), ), ] ) @@ -836,27 +836,15 @@ def test__add_parameters_query_optionality(self): data = oai.Operation.model_construct( parameters=[ oai.Parameter.model_construct( - name="not_null_not_required", + name="not_required", required=False, - param_schema=oai.Schema.model_construct(nullable=False, type="string"), + param_schema=oai.Schema.model_construct(type="string"), param_in="query", ), oai.Parameter.model_construct( - name="not_null_required", + name="required", required=True, - param_schema=oai.Schema.model_construct(nullable=False, type="string"), - param_in="query", - ), - oai.Parameter.model_construct( - name="null_not_required", - required=False, - param_schema=oai.Schema.model_construct(nullable=True, type="string"), - param_in="query", - ), - oai.Parameter.model_construct( - name="null_required", - required=True, - param_schema=oai.Schema.model_construct(nullable=True, type="string"), + param_schema=oai.Schema.model_construct(type="string"), param_in="query", ), ] @@ -866,13 +854,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" + assert len(endpoint.query_parameters) == 2, "Not all query params were added" 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_init.py b/tests/test_parser/test_properties/test_init.py index 90d65554c..fb0040bfa 100644 --- a/tests/test_parser/test_properties/test_init.py +++ b/tests/test_parser/test_properties/test_init.py @@ -7,7 +7,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.properties import ( + BooleanProperty, + FloatProperty, + IntProperty, + Property, + Schemas, + UnionProperty, +) MODULE_NAME = "openapi_python_client.parser.properties" @@ -17,16 +24,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 +41,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 +63,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 +85,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 +146,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 +194,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 +226,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 +243,6 @@ def test_get_type_string( union_property_factory, date_time_property_factory, string_property_factory, - nullable, required, no_optional, json, @@ -272,7 +250,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 +293,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 +304,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 +318,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 +380,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 @@ -436,7 +409,7 @@ def test_property_from_data_str_enum_with_null(self, enum_property_factory): 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,16 +420,15 @@ 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 isinstance(prop, UnionProperty), "Enums with None should be converted to UnionProperties" assert prop == enum_property_factory( name=name, 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 assert schemas != new_schemas, "Provided Schemas was mutated" assert new_schemas.classes_by_name == { "AnEnum": existing, @@ -467,7 +439,7 @@ def test_property_from_data_null_enum(self, enum_property_factory, none_property from openapi_python_client.parser.properties import Class, 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 +449,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 +457,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 +469,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, @@ -697,7 +667,6 @@ def test_property_from_data_simple_types(self, openapi_type: str, prop_type: Typ name=name, required=required, default=python_type(data.default), - nullable=False, python_name=name, description=description, example=example, @@ -706,7 +675,6 @@ def test_property_from_data_simple_types(self, openapi_type: str, prop_type: Typ # 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() @@ -715,7 +683,6 @@ def test_property_from_data_simple_types(self, openapi_type: str, prop_type: Typ name=name, required=required, default=python_type(data.default), - nullable=True, python_name=name, description=description, example=example, @@ -836,13 +803,11 @@ def test_property_from_data_union_of_one_element(self, mocker, model_property_fa 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") @@ -850,7 +815,7 @@ def test_property_from_data_union_of_one_element(self, mocker, model_property_fa 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) + assert prop == attr.evolve(existing_model, name=name, required=required, python_name=name) build_union_property.assert_not_called() def test_property_from_data_no_valid_props_in_data(self, any_property_factory): @@ -864,7 +829,7 @@ 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 prop == any_property_factory(name=name, required=True, default=None) assert new_schemas == schemas def test_property_from_data_validation_error(self, mocker): @@ -1025,20 +990,19 @@ def test_build_union_property_invalid_property(self, mocker): 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,24 +1010,20 @@ 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 @@ -1076,26 +1036,22 @@ def test_date_format(self, date_property_factory): 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 @@ -1108,27 +1064,25 @@ def test__string_based_property_binary_format(self, file_property_factory): 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: diff --git a/tests/test_parser/test_properties/test_model_property.py b/tests/test_parser/test_properties/test_model_property.py index d22204a46..ec0c65ed7 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", @@ -89,7 +79,6 @@ class TestBuildModelProperty: StringProperty( name="AdditionalProperty", required=True, - nullable=False, default=None, python_name="additional_property", description=None, @@ -122,7 +111,6 @@ def test_happy_path(self, model_property_factory, string_property_factory, date_ from openapi_python_client.parser.properties import Class, Schemas, build_model_property name = "prop" - nullable = False required = True data = oai.Schema.model_construct( @@ -133,7 +121,6 @@ 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") @@ -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, @@ -286,7 +272,6 @@ def test_process_properties_false(self, model_property_factory): from openapi_python_client.parser.properties import Class, Schemas, build_model_property name = "prop" - nullable = False required = True data = oai.Schema.model_construct( @@ -297,7 +282,6 @@ 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"} @@ -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_property.py b/tests/test_parser/test_properties/test_property.py index aa1b3fb4f..6091db944 100644 --- a/tests/test_parser/test_properties/test_property.py +++ b/tests/test_parser/test_properties/test_property.py @@ -6,34 +6,24 @@ 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", + "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"), + (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(self, property_factory, mocker, nullable, required, no_optional, json, expected, quoted): + def test_get_type_string(self, property_factory, mocker, 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) + p = property_factory(required=required) assert p.get_type_string(no_optional=no_optional, json=json, quoted=quoted) == expected @pytest.mark.parametrize( @@ -56,16 +46,9 @@ 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) + p = property_factory(name="test", required=False, default=None) 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", [ diff --git a/tests/test_parser/test_responses.py b/tests/test_parser/test_responses.py index f4b75829f..a12059f9d 100644 --- a/tests/test_parser/test_responses.py +++ b/tests/test_parser/test_responses.py @@ -23,7 +23,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="", ), @@ -47,7 +46,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", @@ -78,7 +76,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, ), 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_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..e71bbbf96 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,8 @@ 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() From 530733a6bdcb438c6141c8b0e42383ca81a37026 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sun, 15 Oct 2023 12:33:47 -0600 Subject: [PATCH 02/30] Lots of refactoring + make unit tests work again! --- openapi_python_client/parser/errors.py | 6 +- openapi_python_client/parser/openapi.py | 2 +- .../parser/properties/__init__.py | 661 ++---------------- .../parser/properties/any.py | 47 ++ .../parser/properties/boolean.py | 64 ++ .../parser/properties/converter.py | 82 --- .../parser/properties/date.py | 71 ++ .../parser/properties/datetime.py | 73 ++ .../parser/properties/enum_property.py | 149 +++- .../parser/properties/file.py | 62 ++ .../parser/properties/float.py | 65 ++ .../parser/properties/int.py | 65 ++ .../parser/properties/list_property.py | 118 ++++ .../parser/properties/model_property.py | 26 +- .../parser/properties/none.py | 54 ++ .../parser/properties/property.py | 189 +---- .../parser/properties/protocol.py | 171 +++++ .../parser/properties/string.py | 63 ++ .../parser/properties/union.py | 168 +++++ .../openapi_schema_pydantic/open_api.py | 6 +- tests/conftest.py | 16 - tests/test_parser/test_openapi.py | 16 +- .../test_properties/test_converter.py | 41 -- .../test_properties/test_enum_property.py | 49 ++ .../test_parser/test_properties/test_init.py | 307 ++------ .../test_properties/test_list_property.py | 88 +++ .../test_properties/test_property.py | 78 --- .../test_properties/test_protocol.py | 82 +++ .../test_parser/test_properties/test_union.py | 45 ++ tests/test_parser/test_responses.py | 4 +- 30 files changed, 1597 insertions(+), 1271 deletions(-) create mode 100644 openapi_python_client/parser/properties/any.py create mode 100644 openapi_python_client/parser/properties/boolean.py delete mode 100644 openapi_python_client/parser/properties/converter.py create mode 100644 openapi_python_client/parser/properties/date.py create mode 100644 openapi_python_client/parser/properties/datetime.py create mode 100644 openapi_python_client/parser/properties/file.py create mode 100644 openapi_python_client/parser/properties/float.py create mode 100644 openapi_python_client/parser/properties/int.py create mode 100644 openapi_python_client/parser/properties/list_property.py create mode 100644 openapi_python_client/parser/properties/none.py create mode 100644 openapi_python_client/parser/properties/protocol.py create mode 100644 openapi_python_client/parser/properties/string.py create mode 100644 openapi_python_client/parser/properties/union.py delete mode 100644 tests/test_parser/test_properties/test_converter.py create mode 100644 tests/test_parser/test_properties/test_enum_property.py create mode 100644 tests/test_parser/test_properties/test_list_property.py delete mode 100644 tests/test_parser/test_properties/test_property.py create mode 100644 tests/test_parser/test_properties/test_protocol.py create mode 100644 tests/test_parser/test_properties/test_union.py 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 98242d35b..3bc4a3ad5 100644 --- a/openapi_python_client/parser/openapi.py +++ b/openapi_python_client/parser/openapi.py @@ -307,7 +307,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], diff --git a/openapi_python_client/parser/properties/__init__.py b/openapi_python_client/parser/properties/__init__.py index d566b1821..b3c82204d 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,18 +13,24 @@ "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 ...schema import DataType -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 .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, build_model_property, process_model +from .none import NoneProperty from .property import Property from .schemas import ( Class, @@ -33,296 +41,36 @@ 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 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), + 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), + 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, @@ -330,9 +78,9 @@ def _string_based_property( 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, python_name=python_name, @@ -341,245 +89,15 @@ def _string_based_property( ) -def build_enum_property( - *, - data: oai.Schema, - name: str, - required: bool, - schemas: Schemas, - enum: Union[List[Optional[str]], List[Optional[int]]], - parent_name: str, - config: Config, -) -> Tuple[Union[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 describing what went wrong 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: Union[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 in that case - if len(value_list) == 0: - return ( - NoneProperty( - 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})] - data.enum = None - return build_union_property( - 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, - ) - - 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] = [] - - type_list_data = [] - if isinstance(data.type, list): - for _type in data.type: - type_list_data.append(data.model_copy(update={"type": _type})) - - 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) - - 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, - 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, - 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 @@ -587,40 +105,42 @@ def _property_from_ref( if not existing: 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, ) - if parent and 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 ) - 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( @@ -628,7 +148,7 @@ def _property_from_data( # noqa: PLR0911 ) if data.enum: - return build_enum_property( + return EnumProperty.build( data=data, name=name, required=required, @@ -638,16 +158,16 @@ def _property_from_data( # noqa: PLR0911 config=config, ) if data.anyOf or data.oneOf or isinstance(data.type, list): - return build_union_property( + return UnionProperty.build( data=data, name=name, required=required, schemas=schemas, parent_name=parent_name, config=config ) if data.type == oai.DataType.STRING: 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, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), description=data.description, @@ -657,9 +177,9 @@ 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, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), description=data.description, @@ -669,10 +189,10 @@ 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), + default=data.default, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), description=data.description, example=data.example, @@ -692,7 +212,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, @@ -714,7 +234,7 @@ def _property_from_data( # noqa: PLR0911 roots=roots, ) return ( - AnyProperty( + AnyProperty.build( name=name, required=required, default=None, @@ -726,65 +246,10 @@ def _property_from_data( # noqa: PLR0911 ) -def property_from_data( - *, - name: str, - required: bool, - data: Union[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() +def _create_schemas(*, components: dict[str, oai.Reference | oai.Schema], schemas: Schemas, config: Config) -> Schemas: + 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: @@ -813,7 +278,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 @@ -826,8 +291,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:" @@ -839,8 +304,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: @@ -872,9 +337,7 @@ def _process_models(*, schemas: Schemas, config: Config) -> Schemas: return schemas -def build_schemas( - *, components: Dict[str, Union[oai.Reference, oai.Schema]], schemas: Schemas, config: Config -) -> Schemas: +def build_schemas(*, 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) schemas = _process_models(schemas=schemas, config=config) @@ -883,16 +346,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..e52339b17 --- /dev/null +++ b/openapi_python_client/parser/properties/any.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import 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: str | None, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> AnyProperty: + return cls( + name=name, + required=required, + default=Value(default) if default is not None else None, + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: str | Value | None) -> Value | None: + if isinstance(value, str): + return Value(value) + return 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..dc1adcc15 --- /dev/null +++ b/openapi_python_client/parser/properties/boolean.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from typing import 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: str | None | Value, + 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: str | Value | None) -> Value | None | PropertyError: + if isinstance(value, str): + try: + bool(value) + except ValueError: + return PropertyError(f"Invalid boolean value: {value}") + return Value(value) + return value 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..654d8d181 --- /dev/null +++ b/openapi_python_client/parser/properties/date.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import 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: str | Value | None, + 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: str | Value | None) -> Value | None | PropertyError: + 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 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({"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..7ad35c37a --- /dev/null +++ b/openapi_python_client/parser/properties/datetime.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import 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: str | Value | None, + 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: str | Value | None) -> Value | None | PropertyError: + 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 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({"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..26c07ec93 100644 --- a/openapi_python_client/parser/properties/enum_property.py +++ b/openapi_python_client/parser/properties/enum_property.py @@ -1,42 +1,165 @@ +from __future__ import annotations + __all__ = ["EnumProperty"] -from typing import Any, ClassVar, Dict, List, Optional, Set, Type, Union, cast +from typing import 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: str | Value | None) -> Value | PropertyError | None: + if isinstance(value, str): + 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 value + 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 +172,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..9346d938f --- /dev/null +++ b/openapi_python_client/parser/properties/file.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from typing import ClassVar + +from attr import define + +from ...utils import PythonIdentifier +from .protocol import PropertyProtocol, Value + + +@define +class FileProperty(PropertyProtocol): + """A property used for uploading files""" + + name: str + required: bool + default: Value | 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: str | Value | None, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + ) -> FileProperty: + return cls( + name=name, + required=required, + default=cls.convert_value(default), + python_name=python_name, + description=description, + example=example, + ) + + @classmethod + def convert_value(cls, value: str | Value | None) -> Value | None: + if isinstance(value, str): + return Value(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..e32efe345 --- /dev/null +++ b/openapi_python_client/parser/properties/float.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from typing import 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: str | None | Value, + 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: str | Value | None) -> Value | None | PropertyError: + if isinstance(value, str): + try: + float(value) + except ValueError: + return PropertyError(f"Invalid float value: {value}") + return Value(value) + return value diff --git a/openapi_python_client/parser/properties/int.py b/openapi_python_client/parser/properties/int.py new file mode 100644 index 000000000..a1578a12c --- /dev/null +++ b/openapi_python_client/parser/properties/int.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from typing import 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: str | None | Value, + 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: str | Value | None) -> Value | None | PropertyError: + if isinstance(value, str): + try: + int(value) + except ValueError: + return PropertyError(f"Invalid int value: {value}") + return Value(value) + return 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..0e373be05 --- /dev/null +++ b/openapi_python_client/parser/properties/list_property.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +from typing import 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: str | Value | None) -> Value | None | PropertyError: + return self.inner_property.convert_value(value) + + 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 04d1c6228..03701f151 100644 --- a/openapi_python_client/parser/properties/model_property.py +++ b/openapi_python_client/parser/properties/model_property.py @@ -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,10 @@ class ModelProperty(Property): json_is_dict: ClassVar[bool] = True is_multipart_body: bool = False + @classmethod + def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: + return None + def __attrs_post_init__(self) -> None: if self.relative_imports: self.set_relative_imports(self.relative_imports) @@ -114,6 +123,9 @@ def get_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()) @@ -240,7 +252,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 @@ -319,11 +331,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 diff --git a/openapi_python_client/parser/properties/none.py b/openapi_python_client/parser/properties/none.py new file mode 100644 index 000000000..f1ba6df16 --- /dev/null +++ b/openapi_python_client/parser/properties/none.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from typing import ClassVar + +from attr import define + +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 + + _type_string: ClassVar[str] = "None" + _json_type_string: ClassVar[str] = "None" + + @classmethod + def build( + cls, + name: str, + required: bool, + default: str | None, + 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: str | Value | None) -> Value | None | PropertyError: + if isinstance(value, str): + if value != "None": + return PropertyError(f"Value {value} is not valid, onlly None is allowed") + return Value(value) + return value diff --git a/openapi_python_client/parser/properties/property.py b/openapi_python_client/parser/properties/property.py index 10848bf8d..5e60c402a 100644 --- a/openapi_python_client/parser/properties/property.py +++ b/openapi_python_client/parser/properties/property.py @@ -1,158 +1,35 @@ __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 - _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: - 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: 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 .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, + 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..1c5d3fb95 --- /dev/null +++ b/openapi_python_client/parser/properties/protocol.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +__all__ = ["PropertyProtocol", "Value"] + +from abc import abstractmethod +from typing import TYPE_CHECKING, 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: str | Value | None) -> Value | None | PropertyError: + """Convert a string value to a Value object""" + raise NotImplementedError() + + 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, + *, + 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 + 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/string.py b/openapi_python_client/parser/properties/string.py new file mode 100644 index 000000000..7099ca314 --- /dev/null +++ b/openapi_python_client/parser/properties/string.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from typing import ClassVar + +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: str | None | Value, + python_name: PythonIdentifier, + description: str | None, + example: str | None, + pattern: str | None = None, + ) -> StringProperty | 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, + pattern=pattern, + ) + + @classmethod + def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: + if isinstance(value, str): + return Value(repr(utils.remove_string_escapes(value))) + return 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..a6b96d55b --- /dev/null +++ b/openapi_python_client/parser/properties/union.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +from itertools import chain +from typing import ClassVar + +from attr import define, evolve + +from ... import Config +from ... import schema as oai +from ...utils import PythonIdentifier +from ..errors import 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})) + + 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: str | Value | None) -> Value | None | PropertyError: + if value is None: + 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 = 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 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 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 4f5f49b03..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,4 +1,4 @@ -from typing import List, Literal, Optional, Union +from typing import List, Optional from pydantic import BaseModel, ConfigDict, field_validator @@ -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. @@ -37,7 +39,7 @@ class OpenAPI(BaseModel): def check_openapi_version(cls, value: str) -> str: """Validates that the declared OpenAPI version is a supported one""" parts = value.split(".") - if len(parts) != 3: + 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}") diff --git a/tests/conftest.py b/tests/conftest.py index f6f7fc074..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]: """ diff --git a/tests/test_parser/test_openapi.py b/tests/test_parser/test_openapi.py index dc97fa3e6..4b82c7540 100644 --- a/tests/test_parser/test_openapi.py +++ b/tests/test_parser/test_openapi.py @@ -643,15 +643,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, default=None) - query_prop = property_factory(name="prop_name", required=True, default=None) - path_prop = property_factory(name="prop_name", required=True, 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() @@ -693,14 +693,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, default=None) - path_prop = property_factory(name="prop_name", required=True, default=None) - query_prop = property_factory(name="prop_name", required=True, 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() 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_enum_property.py b/tests/test_parser/test_properties/test_enum_property.py new file mode 100644 index 000000000..866a986c0 --- /dev/null +++ b/tests/test_parser/test_properties/test_enum_property.py @@ -0,0 +1,49 @@ +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(): + 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) diff --git a/tests/test_parser/test_properties/test_init.py b/tests/test_parser/test_properties/test_init.py index a37af55c4..7dde7c56f 100644 --- a/tests/test_parser/test_properties/test_init.py +++ b/tests/test_parser/test_properties/test_init.py @@ -6,15 +6,18 @@ 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.errors import ParameterError, PropertyError from openapi_python_client.parser.properties import ( BooleanProperty, FloatProperty, IntProperty, + ListProperty, Property, Schemas, + StringProperty, UnionProperty, ) +from openapi_python_client.schema import DataType MODULE_NAME = "openapi_python_client.parser.properties" @@ -404,7 +407,9 @@ 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 @@ -421,18 +426,22 @@ 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 isinstance(prop, UnionProperty), "Enums with None should be converted to UnionProperties" - assert prop == enum_property_factory( - name=name, + enum_prop = enum_property_factory( + name="my_enum_type_1", required=required, values={"A": "A", "B": "B", "C": "C"}, class_info=Class(name="ParentAnEnum", module_name="parent_an_enum"), value_type=str, default="ParentAnEnum.B", ) + 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): @@ -472,7 +481,7 @@ def test_property_from_data_int_enum(self, enum_property_factory): values={"VALUE_1": 1, "VALUE_2": 2, "VALUE_3": 3}, class_info=Class(name="ParentAnEnum", module_name="parent_an_enum"), value_type=int, - default="ParentAnEnum.VALUE_3", + default=3, ) assert schemas != new_schemas, "Provided Schemas was mutated" assert new_schemas.classes_by_name == { @@ -556,7 +565,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 @@ -601,7 +610,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" @@ -610,7 +619,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) @@ -618,7 +627,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())}} @@ -695,21 +704,17 @@ def test_property_from_data_simple_types(self, openapi_type: str, prop_type: Typ ) assert python_type is bool or isinstance(p, PropertyError) - def test_property_from_data_array(self, mocker): + def test_property_from_data_array(self): from openapi_python_client.parser.properties import Schemas, property_from_data - name = mocker.MagicMock() - required = mocker.MagicMock() + name = "a_list_prop" + required = True 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, @@ -718,21 +723,10 @@ 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): from openapi_python_client.parser.properties import Schemas, property_from_data @@ -772,32 +766,28 @@ def test_property_from_data_object(self, mocker): roots=roots, ) - def test_property_from_data_union(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() - data = oai.Schema.model_construct( - anyOf=[{"type": "number", "default": "0.0"}], + name = "union_prop" + required = True + data = oai.Schema( + anyOf=[oai.Schema(type=DataType.NUMBER)], oneOf=[ - {"type": "integer", "default": "0"}, + oai.Schema(type=DataType.INTEGER), ], ) - 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" @@ -809,14 +799,12 @@ def test_property_from_data_union_of_one_element(self, mocker, model_property_fa data = oai.Schema.model_construct( allOf=[oai.Reference.model_construct(ref=f"#/{class_name}")], ) - 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, python_name=name) - build_union_property.assert_not_called() 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 @@ -832,162 +820,6 @@ def test_property_from_data_no_valid_props_in_data(self, any_property_factory): assert prop == any_property_factory(name=name, required=True, 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 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("required", (True, False)) @@ -1029,7 +861,8 @@ def test_datetime_bad_default(self): 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 @@ -1057,7 +890,8 @@ def test_date_format_bad_default(self): 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 @@ -1161,7 +995,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() @@ -1169,7 +1003,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( @@ -1401,57 +1235,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_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_property.py b/tests/test_parser/test_properties/test_property.py deleted file mode 100644 index 6091db944..000000000 --- a/tests/test_parser/test_properties/test_property.py +++ /dev/null @@ -1,78 +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( - "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(self, property_factory, mocker, 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) - 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) - 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(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..3ea1ed59d --- /dev/null +++ b/tests/test_parser/test_properties/test_union.py @@ -0,0 +1,45 @@ +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 Schemas, UnionProperty +from openapi_python_client.schema import DataType + + +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) diff --git a/tests/test_parser/test_responses.py b/tests/test_parser/test_responses.py index c3f99aa79..ed15f271a 100644 --- a/tests/test_parser/test_responses.py +++ b/tests/test_parser/test_responses.py @@ -104,10 +104,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="", content={"application/json": oai.MediaType.model_construct(media_type_schema="something")} From 2be35445c0f6e915cd520ddd422af7ed536a3ea3 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sun, 15 Oct 2023 14:35:22 -0600 Subject: [PATCH 03/30] Fix e2e tests --- .../api/default/get_common_parameters.py | 10 +- .../api/default/post_common_parameters.py | 10 +- .../get_location_query_optionality.py | 58 +++-- .../get_parameter_references_path_param.py | 20 +- ...lete_common_parameters_overriding_param.py | 10 +- .../get_same_name_multiple_locations_param.py | 10 +- .../api/tests/defaults_tests_defaults_post.py | 23 +- .../api/tests/get_user_list.py | 29 ++- .../my_test_api_client/models/a_model.py | 239 ++++++++++++------ ...roperties_reference_that_are_not_object.py | 3 + .../body_upload_file_tests_upload_post.py | 58 +++-- end_to_end_tests/openapi_3.1.yaml | 35 +-- end_to_end_tests/regen_golden_record.py | 4 +- .../parser/properties/model_property.py | 3 + .../parser/properties/protocol.py | 2 + .../parser/properties/union.py | 17 +- .../schema/openapi_schema_pydantic/schema.py | 3 + .../templates/errors.py.jinja | 2 +- .../property_templates/enum_property.py.jinja | 2 +- .../model_property.py.jinja | 2 +- .../union_property.py.jinja | 6 +- .../test_parser/test_properties/test_init.py | 18 ++ tests/test_schema/test_schema.py | 12 + 23 files changed, 362 insertions(+), 214 deletions(-) create mode 100644 tests/test_schema/test_schema.py 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..840bee628 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,7 +10,7 @@ def _get_kwargs( *, - common: Union[Unset, None, str] = UNSET, + common: Union[Unset, str] = UNSET, ) -> Dict[str, Any]: params: Dict[str, Any] = {} params["common"] = common @@ -45,11 +45,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 +73,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..ad59688e6 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,7 +10,7 @@ def _get_kwargs( *, - common: Union[Unset, None, str] = UNSET, + common: Union[Unset, str] = UNSET, ) -> Dict[str, Any]: params: Dict[str, Any] = {} params["common"] = common @@ -45,11 +45,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 +73,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/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..341d4c3d0 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,30 +12,42 @@ 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() 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 @@ -70,16 +82,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 +119,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..e44159767 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,8 +11,8 @@ def _get_kwargs( path_param: str, *, - string_param: Union[Unset, None, str] = UNSET, - integer_param: Union[Unset, None, int] = 0, + string_param: Union[Unset, str] = UNSET, + integer_param: Union[Unset, int] = 0, header_param: Union[Unset, str] = UNSET, cookie_param: Union[Unset, str] = UNSET, ) -> Dict[str, Any]: @@ -64,8 +64,8 @@ def sync_detailed( path_param: str, *, client: Union[AuthenticatedClient, Client], - string_param: Union[Unset, None, str] = UNSET, - integer_param: Union[Unset, None, int] = 0, + string_param: Union[Unset, str] = UNSET, + integer_param: Union[Unset, int] = 0, header_param: Union[Unset, str] = UNSET, cookie_param: Union[Unset, str] = UNSET, ) -> Response[Any]: @@ -73,8 +73,8 @@ def sync_detailed( Args: path_param (str): - string_param (Union[Unset, None, str]): - integer_param (Union[Unset, None, int]): + string_param (Union[Unset, str]): + integer_param (Union[Unset, int]): header_param (Union[Unset, str]): cookie_param (Union[Unset, str]): @@ -105,8 +105,8 @@ 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, + string_param: Union[Unset, str] = UNSET, + integer_param: Union[Unset, int] = 0, header_param: Union[Unset, str] = UNSET, cookie_param: Union[Unset, str] = UNSET, ) -> Response[Any]: @@ -114,8 +114,8 @@ async def asyncio_detailed( Args: path_param (str): - string_param (Union[Unset, None, str]): - integer_param (Union[Unset, None, int]): + string_param (Union[Unset, str]): + integer_param (Union[Unset, int]): header_param (Union[Unset, str]): cookie_param (Union[Unset, str]): 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..0c2321a6b 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,7 +11,7 @@ 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 @@ -49,12 +49,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 +80,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_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..a99f4f9c5 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]: @@ -61,14 +61,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 +98,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/defaults_tests_defaults_post.py b/end_to_end_tests/golden-record/my_test_api_client/api/tests/defaults_tests_defaults_post.py index f958a03e1..ff5c2f40b 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/tests/defaults_tests_defaults_post.py @@ -22,7 +22,7 @@ def _get_kwargs( 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", @@ -31,6 +31,7 @@ def _get_kwargs( params["string_prop"] = string_prop json_date_prop = date_prop.isoformat() + params["date_prop"] = json_date_prop params["float_prop"] = float_prop @@ -53,11 +54,9 @@ def _get_kwargs( 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 @@ -127,7 +126,7 @@ def sync_detailed( 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", @@ -142,7 +141,7 @@ def sync_detailed( boolean_prop (bool): 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): @@ -186,7 +185,7 @@ def sync( 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", @@ -201,7 +200,7 @@ def sync( boolean_prop (bool): 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): @@ -240,7 +239,7 @@ async def asyncio_detailed( 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", @@ -255,7 +254,7 @@ async def asyncio_detailed( boolean_prop (bool): 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): @@ -297,7 +296,7 @@ async def asyncio( 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", @@ -312,7 +311,7 @@ async def asyncio( boolean_prop (bool): 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): 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..348b8a970 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,7 +16,7 @@ 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]: @@ -31,9 +31,13 @@ def _get_kwargs( 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) @@ -47,6 +51,7 @@ def _get_kwargs( if isinstance(some_date, datetime.date): json_some_date = some_date.isoformat() + else: json_some_date = some_date.isoformat() @@ -102,7 +107,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 +117,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 +147,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 +157,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 +182,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 +192,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 +220,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 +230,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/models/a_model.py b/end_to_end_tests/golden-record/my_test_api_client/models/a_model.py index 6ac9c21b2..b1f1db2be 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 @@ -88,6 +88,19 @@ def to_dict(self) -> Dict[str, Any]: 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]] @@ -100,8 +113,27 @@ def to_dict(self) -> Dict[str, Any]: 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): @@ -119,26 +151,20 @@ def to_dict(self) -> Dict[str, Any]: 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() + 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 @@ -156,8 +182,6 @@ 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 @@ -172,17 +196,21 @@ def to_dict(self) -> Dict[str, Any]: 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 +219,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 +284,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 +329,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 +390,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 +401,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 +484,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 +491,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..e14556f9a 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 @@ -94,6 +94,7 @@ def to_dict(self) -> Dict[str, Any]: componentsschemas_an_other_array_of_date_item = ( componentsschemas_an_other_array_of_date_item_data.isoformat() ) + date_properties_ref.append(componentsschemas_an_other_array_of_date_item) datetime_properties_ref = [] @@ -133,6 +134,7 @@ def to_dict(self) -> Dict[str, Any]: date_properties = [] for componentsschemas_an_array_of_date_item_data in self.date_properties: componentsschemas_an_array_of_date_item = componentsschemas_an_array_of_date_item_data.isoformat() + date_properties.append(componentsschemas_an_array_of_date_item) datetime_properties = [] @@ -161,6 +163,7 @@ def to_dict(self) -> Dict[str, Any]: 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 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..87228aa40 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,10 +59,22 @@ 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() @@ -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 @@ -126,6 +136,14 @@ 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() @@ -157,12 +175,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") @@ -215,6 +227,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 +276,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 +286,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 +294,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/openapi_3.1.yaml b/end_to_end_tests/openapi_3.1.yaml index c21ac6dc6..9192bad92 100644 --- a/end_to_end_tests/openapi_3.1.yaml +++ b/end_to_end_tests/openapi_3.1.yaml @@ -1424,12 +1424,12 @@ info: "a_nullable_date": { "title": "A Nullable Date", "anyOf": [ - { - "type": "null" - }, { "type": "string", "format": "date" + }, + { + "type": "null" } ] }, @@ -1534,12 +1534,12 @@ info: ] }, "nullable_model": { - "allOf": [ + "oneOf": [ { - "$ref": "#/components/schemas/ModelWithUnionProperty" + "type": "null" }, { - "type": "null" + "$ref": "#/components/schemas/ModelWithUnionProperty" } ] }, @@ -1551,12 +1551,12 @@ info: ] }, "not_required_nullable_model": { - "allOf": [ + "oneOf": [ { - "$ref": "#/components/schemas/ModelWithUnionProperty" + "type": "null" }, { - "type": "null" + "$ref": "#/components/schemas/ModelWithUnionProperty" } ] } @@ -1683,19 +1683,12 @@ info: }, "some_nullable_object": { "title": "Some Nullable Object", - "oneOf": [ - { - "type": "object", - "properties": { - "bar": { - "type": "string" - } - } - }, - { - "type": "null" + "type": [ "object", "null" ], + "properties": { + "bar": { + "type": "string" } - ] + } }, "some_enum": { "$ref": "#/components/schemas/DifferentEnum" diff --git a/end_to_end_tests/regen_golden_record.py b/end_to_end_tests/regen_golden_record.py index 1d4dc943d..ff7b38046 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 / "openapi_3.0.json" gr_path = Path(__file__).parent / "golden-record" output_path = Path.cwd() / "my-test-api-client" @@ -32,7 +32,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 / "openapi_3.0.json" tpl_dir = Path(__file__).parent / "test_custom_templates" gr_path = Path(__file__).parent / "golden-record" diff --git a/openapi_python_client/parser/properties/model_property.py b/openapi_python_client/parser/properties/model_property.py index 03701f151..e8f9e554b 100644 --- a/openapi_python_client/parser/properties/model_property.py +++ b/openapi_python_client/parser/properties/model_property.py @@ -100,6 +100,7 @@ def get_type_string( no_optional: bool = False, json: bool = False, *, + multipart: bool = False, quoted: bool = False, ) -> str: """ @@ -111,6 +112,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() diff --git a/openapi_python_client/parser/properties/protocol.py b/openapi_python_client/parser/properties/protocol.py index 1c5d3fb95..cb2d7176b 100644 --- a/openapi_python_client/parser/properties/protocol.py +++ b/openapi_python_client/parser/properties/protocol.py @@ -89,6 +89,7 @@ def get_type_string( no_optional: bool = False, json: bool = False, *, + multipart: bool = False, quoted: bool = False, ) -> str: """ @@ -97,6 +98,7 @@ def get_type_string( 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: diff --git a/openapi_python_client/parser/properties/union.py b/openapi_python_client/parser/properties/union.py index a6b96d55b..9b2894f23 100644 --- a/openapi_python_client/parser/properties/union.py +++ b/openapi_python_client/parser/properties/union.py @@ -95,9 +95,10 @@ def convert_value(self, value: str | Value | None) -> Value | None | PropertyErr return value_or_error return value_or_error - def _get_inner_type_strings(self, json: bool = False) -> set[str]: + def _get_inner_type_strings(self, json: bool, multipart: bool) -> set[str]: return { - p.get_type_string(no_optional=True, json=json, quoted=not p.is_base_type) for p in self.inner_properties + p.get_type_string(no_optional=True, json=json, multipart=multipart, quoted=not p.is_base_type) + for p in self.inner_properties } @staticmethod @@ -107,12 +108,12 @@ def _get_type_string_from_inner_type_strings(inner_types: set[str]) -> str: 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)) + 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)) + 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 = False) -> set[str]: + 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. @@ -121,11 +122,12 @@ def get_type_strings_in_union(self, no_optional: bool = False, json: bool = Fals 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) + type_strings = self._get_inner_type_strings(json=json, multipart=multipart) if no_optional: return type_strings if not self.required: @@ -137,6 +139,7 @@ def get_type_string( no_optional: bool = False, json: bool = False, *, + multipart: bool = False, quoted: bool = False, ) -> str: """ @@ -144,7 +147,7 @@ def get_type_string( 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) + 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]: diff --git a/openapi_python_client/schema/openapi_schema_pydantic/schema.py b/openapi_python_client/schema/openapi_schema_pydantic/schema.py index 57edc7a00..9d693dee4 100644 --- a/openapi_python_client/schema/openapi_schema_pydantic/schema.py +++ b/openapi_python_client/schema/openapi_schema_pydantic/schema.py @@ -155,6 +155,9 @@ def handle_nullable(self) -> "Schema": 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 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/property_templates/enum_property.py.jinja b/openapi_python_client/templates/property_templates/enum_property.py.jinja index 07af39b12..1c9c02927 100644 --- a/openapi_python_client/templates/property_templates/enum_property.py.jinja +++ b/openapi_python_client/templates/property_templates/enum_property.py.jinja @@ -22,7 +22,7 @@ {% else %} {{ destination }}{% if declare_type %}: {{ type_string }}{% endif %} = UNSET if not isinstance({{ source }}, Unset): - {{ destination }} = {{ transformed }} if {{ source }} else None + {{ destination }} = {{ transformed }} {% 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 24cdb82f7..3e4890504 100644 --- a/openapi_python_client/templates/property_templates/model_property.py.jinja +++ b/openapi_python_client/templates/property_templates/model_property.py.jinja @@ -14,7 +14,7 @@ {% 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 %} 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 e1436eecd..9944383be 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,7 +41,7 @@ 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): diff --git a/tests/test_parser/test_properties/test_init.py b/tests/test_parser/test_properties/test_init.py index 7dde7c56f..73388b2df 100644 --- a/tests/test_parser/test_properties/test_init.py +++ b/tests/test_parser/test_properties/test_init.py @@ -787,6 +787,24 @@ def test_property_from_data_union(self): assert isinstance(response, UnionProperty) assert len(response.inner_properties) == 2 # noqa: PLR2004 + def test_property_from_data_list_of_types(self): + from openapi_python_client.parser.properties import Schemas, property_from_data + + name = "union_prop" + required = True + data = oai.Schema( + type=[DataType.NUMBER, DataType.NULL], + ) + schemas = Schemas() + config = Config() + + response = property_from_data( + name=name, required=required, data=data, schemas=schemas, parent_name="parent", config=config + )[0] + + assert isinstance(response, UnionProperty) + assert len(response.inner_properties) == 2 # noqa: PLR2004 + def test_property_from_data_union_of_one_element(self, model_property_factory): from openapi_python_client.parser.properties import Schemas, property_from_data diff --git a/tests/test_schema/test_schema.py b/tests/test_schema/test_schema.py new file mode 100644 index 000000000..0dc2ad567 --- /dev/null +++ b/tests/test_schema/test_schema.py @@ -0,0 +1,12 @@ +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 == [] From a9026168faa2fb55e5cb72a514b7f0f5a6cce1c2 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sun, 15 Oct 2023 15:21:43 -0600 Subject: [PATCH 04/30] More nullable test coverage --- tests/test_schema/test_schema.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/test_schema/test_schema.py b/tests/test_schema/test_schema.py index 0dc2ad567..4b93f2c42 100644 --- a/tests/test_schema/test_schema.py +++ b/tests/test_schema/test_schema.py @@ -10,3 +10,18 @@ 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)] From d2d3e586edeeaa0312ab5d266437fc6454e6d79c Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 3 Nov 2023 15:05:00 -0600 Subject: [PATCH 05/30] fix: Nullable header values --- .../get_parameter_references_path_param.py | 10 +++++----- end_to_end_tests/openapi_3.0.json | 3 ++- end_to_end_tests/openapi_3.1.yaml | 5 ++++- openapi_python_client/parser/properties/none.py | 10 ++++++++-- openapi_python_client/parser/properties/union.py | 11 ++++++++++- 5 files changed, 29 insertions(+), 10 deletions(-) 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 e44159767..b24e1990b 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 @@ -13,7 +13,7 @@ def _get_kwargs( *, string_param: Union[Unset, str] = UNSET, integer_param: Union[Unset, int] = 0, - header_param: Union[Unset, str] = UNSET, + header_param: Union[None, Unset, str] = UNSET, cookie_param: Union[Unset, str] = UNSET, ) -> Dict[str, Any]: headers = {} @@ -66,7 +66,7 @@ def sync_detailed( client: Union[AuthenticatedClient, Client], string_param: Union[Unset, str] = UNSET, integer_param: Union[Unset, int] = 0, - header_param: Union[Unset, str] = UNSET, + header_param: Union[None, Unset, str] = UNSET, cookie_param: Union[Unset, str] = UNSET, ) -> Response[Any]: """Test different types of parameter references @@ -75,7 +75,7 @@ def sync_detailed( path_param (str): string_param (Union[Unset, str]): integer_param (Union[Unset, int]): - header_param (Union[Unset, str]): + header_param (Union[None, Unset, str]): cookie_param (Union[Unset, str]): Raises: @@ -107,7 +107,7 @@ async def asyncio_detailed( client: Union[AuthenticatedClient, Client], string_param: Union[Unset, str] = UNSET, integer_param: Union[Unset, int] = 0, - header_param: Union[Unset, str] = UNSET, + header_param: Union[None, Unset, str] = UNSET, cookie_param: Union[Unset, str] = UNSET, ) -> Response[Any]: """Test different types of parameter references @@ -116,7 +116,7 @@ async def asyncio_detailed( path_param (str): string_param (Union[Unset, str]): integer_param (Union[Unset, int]): - header_param (Union[Unset, str]): + header_param (Union[None, Unset, str]): cookie_param (Union[Unset, str]): Raises: diff --git a/end_to_end_tests/openapi_3.0.json b/end_to_end_tests/openapi_3.0.json index 7a0bd7b66..38f7e471c 100644 --- a/end_to_end_tests/openapi_3.0.json +++ b/end_to_end_tests/openapi_3.0.json @@ -2364,7 +2364,8 @@ "in": "header", "required": false, "schema": { - "type": "string" + "type": "string", + "nullable": true } }, "cookie-param": { diff --git a/end_to_end_tests/openapi_3.1.yaml b/end_to_end_tests/openapi_3.1.yaml index 9192bad92..1ba2dee49 100644 --- a/end_to_end_tests/openapi_3.1.yaml +++ b/end_to_end_tests/openapi_3.1.yaml @@ -2420,7 +2420,10 @@ info: "in": "header", "required": false, "schema": { - "type": "string" + oneOf: [ + type: "string", + type: "null", + ] } }, "cookie-param": { diff --git a/openapi_python_client/parser/properties/none.py b/openapi_python_client/parser/properties/none.py index f1ba6df16..132aecc7c 100644 --- a/openapi_python_client/parser/properties/none.py +++ b/openapi_python_client/parser/properties/none.py @@ -4,9 +4,10 @@ from attr import define -from ...utils import PythonIdentifier -from ..errors import PropertyError from .protocol import PropertyProtocol, Value +from ..errors import PropertyError +from ... import schema as oai +from ...utils import PythonIdentifier @define @@ -20,6 +21,11 @@ class NoneProperty(PropertyProtocol): 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" diff --git a/openapi_python_client/parser/properties/union.py b/openapi_python_client/parser/properties/union.py index 9b2894f23..9b2570dd1 100644 --- a/openapi_python_client/parser/properties/union.py +++ b/openapi_python_client/parser/properties/union.py @@ -8,7 +8,7 @@ from ... import Config from ... import schema as oai from ...utils import PythonIdentifier -from ..errors import PropertyError +from ..errors import PropertyError, ParseError from .protocol import PropertyProtocol, Value from .schemas import Schemas @@ -169,3 +169,12 @@ def get_lazy_imports(self, *, prefix: str) -> set[str]: 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}") + if location == oai.ParameterLocation.PATH and not self.required: + return ParseError(detail="Path parameter must be required") + return None From 12467f0ab42001285e2ce9934c019f040a15346c Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 3 Nov 2023 15:06:35 -0600 Subject: [PATCH 06/30] style: Sort imports --- openapi_python_client/parser/properties/none.py | 4 ++-- openapi_python_client/parser/properties/union.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/openapi_python_client/parser/properties/none.py b/openapi_python_client/parser/properties/none.py index 132aecc7c..01371320f 100644 --- a/openapi_python_client/parser/properties/none.py +++ b/openapi_python_client/parser/properties/none.py @@ -4,10 +4,10 @@ from attr import define -from .protocol import PropertyProtocol, Value -from ..errors import PropertyError from ... import schema as oai from ...utils import PythonIdentifier +from ..errors import PropertyError +from .protocol import PropertyProtocol, Value @define diff --git a/openapi_python_client/parser/properties/union.py b/openapi_python_client/parser/properties/union.py index 9b2570dd1..7a3c07a04 100644 --- a/openapi_python_client/parser/properties/union.py +++ b/openapi_python_client/parser/properties/union.py @@ -8,7 +8,7 @@ from ... import Config from ... import schema as oai from ...utils import PythonIdentifier -from ..errors import PropertyError, ParseError +from ..errors import ParseError, PropertyError from .protocol import PropertyProtocol, Value from .schemas import Schemas From 72638d5b90943fee61c693b60757cb961b398e5d Mon Sep 17 00:00:00 2001 From: Dylan Anthony <43723790+dbanty@users.noreply.github.com> Date: Sun, 3 Dec 2023 15:26:35 -0700 Subject: [PATCH 07/30] 3.1 const (#896) * chore(deps): update dependency knope to v0.13.1 (#888) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * chore(deps): lock file maintenance (#889) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * chore(deps): update dependency knope to v0.13.2 (#890) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * chore(deps): lock file maintenance (#891) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * chore(deps): lock file maintenance (#893) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> * WIP support of `const` keyword * feat: Basic `const` support --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Dylan Anthony --- .github/workflows/preview_release_pr.yml | 2 +- .github/workflows/release-dry-run.yml | 2 +- .github/workflows/release.yml | 2 +- .gitignore | 3 +- end_to_end_tests/3.1_specific.openapi.yaml | 49 +++ ...api_3.0.json => baseline_openapi_3.0.json} | 0 ...api_3.1.yaml => baseline_openapi_3.1.yaml} | 0 end_to_end_tests/regen_golden_record.py | 36 +- .../test-3-1-golden-record/.gitignore | 23 + .../test-3-1-golden-record/README.md | 124 ++++++ .../test-3-1-golden-record/pyproject.toml | 26 ++ .../test_3_1_features_client/__init__.py | 7 + .../test_3_1_features_client/api/__init__.py | 1 + .../api/const/__init__.py | 0 .../api/const/post_const_path.py | 196 +++++++++ .../test_3_1_features_client/client.py | 268 ++++++++++++ .../test_3_1_features_client/errors.py | 14 + .../models/__init__.py | 5 + .../models/post_const_path_json_body.py | 83 ++++ .../test_3_1_features_client/py.typed | 1 + .../test_3_1_features_client/types.py | 44 ++ end_to_end_tests/test_end_to_end.py | 77 +++- integration-tests/poetry.lock | 101 ++--- openapi_python_client/parser/openapi.py | 70 ++- .../parser/properties/__init__.py | 62 ++- .../parser/properties/const.py | 123 ++++++ .../parser/properties/none.py | 2 +- .../parser/properties/property.py | 2 + .../schema/openapi_schema_pydantic/schema.py | 29 +- poetry.lock | 403 +++++++++--------- tests/test_parser/test_openapi.py | 5 +- 31 files changed, 1454 insertions(+), 306 deletions(-) create mode 100644 end_to_end_tests/3.1_specific.openapi.yaml rename end_to_end_tests/{openapi_3.0.json => baseline_openapi_3.0.json} (100%) rename end_to_end_tests/{openapi_3.1.yaml => baseline_openapi_3.1.yaml} (100%) create mode 100644 end_to_end_tests/test-3-1-golden-record/.gitignore create mode 100644 end_to_end_tests/test-3-1-golden-record/README.md create mode 100644 end_to_end_tests/test-3-1-golden-record/pyproject.toml create mode 100644 end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/__init__.py create mode 100644 end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/__init__.py create mode 100644 end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/const/__init__.py create mode 100644 end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/api/const/post_const_path.py create mode 100644 end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/client.py create mode 100644 end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/errors.py create mode 100644 end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/models/__init__.py create mode 100644 end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/models/post_const_path_json_body.py create mode 100644 end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/py.typed create mode 100644 end_to_end_tests/test-3-1-golden-record/test_3_1_features_client/types.py create mode 100644 openapi_python_client/parser/properties/const.py diff --git a/.github/workflows/preview_release_pr.yml b/.github/workflows/preview_release_pr.yml index 82c77e033..539d081c8 100644 --- a/.github/workflows/preview_release_pr.yml +++ b/.github/workflows/preview_release_pr.yml @@ -17,7 +17,7 @@ jobs: git config user.email github-actions@github.com - uses: knope-dev/action@v2.0.0 with: - version: 0.13.0 + version: 0.13.2 - run: knope prepare-release --verbose env: GITHUB_TOKEN: ${{ secrets.PAT }} diff --git a/.github/workflows/release-dry-run.yml b/.github/workflows/release-dry-run.yml index 54d4e84a6..75f9e125a 100644 --- a/.github/workflows/release-dry-run.yml +++ b/.github/workflows/release-dry-run.yml @@ -13,5 +13,5 @@ jobs: - name: Install Knope uses: knope-dev/action@v2.0.0 with: - version: 0.13.0 + version: 0.13.2 - run: knope prepare-release --dry-run diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8799a34e6..2ad5ac049 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,7 +17,7 @@ jobs: - name: Install Knope uses: knope-dev/action@v2.0.0 with: - version: 0.13.0 + version: 0.13.2 - name: Install Poetry run: pip install --upgrade poetry - name: Push to PyPI 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/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_3.0.json b/end_to_end_tests/baseline_openapi_3.0.json similarity index 100% rename from end_to_end_tests/openapi_3.0.json rename to end_to_end_tests/baseline_openapi_3.0.json diff --git a/end_to_end_tests/openapi_3.1.yaml b/end_to_end_tests/baseline_openapi_3.1.yaml similarity index 100% rename from end_to_end_tests/openapi_3.1.yaml rename to end_to_end_tests/baseline_openapi_3.1.yaml diff --git a/end_to_end_tests/regen_golden_record.py b/end_to_end_tests/regen_golden_record.py index ff7b38046..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_3.0.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_3.0.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..51d655e1d --- /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.26.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..7e39c3683 --- /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,196 @@ +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..00b9dbabc --- /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 cd479de02..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(openapi_document: str, 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_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(openapi_document: str, extra_args: List[str], expected_differen 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,18 +110,32 @@ def run_e2e_test(openapi_document: str, extra_args: List[str], expected_differen shutil.rmtree(output_path) -def test_end_to_end_3_0(): - run_e2e_test("openapi_3.0.json", [], {}) +def test_baseline_end_to_end_3_0(): + run_e2e_test("baseline_openapi_3.0.json", [], {}) -def test_end_to_end_3_1(): - run_e2e_test("openapi_3.1.yaml", [], {}) +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"), @@ -104,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(): @@ -115,7 +156,7 @@ def test_custom_templates(): expected_differences[relative_path] = expected_text run_e2e_test( - "openapi_3.0.json", + "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/poetry.lock b/integration-tests/poetry.lock index 4f7410fb3..5d6635139 100644 --- a/integration-tests/poetry.lock +++ b/integration-tests/poetry.lock @@ -2,13 +2,13 @@ [[package]] name = "anyio" -version = "4.0.0" +version = "4.1.0" description = "High level compatibility layer for multiple asynchronous event loop implementations" optional = false python-versions = ">=3.8" files = [ - {file = "anyio-4.0.0-py3-none-any.whl", hash = "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f"}, - {file = "anyio-4.0.0.tar.gz", hash = "sha256:f7ed51751b2c2add651e5747c891b47e26d2a21be5d32d9311dfe9692f3e5d7a"}, + {file = "anyio-4.1.0-py3-none-any.whl", hash = "sha256:56a415fbc462291813a94528a779597226619c8e78af7de0507333f700011e5f"}, + {file = "anyio-4.1.0.tar.gz", hash = "sha256:5a0bec7085176715be77df87fc66d6c9d70626bd752fcc85f57cdbee5b3760da"}, ] [package.dependencies] @@ -17,9 +17,9 @@ idna = ">=2.8" sniffio = ">=1.1" [package.extras] -doc = ["Sphinx (>=7)", "packaging", "sphinx-autodoc-typehints (>=1.2.0)"] -test = ["anyio[trio]", "coverage[toml] (>=7)", "hypothesis (>=4.0)", "psutil (>=5.9)", "pytest (>=7.0)", "pytest-mock (>=3.6.1)", "trustme", "uvloop (>=0.17)"] -trio = ["trio (>=0.22)"] +doc = ["Sphinx (>=7)", "packaging", "sphinx-autodoc-typehints (>=1.2.0)", "sphinx-rtd-theme"] +test = ["anyio[trio]", "coverage[toml] (>=7)", "exceptiongroup (>=1.2.0)", "hypothesis (>=4.0)", "psutil (>=5.9)", "pytest (>=7.0)", "pytest-mock (>=3.6.1)", "trustme", "uvloop (>=0.17)"] +trio = ["trio (>=0.23)"] [[package]] name = "attrs" @@ -41,13 +41,13 @@ tests-no-zope = ["cloudpickle", "hypothesis", "mypy (>=1.1.1)", "pympler", "pyte [[package]] name = "certifi" -version = "2023.7.22" +version = "2023.11.17" description = "Python package for providing Mozilla's CA Bundle." optional = false python-versions = ">=3.6" files = [ - {file = "certifi-2023.7.22-py3-none-any.whl", hash = "sha256:92d6037539857d8206b8f6ae472e8b77db8058fec5937a1ef3f54304089edbb9"}, - {file = "certifi-2023.7.22.tar.gz", hash = "sha256:539cc1d13202e33ca466e88b2807e29f4c13049d6d87031a3c110744495cb082"}, + {file = "certifi-2023.11.17-py3-none-any.whl", hash = "sha256:e036ab49d5b79556f99cfc2d9320b34cfbe5be05c5871b51de9329f0603b0474"}, + {file = "certifi-2023.11.17.tar.gz", hash = "sha256:9b469f3a900bf28dc19b8cfbf8019bf47f7fdd1a65a1d4ffb98fc14166beb4d1"}, ] [[package]] @@ -63,13 +63,13 @@ files = [ [[package]] name = "exceptiongroup" -version = "1.1.3" +version = "1.2.0" description = "Backport of PEP 654 (exception groups)" optional = false python-versions = ">=3.7" files = [ - {file = "exceptiongroup-1.1.3-py3-none-any.whl", hash = "sha256:343280667a4585d195ca1cf9cef84a4e178c4b6cf2274caef9859782b567d5e3"}, - {file = "exceptiongroup-1.1.3.tar.gz", hash = "sha256:097acd85d473d75af5bb98e41b61ff7fe35efe6675e4f9370ec6ec5126d160e9"}, + {file = "exceptiongroup-1.2.0-py3-none-any.whl", hash = "sha256:4bfd3996ac73b41e9b9628b04e079f193850720ea5945fc96a08633c66912f14"}, + {file = "exceptiongroup-1.2.0.tar.gz", hash = "sha256:91f5c769735f051a4290d52edd0858999b57e5876e9f85937691bd4c9fa3ed68"}, ] [package.extras] @@ -88,13 +88,13 @@ files = [ [[package]] name = "httpcore" -version = "1.0.1" +version = "1.0.2" description = "A minimal low-level HTTP client." optional = false python-versions = ">=3.8" files = [ - {file = "httpcore-1.0.1-py3-none-any.whl", hash = "sha256:c5e97ef177dca2023d0b9aad98e49507ef5423e9f1d94ffe2cfe250aa28e63b0"}, - {file = "httpcore-1.0.1.tar.gz", hash = "sha256:fce1ddf9b606cfb98132ab58865c3728c52c8e4c3c46e2aabb3674464a186e92"}, + {file = "httpcore-1.0.2-py3-none-any.whl", hash = "sha256:096cc05bca73b8e459a1fc3dcf585148f63e534eae4339559c9b8a8d6399acc7"}, + {file = "httpcore-1.0.2.tar.gz", hash = "sha256:9fc092e4799b26174648e54b74ed5f683132a464e95643b226e00c2ed2fa6535"}, ] [package.dependencies] @@ -109,19 +109,19 @@ trio = ["trio (>=0.22.0,<0.23.0)"] [[package]] name = "httpx" -version = "0.25.1" +version = "0.25.2" description = "The next generation HTTP client." optional = false python-versions = ">=3.8" files = [ - {file = "httpx-0.25.1-py3-none-any.whl", hash = "sha256:fec7d6cc5c27c578a391f7e87b9aa7d3d8fbcd034f6399f9f79b45bcc12a866a"}, - {file = "httpx-0.25.1.tar.gz", hash = "sha256:ffd96d5cf901e63863d9f1b4b6807861dbea4d301613415d9e6e57ead15fc5d0"}, + {file = "httpx-0.25.2-py3-none-any.whl", hash = "sha256:a05d3d052d9b2dfce0e3896636467f8a5342fb2b902c819428e1ac65413ca118"}, + {file = "httpx-0.25.2.tar.gz", hash = "sha256:8b8fcaa0c8ea7b05edd69a094e63a2094c4efcb48129fb757361bc423c0ad9e8"}, ] [package.dependencies] anyio = "*" certifi = "*" -httpcore = "*" +httpcore = "==1.*" idna = "*" sniffio = "*" @@ -133,13 +133,13 @@ socks = ["socksio (==1.*)"] [[package]] name = "idna" -version = "3.4" +version = "3.6" description = "Internationalized Domain Names in Applications (IDNA)" optional = false python-versions = ">=3.5" files = [ - {file = "idna-3.4-py3-none-any.whl", hash = "sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2"}, - {file = "idna-3.4.tar.gz", hash = "sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4"}, + {file = "idna-3.6-py3-none-any.whl", hash = "sha256:c05567e9c24a6b9faaa835c4821bad0590fbb9d5779e7caa6e1cc4978e7eb24f"}, + {file = "idna-3.6.tar.gz", hash = "sha256:9ecdbbd083b06798ae1e86adcbfe8ab1479cf864e4ee30fe4e46a003d12491ca"}, ] [[package]] @@ -155,38 +155,38 @@ files = [ [[package]] name = "mypy" -version = "1.6.1" +version = "1.7.1" description = "Optional static typing for Python" optional = false python-versions = ">=3.8" files = [ - {file = "mypy-1.6.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e5012e5cc2ac628177eaac0e83d622b2dd499e28253d4107a08ecc59ede3fc2c"}, - {file = "mypy-1.6.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d8fbb68711905f8912e5af474ca8b78d077447d8f3918997fecbf26943ff3cbb"}, - {file = "mypy-1.6.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21a1ad938fee7d2d96ca666c77b7c494c3c5bd88dff792220e1afbebb2925b5e"}, - {file = "mypy-1.6.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b96ae2c1279d1065413965c607712006205a9ac541895004a1e0d4f281f2ff9f"}, - {file = "mypy-1.6.1-cp310-cp310-win_amd64.whl", hash = "sha256:40b1844d2e8b232ed92e50a4bd11c48d2daa351f9deee6c194b83bf03e418b0c"}, - {file = "mypy-1.6.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:81af8adaa5e3099469e7623436881eff6b3b06db5ef75e6f5b6d4871263547e5"}, - {file = "mypy-1.6.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8c223fa57cb154c7eab5156856c231c3f5eace1e0bed9b32a24696b7ba3c3245"}, - {file = "mypy-1.6.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a8032e00ce71c3ceb93eeba63963b864bf635a18f6c0c12da6c13c450eedb183"}, - {file = "mypy-1.6.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:4c46b51de523817a0045b150ed11b56f9fff55f12b9edd0f3ed35b15a2809de0"}, - {file = "mypy-1.6.1-cp311-cp311-win_amd64.whl", hash = "sha256:19f905bcfd9e167159b3d63ecd8cb5e696151c3e59a1742e79bc3bcb540c42c7"}, - {file = "mypy-1.6.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:82e469518d3e9a321912955cc702d418773a2fd1e91c651280a1bda10622f02f"}, - {file = "mypy-1.6.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d4473c22cc296425bbbce7e9429588e76e05bc7342da359d6520b6427bf76660"}, - {file = "mypy-1.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59a0d7d24dfb26729e0a068639a6ce3500e31d6655df8557156c51c1cb874ce7"}, - {file = "mypy-1.6.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:cfd13d47b29ed3bbaafaff7d8b21e90d827631afda134836962011acb5904b71"}, - {file = "mypy-1.6.1-cp312-cp312-win_amd64.whl", hash = "sha256:eb4f18589d196a4cbe5290b435d135dee96567e07c2b2d43b5c4621b6501531a"}, - {file = "mypy-1.6.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:41697773aa0bf53ff917aa077e2cde7aa50254f28750f9b88884acea38a16169"}, - {file = "mypy-1.6.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:7274b0c57737bd3476d2229c6389b2ec9eefeb090bbaf77777e9d6b1b5a9d143"}, - {file = "mypy-1.6.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bbaf4662e498c8c2e352da5f5bca5ab29d378895fa2d980630656178bd607c46"}, - {file = "mypy-1.6.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:bb8ccb4724f7d8601938571bf3f24da0da791fe2db7be3d9e79849cb64e0ae85"}, - {file = "mypy-1.6.1-cp38-cp38-win_amd64.whl", hash = "sha256:68351911e85145f582b5aa6cd9ad666c8958bcae897a1bfda8f4940472463c45"}, - {file = "mypy-1.6.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:49ae115da099dcc0922a7a895c1eec82c1518109ea5c162ed50e3b3594c71208"}, - {file = "mypy-1.6.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:8b27958f8c76bed8edaa63da0739d76e4e9ad4ed325c814f9b3851425582a3cd"}, - {file = "mypy-1.6.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:925cd6a3b7b55dfba252b7c4561892311c5358c6b5a601847015a1ad4eb7d332"}, - {file = "mypy-1.6.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:8f57e6b6927a49550da3d122f0cb983d400f843a8a82e65b3b380d3d7259468f"}, - {file = "mypy-1.6.1-cp39-cp39-win_amd64.whl", hash = "sha256:a43ef1c8ddfdb9575691720b6352761f3f53d85f1b57d7745701041053deff30"}, - {file = "mypy-1.6.1-py3-none-any.whl", hash = "sha256:4cbe68ef919c28ea561165206a2dcb68591c50f3bcf777932323bc208d949cf1"}, - {file = "mypy-1.6.1.tar.gz", hash = "sha256:4d01c00d09a0be62a4ca3f933e315455bde83f37f892ba4b08ce92f3cf44bcc1"}, + {file = "mypy-1.7.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:12cce78e329838d70a204293e7b29af9faa3ab14899aec397798a4b41be7f340"}, + {file = "mypy-1.7.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:1484b8fa2c10adf4474f016e09d7a159602f3239075c7bf9f1627f5acf40ad49"}, + {file = "mypy-1.7.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:31902408f4bf54108bbfb2e35369877c01c95adc6192958684473658c322c8a5"}, + {file = "mypy-1.7.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:f2c2521a8e4d6d769e3234350ba7b65ff5d527137cdcde13ff4d99114b0c8e7d"}, + {file = "mypy-1.7.1-cp310-cp310-win_amd64.whl", hash = "sha256:fcd2572dd4519e8a6642b733cd3a8cfc1ef94bafd0c1ceed9c94fe736cb65b6a"}, + {file = "mypy-1.7.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4b901927f16224d0d143b925ce9a4e6b3a758010673eeded9b748f250cf4e8f7"}, + {file = "mypy-1.7.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2f7f6985d05a4e3ce8255396df363046c28bea790e40617654e91ed580ca7c51"}, + {file = "mypy-1.7.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:944bdc21ebd620eafefc090cdf83158393ec2b1391578359776c00de00e8907a"}, + {file = "mypy-1.7.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:9c7ac372232c928fff0645d85f273a726970c014749b924ce5710d7d89763a28"}, + {file = "mypy-1.7.1-cp311-cp311-win_amd64.whl", hash = "sha256:f6efc9bd72258f89a3816e3a98c09d36f079c223aa345c659622f056b760ab42"}, + {file = "mypy-1.7.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:6dbdec441c60699288adf051f51a5d512b0d818526d1dcfff5a41f8cd8b4aaf1"}, + {file = "mypy-1.7.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4fc3d14ee80cd22367caaaf6e014494415bf440980a3045bf5045b525680ac33"}, + {file = "mypy-1.7.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c6e4464ed5f01dc44dc9821caf67b60a4e5c3b04278286a85c067010653a0eb"}, + {file = "mypy-1.7.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:d9b338c19fa2412f76e17525c1b4f2c687a55b156320acb588df79f2e6fa9fea"}, + {file = "mypy-1.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:204e0d6de5fd2317394a4eff62065614c4892d5a4d1a7ee55b765d7a3d9e3f82"}, + {file = "mypy-1.7.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:84860e06ba363d9c0eeabd45ac0fde4b903ad7aa4f93cd8b648385a888e23200"}, + {file = "mypy-1.7.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:8c5091ebd294f7628eb25ea554852a52058ac81472c921150e3a61cdd68f75a7"}, + {file = "mypy-1.7.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40716d1f821b89838589e5b3106ebbc23636ffdef5abc31f7cd0266db936067e"}, + {file = "mypy-1.7.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:5cf3f0c5ac72139797953bd50bc6c95ac13075e62dbfcc923571180bebb662e9"}, + {file = "mypy-1.7.1-cp38-cp38-win_amd64.whl", hash = "sha256:78e25b2fd6cbb55ddfb8058417df193f0129cad5f4ee75d1502248e588d9e0d7"}, + {file = "mypy-1.7.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:75c4d2a6effd015786c87774e04331b6da863fc3fc4e8adfc3b40aa55ab516fe"}, + {file = "mypy-1.7.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:2643d145af5292ee956aa0a83c2ce1038a3bdb26e033dadeb2f7066fb0c9abce"}, + {file = "mypy-1.7.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:75aa828610b67462ffe3057d4d8a4112105ed211596b750b53cbfe182f44777a"}, + {file = "mypy-1.7.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:ee5d62d28b854eb61889cde4e1dbc10fbaa5560cb39780c3995f6737f7e82120"}, + {file = "mypy-1.7.1-cp39-cp39-win_amd64.whl", hash = "sha256:72cf32ce7dd3562373f78bd751f73c96cfb441de147cc2448a92c1a308bd0ca6"}, + {file = "mypy-1.7.1-py3-none-any.whl", hash = "sha256:f7c5d642db47376a0cc130f0de6d055056e010debdaf0707cd2b0fc7e7ef30ea"}, + {file = "mypy-1.7.1.tar.gz", hash = "sha256:fcb6d9afb1b6208b4c712af0dafdc650f518836065df0d4fb1d800f5d6773db2"}, ] [package.dependencies] @@ -197,6 +197,7 @@ typing-extensions = ">=4.1.0" [package.extras] dmypy = ["psutil (>=4.0)"] install-types = ["pip"] +mypyc = ["setuptools (>=50)"] reports = ["lxml"] [[package]] diff --git a/openapi_python_client/parser/openapi.py b/openapi_python_client/parser/openapi.py index 3bc4a3ad5..c33bc8248 100644 --- a/openapi_python_client/parser/openapi.py +++ b/openapi_python_client/parser/openapi.py @@ -46,7 +46,11 @@ class EndpointCollection: @staticmethod def from_data( - *, data: Dict[str, oai.PathItem], schemas: Schemas, parameters: Parameters, config: Config + *, + data: Dict[str, oai.PathItem], + schemas: Schemas, + parameters: Parameters, + config: Config, ) -> Tuple[Dict[utils.PythonIdentifier, "EndpointCollection"], Schemas, Parameters]: """Parse the openapi paths data to get EndpointCollections by tag""" endpoints_by_tag: Dict[utils.PythonIdentifier, EndpointCollection] = {} @@ -72,7 +76,11 @@ def from_data( # Add `PathItem` parameters if not isinstance(endpoint, ParseError): endpoint, schemas, parameters = Endpoint.add_parameters( - endpoint=endpoint, data=path_data, schemas=schemas, parameters=parameters, config=config + endpoint=endpoint, + data=path_data, + schemas=schemas, + parameters=parameters, + config=config, ) if not isinstance(endpoint, ParseError): endpoint = Endpoint.sort_parameters(endpoint=endpoint) @@ -145,7 +153,13 @@ def parse_request_form_body( config=config, ) if isinstance(prop, ModelProperty): - schemas = attr.evolve(schemas, classes_by_name={**schemas.classes_by_name, prop.class_info.name: prop}) + schemas = attr.evolve( + schemas, + classes_by_name={ + **schemas.classes_by_name, + prop.class_info.name: prop, + }, + ) return prop, schemas return None, schemas @@ -167,7 +181,13 @@ def parse_multipart_body( ) if isinstance(prop, ModelProperty): prop = attr.evolve(prop, is_multipart_body=True) - schemas = attr.evolve(schemas, classes_by_name={**schemas.classes_by_name, prop.class_info.name: prop}) + schemas = attr.evolve( + schemas, + classes_by_name={ + **schemas.classes_by_name, + prop.class_info.name: prop, + }, + ) return prop, schemas return None, schemas @@ -209,7 +229,10 @@ def _add_body( return endpoint, schemas form_body, schemas = Endpoint.parse_request_form_body( - body=data.requestBody, schemas=schemas, parent_name=endpoint.name, config=config + body=data.requestBody, + schemas=schemas, + parent_name=endpoint.name, + config=config, ) if isinstance(form_body, ParseError): @@ -223,7 +246,10 @@ def _add_body( ) json_body, schemas = Endpoint.parse_request_json_body( - body=data.requestBody, schemas=schemas, parent_name=endpoint.name, config=config + body=data.requestBody, + schemas=schemas, + parent_name=endpoint.name, + config=config, ) if isinstance(json_body, ParseError): return ( @@ -236,7 +262,10 @@ def _add_body( ) multipart_body, schemas = Endpoint.parse_multipart_body( - body=data.requestBody, schemas=schemas, parent_name=endpoint.name, config=config + body=data.requestBody, + schemas=schemas, + parent_name=endpoint.name, + config=config, ) if isinstance(multipart_body, ParseError): return ( @@ -285,7 +314,11 @@ def _add_responses( continue response, schemas = response_from_data( - status_code=status_code, data=response_data, schemas=schemas, parent_name=endpoint.name, config=config + status_code=status_code, + data=response_data, + schemas=schemas, + parent_name=endpoint.name, + config=config, ) if isinstance(response, ParseError): detail_suffix = "" if response.detail is None else f" ({response.detail})" @@ -393,7 +426,10 @@ def add_parameters( # noqa: PLR0911 if isinstance(prop, ParseError): return ( - ParseError(detail=f"cannot parse parameter of endpoint {endpoint.name}", data=prop.data), + ParseError( + detail=f"cannot parse parameter of endpoint {endpoint.name}: {prop.detail}", + data=prop.data, + ), schemas, parameters, ) @@ -432,7 +468,8 @@ def add_parameters( # noqa: PLR0911 if prop.python_name in endpoint.used_python_identifiers: return ( ParseError( - detail=f"Parameters with same Python identifier `{prop.python_name}` detected", data=data + detail=f"Parameters with same Python identifier `{prop.python_name}` detected", + data=data, ), schemas, parameters, @@ -462,7 +499,8 @@ def sort_parameters(*, endpoint: "Endpoint") -> Union["Endpoint", ParseError]: parameters_from_path = re.findall(_PATH_PARAM_REGEX, endpoint.path) try: sorted_params = sorted( - endpoint.path_parameters.values(), key=lambda param: parameters_from_path.index(param.name) + endpoint.path_parameters.values(), + key=lambda param: parameters_from_path.index(param.name), ) endpoint.path_parameters = OrderedDict((param.name, param) for param in sorted_params) except ValueError: @@ -503,7 +541,11 @@ def from_data( ) result, schemas, parameters = Endpoint.add_parameters( - endpoint=endpoint, data=data, schemas=schemas, parameters=parameters, config=config + endpoint=endpoint, + data=data, + schemas=schemas, + parameters=parameters, + config=config, ) if isinstance(result, ParseError): return result, schemas, parameters @@ -567,7 +609,9 @@ def from_dict(data: Dict[str, Any], *, config: Config) -> Union["GeneratorData", schemas = build_schemas(components=openapi.components.schemas, schemas=schemas, config=config) if openapi.components and openapi.components.parameters: parameters = build_parameters( - components=openapi.components.parameters, parameters=parameters, config=config + components=openapi.components.parameters, + parameters=parameters, + config=config, ) endpoint_collections_by_tag, schemas, parameters = EndpointCollection.from_data( data=openapi.paths, schemas=schemas, parameters=parameters, config=config diff --git a/openapi_python_client/parser/properties/__init__.py b/openapi_python_client/parser/properties/__init__.py index b3c82204d..42a60653c 100644 --- a/openapi_python_client/parser/properties/__init__.py +++ b/openapi_python_client/parser/properties/__init__.py @@ -22,6 +22,7 @@ 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 @@ -103,7 +104,10 @@ def _property_from_ref( 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): @@ -115,7 +119,7 @@ def _property_from_ref( required=required, name=name, python_name=utils.PythonIdentifier(value=name, prefix=config.field_prefix), - default=default, + default=default, # type: ignore # mypy can't tell that default comes from the same class... ) schemas.add_dependencies(ref_path=ref_path, roots=roots) @@ -137,14 +141,26 @@ def property_from_data( # noqa: PLR0911 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[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: @@ -159,10 +175,30 @@ def property_from_data( # noqa: PLR0911 ) 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 + 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.build( @@ -246,7 +282,12 @@ def property_from_data( # noqa: PLR0911 ) -def _create_schemas(*, components: dict[str, oai.Reference | oai.Schema], schemas: Schemas, config: Config) -> Schemas: +def _create_schemas( + *, + components: dict[str, oai.Reference | oai.Schema], + schemas: Schemas, + config: Config, +) -> Schemas: to_process: Iterable[tuple[str, oai.Reference | oai.Schema]] = components.items() still_making_progress = True errors: list[PropertyError] = [] @@ -337,7 +378,12 @@ def _process_models(*, schemas: Schemas, config: Config) -> Schemas: return schemas -def build_schemas(*, components: dict[str, oai.Reference | oai.Schema], schemas: Schemas, config: Config) -> Schemas: +def build_schemas( + *, + 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) schemas = _process_models(schemas=schemas, config=config) diff --git a/openapi_python_client/parser/properties/const.py b/openapi_python_client/parser/properties/const.py new file mode 100644 index 000000000..4babbf1d0 --- /dev/null +++ b/openapi_python_client/parser/properties/const.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +from typing import 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: str | int | None, + 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) + if isinstance(value, PropertyError): + return value + + 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: str | Value | None | int) -> Value | None | PropertyError: + if value is None: + return None + value_or_error = self._convert_value(value) + if isinstance(value_or_error, PropertyError): + return value_or_error + if value_or_error != self.value: + return PropertyError(detail=f"Invalid value for const {self.name}; {value_or_error} != {self.value}") + return value_or_error + + @staticmethod + @overload + def _convert_value(value: str | int) -> Value | PropertyError: + ... + + @staticmethod + @overload + def _convert_value(value: None) -> None: + ... + + @staticmethod + def _convert_value(value: str | int | Value | None) -> Value | None | PropertyError: + if value is None: + return None + if isinstance(value, Value): + return value + if isinstance(value, str): + return StringProperty.convert_value(value) + if isinstance(value, int): + return Value(repr(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/none.py b/openapi_python_client/parser/properties/none.py index 01371320f..a0ce4e93f 100644 --- a/openapi_python_client/parser/properties/none.py +++ b/openapi_python_client/parser/properties/none.py @@ -55,6 +55,6 @@ def build( def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: if isinstance(value, str): if value != "None": - return PropertyError(f"Value {value} is not valid, onlly None is allowed") + return PropertyError(f"Value {value} is not valid, only None is allowed") return Value(value) return value diff --git a/openapi_python_client/parser/properties/property.py b/openapi_python_client/parser/properties/property.py index 5e60c402a..fa3a26beb 100644 --- a/openapi_python_client/parser/properties/property.py +++ b/openapi_python_client/parser/properties/property.py @@ -6,6 +6,7 @@ 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 @@ -21,6 +22,7 @@ Property: TypeAlias = Union[ AnyProperty, BooleanProperty, + ConstProperty, DateProperty, DateTimeProperty, EnumProperty, diff --git a/openapi_python_client/schema/openapi_schema_pydantic/schema.py b/openapi_python_client/schema/openapi_schema_pydantic/schema.py index 9d693dee4..b83fa0144 100644 --- a/openapi_python_client/schema/openapi_schema_pydantic/schema.py +++ b/openapi_python_client/schema/openapi_schema_pydantic/schema.py @@ -36,6 +36,7 @@ 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) + 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) @@ -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"], diff --git a/poetry.lock b/poetry.lock index 8dd731cf9..085f66ee0 100644 --- a/poetry.lock +++ b/poetry.lock @@ -16,13 +16,13 @@ typing-extensions = {version = ">=4.0.0", markers = "python_version < \"3.9\""} [[package]] name = "anyio" -version = "4.0.0" +version = "4.1.0" description = "High level compatibility layer for multiple asynchronous event loop implementations" optional = false python-versions = ">=3.8" files = [ - {file = "anyio-4.0.0-py3-none-any.whl", hash = "sha256:cfdb2b588b9fc25ede96d8db56ed50848b0b649dca3dd1df0b11f683bb9e0b5f"}, - {file = "anyio-4.0.0.tar.gz", hash = "sha256:f7ed51751b2c2add651e5747c891b47e26d2a21be5d32d9311dfe9692f3e5d7a"}, + {file = "anyio-4.1.0-py3-none-any.whl", hash = "sha256:56a415fbc462291813a94528a779597226619c8e78af7de0507333f700011e5f"}, + {file = "anyio-4.1.0.tar.gz", hash = "sha256:5a0bec7085176715be77df87fc66d6c9d70626bd752fcc85f57cdbee5b3760da"}, ] [package.dependencies] @@ -31,9 +31,9 @@ idna = ">=2.8" sniffio = ">=1.1" [package.extras] -doc = ["Sphinx (>=7)", "packaging", "sphinx-autodoc-typehints (>=1.2.0)"] -test = ["anyio[trio]", "coverage[toml] (>=7)", "hypothesis (>=4.0)", "psutil (>=5.9)", "pytest (>=7.0)", "pytest-mock (>=3.6.1)", "trustme", "uvloop (>=0.17)"] -trio = ["trio (>=0.22)"] +doc = ["Sphinx (>=7)", "packaging", "sphinx-autodoc-typehints (>=1.2.0)", "sphinx-rtd-theme"] +test = ["anyio[trio]", "coverage[toml] (>=7)", "exceptiongroup (>=1.2.0)", "hypothesis (>=4.0)", "psutil (>=5.9)", "pytest (>=7.0)", "pytest-mock (>=3.6.1)", "trustme", "uvloop (>=0.17)"] +trio = ["trio (>=0.23)"] [[package]] name = "attrs" @@ -55,13 +55,13 @@ tests-no-zope = ["cloudpickle", "hypothesis", "mypy (>=1.1.1)", "pympler", "pyte [[package]] name = "certifi" -version = "2023.7.22" +version = "2023.11.17" description = "Python package for providing Mozilla's CA Bundle." optional = false python-versions = ">=3.6" files = [ - {file = "certifi-2023.7.22-py3-none-any.whl", hash = "sha256:92d6037539857d8206b8f6ae472e8b77db8058fec5937a1ef3f54304089edbb9"}, - {file = "certifi-2023.7.22.tar.gz", hash = "sha256:539cc1d13202e33ca466e88b2807e29f4c13049d6d87031a3c110744495cb082"}, + {file = "certifi-2023.11.17-py3-none-any.whl", hash = "sha256:e036ab49d5b79556f99cfc2d9320b34cfbe5be05c5871b51de9329f0603b0474"}, + {file = "certifi-2023.11.17.tar.gz", hash = "sha256:9b469f3a900bf28dc19b8cfbf8019bf47f7fdd1a65a1d4ffb98fc14166beb4d1"}, ] [[package]] @@ -276,13 +276,13 @@ pipenv = ["pipenv (<=2022.12.19)"] [[package]] name = "exceptiongroup" -version = "1.1.3" +version = "1.2.0" description = "Backport of PEP 654 (exception groups)" optional = false python-versions = ">=3.7" files = [ - {file = "exceptiongroup-1.1.3-py3-none-any.whl", hash = "sha256:343280667a4585d195ca1cf9cef84a4e178c4b6cf2274caef9859782b567d5e3"}, - {file = "exceptiongroup-1.1.3.tar.gz", hash = "sha256:097acd85d473d75af5bb98e41b61ff7fe35efe6675e4f9370ec6ec5126d160e9"}, + {file = "exceptiongroup-1.2.0-py3-none-any.whl", hash = "sha256:4bfd3996ac73b41e9b9628b04e079f193850720ea5945fc96a08633c66912f14"}, + {file = "exceptiongroup-1.2.0.tar.gz", hash = "sha256:91f5c769735f051a4290d52edd0858999b57e5876e9f85937691bd4c9fa3ed68"}, ] [package.extras] @@ -301,13 +301,13 @@ files = [ [[package]] name = "httpcore" -version = "1.0.1" +version = "1.0.2" description = "A minimal low-level HTTP client." optional = false python-versions = ">=3.8" files = [ - {file = "httpcore-1.0.1-py3-none-any.whl", hash = "sha256:c5e97ef177dca2023d0b9aad98e49507ef5423e9f1d94ffe2cfe250aa28e63b0"}, - {file = "httpcore-1.0.1.tar.gz", hash = "sha256:fce1ddf9b606cfb98132ab58865c3728c52c8e4c3c46e2aabb3674464a186e92"}, + {file = "httpcore-1.0.2-py3-none-any.whl", hash = "sha256:096cc05bca73b8e459a1fc3dcf585148f63e534eae4339559c9b8a8d6399acc7"}, + {file = "httpcore-1.0.2.tar.gz", hash = "sha256:9fc092e4799b26174648e54b74ed5f683132a464e95643b226e00c2ed2fa6535"}, ] [package.dependencies] @@ -322,19 +322,19 @@ trio = ["trio (>=0.22.0,<0.23.0)"] [[package]] name = "httpx" -version = "0.25.1" +version = "0.25.2" description = "The next generation HTTP client." optional = false python-versions = ">=3.8" files = [ - {file = "httpx-0.25.1-py3-none-any.whl", hash = "sha256:fec7d6cc5c27c578a391f7e87b9aa7d3d8fbcd034f6399f9f79b45bcc12a866a"}, - {file = "httpx-0.25.1.tar.gz", hash = "sha256:ffd96d5cf901e63863d9f1b4b6807861dbea4d301613415d9e6e57ead15fc5d0"}, + {file = "httpx-0.25.2-py3-none-any.whl", hash = "sha256:a05d3d052d9b2dfce0e3896636467f8a5342fb2b902c819428e1ac65413ca118"}, + {file = "httpx-0.25.2.tar.gz", hash = "sha256:8b8fcaa0c8ea7b05edd69a094e63a2094c4efcb48129fb757361bc423c0ad9e8"}, ] [package.dependencies] anyio = "*" certifi = "*" -httpcore = "*" +httpcore = "==1.*" idna = "*" sniffio = "*" @@ -346,13 +346,13 @@ socks = ["socksio (==1.*)"] [[package]] name = "idna" -version = "3.4" +version = "3.6" description = "Internationalized Domain Names in Applications (IDNA)" optional = false python-versions = ">=3.5" files = [ - {file = "idna-3.4-py3-none-any.whl", hash = "sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2"}, - {file = "idna-3.4.tar.gz", hash = "sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4"}, + {file = "idna-3.6-py3-none-any.whl", hash = "sha256:c05567e9c24a6b9faaa835c4821bad0590fbb9d5779e7caa6e1cc4978e7eb24f"}, + {file = "idna-3.6.tar.gz", hash = "sha256:9ecdbbd083b06798ae1e86adcbfe8ab1479cf864e4ee30fe4e46a003d12491ca"}, ] [[package]] @@ -454,49 +454,49 @@ files = [ [[package]] name = "mslex" -version = "0.3.0" +version = "1.1.0" description = "shlex for windows" optional = false python-versions = ">=3.5" files = [ - {file = "mslex-0.3.0-py2.py3-none-any.whl", hash = "sha256:380cb14abf8fabf40e56df5c8b21a6d533dc5cbdcfe42406bbf08dda8f42e42a"}, - {file = "mslex-0.3.0.tar.gz", hash = "sha256:4a1ac3f25025cad78ad2fe499dd16d42759f7a3801645399cce5c404415daa97"}, + {file = "mslex-1.1.0-py2.py3-none-any.whl", hash = "sha256:8826f4bb8d8c63402203d921dc8c2df0c7fec0d9c91d020ddf02fc9d0dce81bd"}, + {file = "mslex-1.1.0.tar.gz", hash = "sha256:7fe305fbdc9721283875e0b737fdb344374b761338a7f41af91875de278568e4"}, ] [[package]] name = "mypy" -version = "1.6.1" +version = "1.7.1" description = "Optional static typing for Python" optional = false python-versions = ">=3.8" files = [ - {file = "mypy-1.6.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:e5012e5cc2ac628177eaac0e83d622b2dd499e28253d4107a08ecc59ede3fc2c"}, - {file = "mypy-1.6.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:d8fbb68711905f8912e5af474ca8b78d077447d8f3918997fecbf26943ff3cbb"}, - {file = "mypy-1.6.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21a1ad938fee7d2d96ca666c77b7c494c3c5bd88dff792220e1afbebb2925b5e"}, - {file = "mypy-1.6.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:b96ae2c1279d1065413965c607712006205a9ac541895004a1e0d4f281f2ff9f"}, - {file = "mypy-1.6.1-cp310-cp310-win_amd64.whl", hash = "sha256:40b1844d2e8b232ed92e50a4bd11c48d2daa351f9deee6c194b83bf03e418b0c"}, - {file = "mypy-1.6.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:81af8adaa5e3099469e7623436881eff6b3b06db5ef75e6f5b6d4871263547e5"}, - {file = "mypy-1.6.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:8c223fa57cb154c7eab5156856c231c3f5eace1e0bed9b32a24696b7ba3c3245"}, - {file = "mypy-1.6.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a8032e00ce71c3ceb93eeba63963b864bf635a18f6c0c12da6c13c450eedb183"}, - {file = "mypy-1.6.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:4c46b51de523817a0045b150ed11b56f9fff55f12b9edd0f3ed35b15a2809de0"}, - {file = "mypy-1.6.1-cp311-cp311-win_amd64.whl", hash = "sha256:19f905bcfd9e167159b3d63ecd8cb5e696151c3e59a1742e79bc3bcb540c42c7"}, - {file = "mypy-1.6.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:82e469518d3e9a321912955cc702d418773a2fd1e91c651280a1bda10622f02f"}, - {file = "mypy-1.6.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d4473c22cc296425bbbce7e9429588e76e05bc7342da359d6520b6427bf76660"}, - {file = "mypy-1.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59a0d7d24dfb26729e0a068639a6ce3500e31d6655df8557156c51c1cb874ce7"}, - {file = "mypy-1.6.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:cfd13d47b29ed3bbaafaff7d8b21e90d827631afda134836962011acb5904b71"}, - {file = "mypy-1.6.1-cp312-cp312-win_amd64.whl", hash = "sha256:eb4f18589d196a4cbe5290b435d135dee96567e07c2b2d43b5c4621b6501531a"}, - {file = "mypy-1.6.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:41697773aa0bf53ff917aa077e2cde7aa50254f28750f9b88884acea38a16169"}, - {file = "mypy-1.6.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:7274b0c57737bd3476d2229c6389b2ec9eefeb090bbaf77777e9d6b1b5a9d143"}, - {file = "mypy-1.6.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bbaf4662e498c8c2e352da5f5bca5ab29d378895fa2d980630656178bd607c46"}, - {file = "mypy-1.6.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:bb8ccb4724f7d8601938571bf3f24da0da791fe2db7be3d9e79849cb64e0ae85"}, - {file = "mypy-1.6.1-cp38-cp38-win_amd64.whl", hash = "sha256:68351911e85145f582b5aa6cd9ad666c8958bcae897a1bfda8f4940472463c45"}, - {file = "mypy-1.6.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:49ae115da099dcc0922a7a895c1eec82c1518109ea5c162ed50e3b3594c71208"}, - {file = "mypy-1.6.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:8b27958f8c76bed8edaa63da0739d76e4e9ad4ed325c814f9b3851425582a3cd"}, - {file = "mypy-1.6.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:925cd6a3b7b55dfba252b7c4561892311c5358c6b5a601847015a1ad4eb7d332"}, - {file = "mypy-1.6.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:8f57e6b6927a49550da3d122f0cb983d400f843a8a82e65b3b380d3d7259468f"}, - {file = "mypy-1.6.1-cp39-cp39-win_amd64.whl", hash = "sha256:a43ef1c8ddfdb9575691720b6352761f3f53d85f1b57d7745701041053deff30"}, - {file = "mypy-1.6.1-py3-none-any.whl", hash = "sha256:4cbe68ef919c28ea561165206a2dcb68591c50f3bcf777932323bc208d949cf1"}, - {file = "mypy-1.6.1.tar.gz", hash = "sha256:4d01c00d09a0be62a4ca3f933e315455bde83f37f892ba4b08ce92f3cf44bcc1"}, + {file = "mypy-1.7.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:12cce78e329838d70a204293e7b29af9faa3ab14899aec397798a4b41be7f340"}, + {file = "mypy-1.7.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:1484b8fa2c10adf4474f016e09d7a159602f3239075c7bf9f1627f5acf40ad49"}, + {file = "mypy-1.7.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:31902408f4bf54108bbfb2e35369877c01c95adc6192958684473658c322c8a5"}, + {file = "mypy-1.7.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:f2c2521a8e4d6d769e3234350ba7b65ff5d527137cdcde13ff4d99114b0c8e7d"}, + {file = "mypy-1.7.1-cp310-cp310-win_amd64.whl", hash = "sha256:fcd2572dd4519e8a6642b733cd3a8cfc1ef94bafd0c1ceed9c94fe736cb65b6a"}, + {file = "mypy-1.7.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4b901927f16224d0d143b925ce9a4e6b3a758010673eeded9b748f250cf4e8f7"}, + {file = "mypy-1.7.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2f7f6985d05a4e3ce8255396df363046c28bea790e40617654e91ed580ca7c51"}, + {file = "mypy-1.7.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:944bdc21ebd620eafefc090cdf83158393ec2b1391578359776c00de00e8907a"}, + {file = "mypy-1.7.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:9c7ac372232c928fff0645d85f273a726970c014749b924ce5710d7d89763a28"}, + {file = "mypy-1.7.1-cp311-cp311-win_amd64.whl", hash = "sha256:f6efc9bd72258f89a3816e3a98c09d36f079c223aa345c659622f056b760ab42"}, + {file = "mypy-1.7.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:6dbdec441c60699288adf051f51a5d512b0d818526d1dcfff5a41f8cd8b4aaf1"}, + {file = "mypy-1.7.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4fc3d14ee80cd22367caaaf6e014494415bf440980a3045bf5045b525680ac33"}, + {file = "mypy-1.7.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c6e4464ed5f01dc44dc9821caf67b60a4e5c3b04278286a85c067010653a0eb"}, + {file = "mypy-1.7.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:d9b338c19fa2412f76e17525c1b4f2c687a55b156320acb588df79f2e6fa9fea"}, + {file = "mypy-1.7.1-cp312-cp312-win_amd64.whl", hash = "sha256:204e0d6de5fd2317394a4eff62065614c4892d5a4d1a7ee55b765d7a3d9e3f82"}, + {file = "mypy-1.7.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:84860e06ba363d9c0eeabd45ac0fde4b903ad7aa4f93cd8b648385a888e23200"}, + {file = "mypy-1.7.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:8c5091ebd294f7628eb25ea554852a52058ac81472c921150e3a61cdd68f75a7"}, + {file = "mypy-1.7.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40716d1f821b89838589e5b3106ebbc23636ffdef5abc31f7cd0266db936067e"}, + {file = "mypy-1.7.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:5cf3f0c5ac72139797953bd50bc6c95ac13075e62dbfcc923571180bebb662e9"}, + {file = "mypy-1.7.1-cp38-cp38-win_amd64.whl", hash = "sha256:78e25b2fd6cbb55ddfb8058417df193f0129cad5f4ee75d1502248e588d9e0d7"}, + {file = "mypy-1.7.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:75c4d2a6effd015786c87774e04331b6da863fc3fc4e8adfc3b40aa55ab516fe"}, + {file = "mypy-1.7.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:2643d145af5292ee956aa0a83c2ce1038a3bdb26e033dadeb2f7066fb0c9abce"}, + {file = "mypy-1.7.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:75aa828610b67462ffe3057d4d8a4112105ed211596b750b53cbfe182f44777a"}, + {file = "mypy-1.7.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:ee5d62d28b854eb61889cde4e1dbc10fbaa5560cb39780c3995f6737f7e82120"}, + {file = "mypy-1.7.1-cp39-cp39-win_amd64.whl", hash = "sha256:72cf32ce7dd3562373f78bd751f73c96cfb441de147cc2448a92c1a308bd0ca6"}, + {file = "mypy-1.7.1-py3-none-any.whl", hash = "sha256:f7c5d642db47376a0cc130f0de6d055056e010debdaf0707cd2b0fc7e7ef30ea"}, + {file = "mypy-1.7.1.tar.gz", hash = "sha256:fcb6d9afb1b6208b4c712af0dafdc650f518836065df0d4fb1d800f5d6773db2"}, ] [package.dependencies] @@ -507,6 +507,7 @@ typing-extensions = ">=4.1.0" [package.extras] dmypy = ["psutil (>=4.0)"] install-types = ["pip"] +mypyc = ["setuptools (>=50)"] reports = ["lxml"] [[package]] @@ -579,18 +580,18 @@ test = ["enum34", "ipaddress", "mock", "pywin32", "wmi"] [[package]] name = "pydantic" -version = "2.4.2" +version = "2.5.2" description = "Data validation using Python type hints" optional = false python-versions = ">=3.7" files = [ - {file = "pydantic-2.4.2-py3-none-any.whl", hash = "sha256:bc3ddf669d234f4220e6e1c4d96b061abe0998185a8d7855c0126782b7abc8c1"}, - {file = "pydantic-2.4.2.tar.gz", hash = "sha256:94f336138093a5d7f426aac732dcfe7ab4eb4da243c88f891d65deb4a2556ee7"}, + {file = "pydantic-2.5.2-py3-none-any.whl", hash = "sha256:80c50fb8e3dcecfddae1adbcc00ec5822918490c99ab31f6cf6140ca1c1429f0"}, + {file = "pydantic-2.5.2.tar.gz", hash = "sha256:ff177ba64c6faf73d7afa2e8cad38fd456c0dbe01c9954e71038001cd15a6edd"}, ] [package.dependencies] annotated-types = ">=0.4.0" -pydantic-core = "2.10.1" +pydantic-core = "2.14.5" typing-extensions = ">=4.6.1" [package.extras] @@ -598,117 +599,116 @@ email = ["email-validator (>=2.0.0)"] [[package]] name = "pydantic-core" -version = "2.10.1" +version = "2.14.5" description = "" optional = false python-versions = ">=3.7" files = [ - {file = "pydantic_core-2.10.1-cp310-cp310-macosx_10_7_x86_64.whl", hash = "sha256:d64728ee14e667ba27c66314b7d880b8eeb050e58ffc5fec3b7a109f8cddbd63"}, - {file = "pydantic_core-2.10.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:48525933fea744a3e7464c19bfede85df4aba79ce90c60b94d8b6e1eddd67096"}, - {file = "pydantic_core-2.10.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ef337945bbd76cce390d1b2496ccf9f90b1c1242a3a7bc242ca4a9fc5993427a"}, - {file = "pydantic_core-2.10.1-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a1392e0638af203cee360495fd2cfdd6054711f2db5175b6e9c3c461b76f5175"}, - {file = "pydantic_core-2.10.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0675ba5d22de54d07bccde38997e780044dcfa9a71aac9fd7d4d7a1d2e3e65f7"}, - {file = "pydantic_core-2.10.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:128552af70a64660f21cb0eb4876cbdadf1a1f9d5de820fed6421fa8de07c893"}, - {file = "pydantic_core-2.10.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8f6e6aed5818c264412ac0598b581a002a9f050cb2637a84979859e70197aa9e"}, - {file = "pydantic_core-2.10.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ecaac27da855b8d73f92123e5f03612b04c5632fd0a476e469dfc47cd37d6b2e"}, - {file = "pydantic_core-2.10.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:b3c01c2fb081fced3bbb3da78510693dc7121bb893a1f0f5f4b48013201f362e"}, - {file = "pydantic_core-2.10.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:92f675fefa977625105708492850bcbc1182bfc3e997f8eecb866d1927c98ae6"}, - {file = "pydantic_core-2.10.1-cp310-none-win32.whl", hash = "sha256:420a692b547736a8d8703c39ea935ab5d8f0d2573f8f123b0a294e49a73f214b"}, - {file = "pydantic_core-2.10.1-cp310-none-win_amd64.whl", hash = "sha256:0880e239827b4b5b3e2ce05e6b766a7414e5f5aedc4523be6b68cfbc7f61c5d0"}, - {file = "pydantic_core-2.10.1-cp311-cp311-macosx_10_7_x86_64.whl", hash = "sha256:073d4a470b195d2b2245d0343569aac7e979d3a0dcce6c7d2af6d8a920ad0bea"}, - {file = "pydantic_core-2.10.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:600d04a7b342363058b9190d4e929a8e2e715c5682a70cc37d5ded1e0dd370b4"}, - {file = "pydantic_core-2.10.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:39215d809470f4c8d1881758575b2abfb80174a9e8daf8f33b1d4379357e417c"}, - {file = "pydantic_core-2.10.1-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:eeb3d3d6b399ffe55f9a04e09e635554012f1980696d6b0aca3e6cf42a17a03b"}, - {file = "pydantic_core-2.10.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a7a7902bf75779bc12ccfc508bfb7a4c47063f748ea3de87135d433a4cca7a2f"}, - {file = "pydantic_core-2.10.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3625578b6010c65964d177626fde80cf60d7f2e297d56b925cb5cdeda6e9925a"}, - {file = "pydantic_core-2.10.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:caa48fc31fc7243e50188197b5f0c4228956f97b954f76da157aae7f67269ae8"}, - {file = "pydantic_core-2.10.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:07ec6d7d929ae9c68f716195ce15e745b3e8fa122fc67698ac6498d802ed0fa4"}, - {file = "pydantic_core-2.10.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:e6f31a17acede6a8cd1ae2d123ce04d8cca74056c9d456075f4f6f85de055607"}, - {file = "pydantic_core-2.10.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:d8f1ebca515a03e5654f88411420fea6380fc841d1bea08effb28184e3d4899f"}, - {file = "pydantic_core-2.10.1-cp311-none-win32.whl", hash = "sha256:6db2eb9654a85ada248afa5a6db5ff1cf0f7b16043a6b070adc4a5be68c716d6"}, - {file = "pydantic_core-2.10.1-cp311-none-win_amd64.whl", hash = "sha256:4a5be350f922430997f240d25f8219f93b0c81e15f7b30b868b2fddfc2d05f27"}, - {file = "pydantic_core-2.10.1-cp311-none-win_arm64.whl", hash = "sha256:5fdb39f67c779b183b0c853cd6b45f7db84b84e0571b3ef1c89cdb1dfc367325"}, - {file = "pydantic_core-2.10.1-cp312-cp312-macosx_10_7_x86_64.whl", hash = "sha256:b1f22a9ab44de5f082216270552aa54259db20189e68fc12484873d926426921"}, - {file = "pydantic_core-2.10.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8572cadbf4cfa95fb4187775b5ade2eaa93511f07947b38f4cd67cf10783b118"}, - {file = "pydantic_core-2.10.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:db9a28c063c7c00844ae42a80203eb6d2d6bbb97070cfa00194dff40e6f545ab"}, - {file = "pydantic_core-2.10.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:0e2a35baa428181cb2270a15864ec6286822d3576f2ed0f4cd7f0c1708472aff"}, - {file = "pydantic_core-2.10.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:05560ab976012bf40f25d5225a58bfa649bb897b87192a36c6fef1ab132540d7"}, - {file = "pydantic_core-2.10.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d6495008733c7521a89422d7a68efa0a0122c99a5861f06020ef5b1f51f9ba7c"}, - {file = "pydantic_core-2.10.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:14ac492c686defc8e6133e3a2d9eaf5261b3df26b8ae97450c1647286750b901"}, - {file = "pydantic_core-2.10.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8282bab177a9a3081fd3d0a0175a07a1e2bfb7fcbbd949519ea0980f8a07144d"}, - {file = "pydantic_core-2.10.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:aafdb89fdeb5fe165043896817eccd6434aee124d5ee9b354f92cd574ba5e78f"}, - {file = "pydantic_core-2.10.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:f6defd966ca3b187ec6c366604e9296f585021d922e666b99c47e78738b5666c"}, - {file = "pydantic_core-2.10.1-cp312-none-win32.whl", hash = "sha256:7c4d1894fe112b0864c1fa75dffa045720a194b227bed12f4be7f6045b25209f"}, - {file = "pydantic_core-2.10.1-cp312-none-win_amd64.whl", hash = "sha256:5994985da903d0b8a08e4935c46ed8daf5be1cf217489e673910951dc533d430"}, - {file = "pydantic_core-2.10.1-cp312-none-win_arm64.whl", hash = "sha256:0d8a8adef23d86d8eceed3e32e9cca8879c7481c183f84ed1a8edc7df073af94"}, - {file = "pydantic_core-2.10.1-cp37-cp37m-macosx_10_7_x86_64.whl", hash = "sha256:9badf8d45171d92387410b04639d73811b785b5161ecadabf056ea14d62d4ede"}, - {file = "pydantic_core-2.10.1-cp37-cp37m-macosx_11_0_arm64.whl", hash = "sha256:ebedb45b9feb7258fac0a268a3f6bec0a2ea4d9558f3d6f813f02ff3a6dc6698"}, - {file = "pydantic_core-2.10.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cfe1090245c078720d250d19cb05d67e21a9cd7c257698ef139bc41cf6c27b4f"}, - {file = "pydantic_core-2.10.1-cp37-cp37m-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:e357571bb0efd65fd55f18db0a2fb0ed89d0bb1d41d906b138f088933ae618bb"}, - {file = "pydantic_core-2.10.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b3dcd587b69bbf54fc04ca157c2323b8911033e827fffaecf0cafa5a892a0904"}, - {file = "pydantic_core-2.10.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9c120c9ce3b163b985a3b966bb701114beb1da4b0468b9b236fc754783d85aa3"}, - {file = "pydantic_core-2.10.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:15d6bca84ffc966cc9976b09a18cf9543ed4d4ecbd97e7086f9ce9327ea48891"}, - {file = "pydantic_core-2.10.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5cabb9710f09d5d2e9e2748c3e3e20d991a4c5f96ed8f1132518f54ab2967221"}, - {file = "pydantic_core-2.10.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:82f55187a5bebae7d81d35b1e9aaea5e169d44819789837cdd4720d768c55d15"}, - {file = "pydantic_core-2.10.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:1d40f55222b233e98e3921df7811c27567f0e1a4411b93d4c5c0f4ce131bc42f"}, - {file = "pydantic_core-2.10.1-cp37-none-win32.whl", hash = "sha256:14e09ff0b8fe6e46b93d36a878f6e4a3a98ba5303c76bb8e716f4878a3bee92c"}, - {file = "pydantic_core-2.10.1-cp37-none-win_amd64.whl", hash = "sha256:1396e81b83516b9d5c9e26a924fa69164156c148c717131f54f586485ac3c15e"}, - {file = "pydantic_core-2.10.1-cp38-cp38-macosx_10_7_x86_64.whl", hash = "sha256:6835451b57c1b467b95ffb03a38bb75b52fb4dc2762bb1d9dbed8de31ea7d0fc"}, - {file = "pydantic_core-2.10.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:b00bc4619f60c853556b35f83731bd817f989cba3e97dc792bb8c97941b8053a"}, - {file = "pydantic_core-2.10.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0fa467fd300a6f046bdb248d40cd015b21b7576c168a6bb20aa22e595c8ffcdd"}, - {file = "pydantic_core-2.10.1-cp38-cp38-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d99277877daf2efe074eae6338453a4ed54a2d93fb4678ddfe1209a0c93a2468"}, - {file = "pydantic_core-2.10.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fa7db7558607afeccb33c0e4bf1c9a9a835e26599e76af6fe2fcea45904083a6"}, - {file = "pydantic_core-2.10.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:aad7bd686363d1ce4ee930ad39f14e1673248373f4a9d74d2b9554f06199fb58"}, - {file = "pydantic_core-2.10.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:443fed67d33aa85357464f297e3d26e570267d1af6fef1c21ca50921d2976302"}, - {file = "pydantic_core-2.10.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:042462d8d6ba707fd3ce9649e7bf268633a41018d6a998fb5fbacb7e928a183e"}, - {file = "pydantic_core-2.10.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:ecdbde46235f3d560b18be0cb706c8e8ad1b965e5c13bbba7450c86064e96561"}, - {file = "pydantic_core-2.10.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:ed550ed05540c03f0e69e6d74ad58d026de61b9eaebebbaaf8873e585cbb18de"}, - {file = "pydantic_core-2.10.1-cp38-none-win32.whl", hash = "sha256:8cdbbd92154db2fec4ec973d45c565e767ddc20aa6dbaf50142676484cbff8ee"}, - {file = "pydantic_core-2.10.1-cp38-none-win_amd64.whl", hash = "sha256:9f6f3e2598604956480f6c8aa24a3384dbf6509fe995d97f6ca6103bb8c2534e"}, - {file = "pydantic_core-2.10.1-cp39-cp39-macosx_10_7_x86_64.whl", hash = "sha256:655f8f4c8d6a5963c9a0687793da37b9b681d9ad06f29438a3b2326d4e6b7970"}, - {file = "pydantic_core-2.10.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e570ffeb2170e116a5b17e83f19911020ac79d19c96f320cbfa1fa96b470185b"}, - {file = "pydantic_core-2.10.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:64322bfa13e44c6c30c518729ef08fda6026b96d5c0be724b3c4ae4da939f875"}, - {file = "pydantic_core-2.10.1-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:485a91abe3a07c3a8d1e082ba29254eea3e2bb13cbbd4351ea4e5a21912cc9b0"}, - {file = "pydantic_core-2.10.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f7c2b8eb9fc872e68b46eeaf835e86bccc3a58ba57d0eedc109cbb14177be531"}, - {file = "pydantic_core-2.10.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a5cb87bdc2e5f620693148b5f8f842d293cae46c5f15a1b1bf7ceeed324a740c"}, - {file = "pydantic_core-2.10.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:25bd966103890ccfa028841a8f30cebcf5875eeac8c4bde4fe221364c92f0c9a"}, - {file = "pydantic_core-2.10.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f323306d0556351735b54acbf82904fe30a27b6a7147153cbe6e19aaaa2aa429"}, - {file = "pydantic_core-2.10.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:0c27f38dc4fbf07b358b2bc90edf35e82d1703e22ff2efa4af4ad5de1b3833e7"}, - {file = "pydantic_core-2.10.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:f1365e032a477c1430cfe0cf2856679529a2331426f8081172c4a74186f1d595"}, - {file = "pydantic_core-2.10.1-cp39-none-win32.whl", hash = "sha256:a1c311fd06ab3b10805abb72109f01a134019739bd3286b8ae1bc2fc4e50c07a"}, - {file = "pydantic_core-2.10.1-cp39-none-win_amd64.whl", hash = "sha256:ae8a8843b11dc0b03b57b52793e391f0122e740de3df1474814c700d2622950a"}, - {file = "pydantic_core-2.10.1-pp310-pypy310_pp73-macosx_10_7_x86_64.whl", hash = "sha256:d43002441932f9a9ea5d6f9efaa2e21458221a3a4b417a14027a1d530201ef1b"}, - {file = "pydantic_core-2.10.1-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:fcb83175cc4936a5425dde3356f079ae03c0802bbdf8ff82c035f8a54b333521"}, - {file = "pydantic_core-2.10.1-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:962ed72424bf1f72334e2f1e61b68f16c0e596f024ca7ac5daf229f7c26e4208"}, - {file = "pydantic_core-2.10.1-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2cf5bb4dd67f20f3bbc1209ef572a259027c49e5ff694fa56bed62959b41e1f9"}, - {file = "pydantic_core-2.10.1-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e544246b859f17373bed915182ab841b80849ed9cf23f1f07b73b7c58baee5fb"}, - {file = "pydantic_core-2.10.1-pp310-pypy310_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:c0877239307b7e69d025b73774e88e86ce82f6ba6adf98f41069d5b0b78bd1bf"}, - {file = "pydantic_core-2.10.1-pp310-pypy310_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:53df009d1e1ba40f696f8995683e067e3967101d4bb4ea6f667931b7d4a01357"}, - {file = "pydantic_core-2.10.1-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:a1254357f7e4c82e77c348dabf2d55f1d14d19d91ff025004775e70a6ef40ada"}, - {file = "pydantic_core-2.10.1-pp37-pypy37_pp73-macosx_10_7_x86_64.whl", hash = "sha256:524ff0ca3baea164d6d93a32c58ac79eca9f6cf713586fdc0adb66a8cdeab96a"}, - {file = "pydantic_core-2.10.1-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3f0ac9fb8608dbc6eaf17956bf623c9119b4db7dbb511650910a82e261e6600f"}, - {file = "pydantic_core-2.10.1-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:320f14bd4542a04ab23747ff2c8a778bde727158b606e2661349557f0770711e"}, - {file = "pydantic_core-2.10.1-pp37-pypy37_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:63974d168b6233b4ed6a0046296803cb13c56637a7b8106564ab575926572a55"}, - {file = "pydantic_core-2.10.1-pp37-pypy37_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:417243bf599ba1f1fef2bb8c543ceb918676954734e2dcb82bf162ae9d7bd514"}, - {file = "pydantic_core-2.10.1-pp37-pypy37_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:dda81e5ec82485155a19d9624cfcca9be88a405e2857354e5b089c2a982144b2"}, - {file = "pydantic_core-2.10.1-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:14cfbb00959259e15d684505263d5a21732b31248a5dd4941f73a3be233865b9"}, - {file = "pydantic_core-2.10.1-pp38-pypy38_pp73-macosx_10_7_x86_64.whl", hash = "sha256:631cb7415225954fdcc2a024119101946793e5923f6c4d73a5914d27eb3d3a05"}, - {file = "pydantic_core-2.10.1-pp38-pypy38_pp73-macosx_11_0_arm64.whl", hash = "sha256:bec7dd208a4182e99c5b6c501ce0b1f49de2802448d4056091f8e630b28e9a52"}, - {file = "pydantic_core-2.10.1-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:149b8a07712f45b332faee1a2258d8ef1fb4a36f88c0c17cb687f205c5dc6e7d"}, - {file = "pydantic_core-2.10.1-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4d966c47f9dd73c2d32a809d2be529112d509321c5310ebf54076812e6ecd884"}, - {file = "pydantic_core-2.10.1-pp38-pypy38_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:7eb037106f5c6b3b0b864ad226b0b7ab58157124161d48e4b30c4a43fef8bc4b"}, - {file = "pydantic_core-2.10.1-pp38-pypy38_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:154ea7c52e32dce13065dbb20a4a6f0cc012b4f667ac90d648d36b12007fa9f7"}, - {file = "pydantic_core-2.10.1-pp38-pypy38_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:e562617a45b5a9da5be4abe72b971d4f00bf8555eb29bb91ec2ef2be348cd132"}, - {file = "pydantic_core-2.10.1-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:f23b55eb5464468f9e0e9a9935ce3ed2a870608d5f534025cd5536bca25b1402"}, - {file = "pydantic_core-2.10.1-pp39-pypy39_pp73-macosx_10_7_x86_64.whl", hash = "sha256:e9121b4009339b0f751955baf4543a0bfd6bc3f8188f8056b1a25a2d45099934"}, - {file = "pydantic_core-2.10.1-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:0523aeb76e03f753b58be33b26540880bac5aa54422e4462404c432230543f33"}, - {file = "pydantic_core-2.10.1-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2e0e2959ef5d5b8dc9ef21e1a305a21a36e254e6a34432d00c72a92fdc5ecda5"}, - {file = "pydantic_core-2.10.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:da01bec0a26befab4898ed83b362993c844b9a607a86add78604186297eb047e"}, - {file = "pydantic_core-2.10.1-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f2e9072d71c1f6cfc79a36d4484c82823c560e6f5599c43c1ca6b5cdbd54f881"}, - {file = "pydantic_core-2.10.1-pp39-pypy39_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:f36a3489d9e28fe4b67be9992a23029c3cec0babc3bd9afb39f49844a8c721c5"}, - {file = "pydantic_core-2.10.1-pp39-pypy39_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:f64f82cc3443149292b32387086d02a6c7fb39b8781563e0ca7b8d7d9cf72bd7"}, - {file = "pydantic_core-2.10.1-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:b4a6db486ac8e99ae696e09efc8b2b9fea67b63c8f88ba7a1a16c24a057a0776"}, - {file = "pydantic_core-2.10.1.tar.gz", hash = "sha256:0f8682dbdd2f67f8e1edddcbffcc29f60a6182b4901c367fc8c1c40d30bb0a82"}, + {file = "pydantic_core-2.14.5-cp310-cp310-macosx_10_7_x86_64.whl", hash = "sha256:7e88f5696153dc516ba6e79f82cc4747e87027205f0e02390c21f7cb3bd8abfd"}, + {file = "pydantic_core-2.14.5-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:4641e8ad4efb697f38a9b64ca0523b557c7931c5f84e0fd377a9a3b05121f0de"}, + {file = "pydantic_core-2.14.5-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:774de879d212db5ce02dfbf5b0da9a0ea386aeba12b0b95674a4ce0593df3d07"}, + {file = "pydantic_core-2.14.5-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ebb4e035e28f49b6f1a7032920bb9a0c064aedbbabe52c543343d39341a5b2a3"}, + {file = "pydantic_core-2.14.5-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b53e9ad053cd064f7e473a5f29b37fc4cc9dc6d35f341e6afc0155ea257fc911"}, + {file = "pydantic_core-2.14.5-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8aa1768c151cf562a9992462239dfc356b3d1037cc5a3ac829bb7f3bda7cc1f9"}, + {file = "pydantic_core-2.14.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eac5c82fc632c599f4639a5886f96867ffced74458c7db61bc9a66ccb8ee3113"}, + {file = "pydantic_core-2.14.5-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d2ae91f50ccc5810b2f1b6b858257c9ad2e08da70bf890dee02de1775a387c66"}, + {file = "pydantic_core-2.14.5-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:6b9ff467ffbab9110e80e8c8de3bcfce8e8b0fd5661ac44a09ae5901668ba997"}, + {file = "pydantic_core-2.14.5-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:61ea96a78378e3bd5a0be99b0e5ed00057b71f66115f5404d0dae4819f495093"}, + {file = "pydantic_core-2.14.5-cp310-none-win32.whl", hash = "sha256:bb4c2eda937a5e74c38a41b33d8c77220380a388d689bcdb9b187cf6224c9720"}, + {file = "pydantic_core-2.14.5-cp310-none-win_amd64.whl", hash = "sha256:b7851992faf25eac90bfcb7bfd19e1f5ffa00afd57daec8a0042e63c74a4551b"}, + {file = "pydantic_core-2.14.5-cp311-cp311-macosx_10_7_x86_64.whl", hash = "sha256:4e40f2bd0d57dac3feb3a3aed50f17d83436c9e6b09b16af271b6230a2915459"}, + {file = "pydantic_core-2.14.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ab1cdb0f14dc161ebc268c09db04d2c9e6f70027f3b42446fa11c153521c0e88"}, + {file = "pydantic_core-2.14.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aae7ea3a1c5bb40c93cad361b3e869b180ac174656120c42b9fadebf685d121b"}, + {file = "pydantic_core-2.14.5-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:60b7607753ba62cf0739177913b858140f11b8af72f22860c28eabb2f0a61937"}, + {file = "pydantic_core-2.14.5-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2248485b0322c75aee7565d95ad0e16f1c67403a470d02f94da7344184be770f"}, + {file = "pydantic_core-2.14.5-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:823fcc638f67035137a5cd3f1584a4542d35a951c3cc68c6ead1df7dac825c26"}, + {file = "pydantic_core-2.14.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:96581cfefa9123accc465a5fd0cc833ac4d75d55cc30b633b402e00e7ced00a6"}, + {file = "pydantic_core-2.14.5-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a33324437018bf6ba1bb0f921788788641439e0ed654b233285b9c69704c27b4"}, + {file = "pydantic_core-2.14.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:9bd18fee0923ca10f9a3ff67d4851c9d3e22b7bc63d1eddc12f439f436f2aada"}, + {file = "pydantic_core-2.14.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:853a2295c00f1d4429db4c0fb9475958543ee80cfd310814b5c0ef502de24dda"}, + {file = "pydantic_core-2.14.5-cp311-none-win32.whl", hash = "sha256:cb774298da62aea5c80a89bd58c40205ab4c2abf4834453b5de207d59d2e1651"}, + {file = "pydantic_core-2.14.5-cp311-none-win_amd64.whl", hash = "sha256:e87fc540c6cac7f29ede02e0f989d4233f88ad439c5cdee56f693cc9c1c78077"}, + {file = "pydantic_core-2.14.5-cp311-none-win_arm64.whl", hash = "sha256:57d52fa717ff445cb0a5ab5237db502e6be50809b43a596fb569630c665abddf"}, + {file = "pydantic_core-2.14.5-cp312-cp312-macosx_10_7_x86_64.whl", hash = "sha256:e60f112ac88db9261ad3a52032ea46388378034f3279c643499edb982536a093"}, + {file = "pydantic_core-2.14.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6e227c40c02fd873c2a73a98c1280c10315cbebe26734c196ef4514776120aeb"}, + {file = "pydantic_core-2.14.5-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f0cbc7fff06a90bbd875cc201f94ef0ee3929dfbd5c55a06674b60857b8b85ed"}, + {file = "pydantic_core-2.14.5-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:103ef8d5b58596a731b690112819501ba1db7a36f4ee99f7892c40da02c3e189"}, + {file = "pydantic_core-2.14.5-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c949f04ecad823f81b1ba94e7d189d9dfb81edbb94ed3f8acfce41e682e48cef"}, + {file = "pydantic_core-2.14.5-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c1452a1acdf914d194159439eb21e56b89aa903f2e1c65c60b9d874f9b950e5d"}, + {file = "pydantic_core-2.14.5-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cb4679d4c2b089e5ef89756bc73e1926745e995d76e11925e3e96a76d5fa51fc"}, + {file = "pydantic_core-2.14.5-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:cf9d3fe53b1ee360e2421be95e62ca9b3296bf3f2fb2d3b83ca49ad3f925835e"}, + {file = "pydantic_core-2.14.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:70f4b4851dbb500129681d04cc955be2a90b2248d69273a787dda120d5cf1f69"}, + {file = "pydantic_core-2.14.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:59986de5710ad9613ff61dd9b02bdd2f615f1a7052304b79cc8fa2eb4e336d2d"}, + {file = "pydantic_core-2.14.5-cp312-none-win32.whl", hash = "sha256:699156034181e2ce106c89ddb4b6504c30db8caa86e0c30de47b3e0654543260"}, + {file = "pydantic_core-2.14.5-cp312-none-win_amd64.whl", hash = "sha256:5baab5455c7a538ac7e8bf1feec4278a66436197592a9bed538160a2e7d11e36"}, + {file = "pydantic_core-2.14.5-cp312-none-win_arm64.whl", hash = "sha256:e47e9a08bcc04d20975b6434cc50bf82665fbc751bcce739d04a3120428f3e27"}, + {file = "pydantic_core-2.14.5-cp37-cp37m-macosx_10_7_x86_64.whl", hash = "sha256:af36f36538418f3806048f3b242a1777e2540ff9efaa667c27da63d2749dbce0"}, + {file = "pydantic_core-2.14.5-cp37-cp37m-macosx_11_0_arm64.whl", hash = "sha256:45e95333b8418ded64745f14574aa9bfc212cb4fbeed7a687b0c6e53b5e188cd"}, + {file = "pydantic_core-2.14.5-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e47a76848f92529879ecfc417ff88a2806438f57be4a6a8bf2961e8f9ca9ec7"}, + {file = "pydantic_core-2.14.5-cp37-cp37m-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d81e6987b27bc7d101c8597e1cd2bcaa2fee5e8e0f356735c7ed34368c471550"}, + {file = "pydantic_core-2.14.5-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:34708cc82c330e303f4ce87758828ef6e457681b58ce0e921b6e97937dd1e2a3"}, + {file = "pydantic_core-2.14.5-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:652c1988019752138b974c28f43751528116bcceadad85f33a258869e641d753"}, + {file = "pydantic_core-2.14.5-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6e4d090e73e0725b2904fdbdd8d73b8802ddd691ef9254577b708d413bf3006e"}, + {file = "pydantic_core-2.14.5-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5c7d5b5005f177764e96bd584d7bf28d6e26e96f2a541fdddb934c486e36fd59"}, + {file = "pydantic_core-2.14.5-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:a71891847f0a73b1b9eb86d089baee301477abef45f7eaf303495cd1473613e4"}, + {file = "pydantic_core-2.14.5-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:a717aef6971208f0851a2420b075338e33083111d92041157bbe0e2713b37325"}, + {file = "pydantic_core-2.14.5-cp37-none-win32.whl", hash = "sha256:de790a3b5aa2124b8b78ae5faa033937a72da8efe74b9231698b5a1dd9be3405"}, + {file = "pydantic_core-2.14.5-cp37-none-win_amd64.whl", hash = "sha256:6c327e9cd849b564b234da821236e6bcbe4f359a42ee05050dc79d8ed2a91588"}, + {file = "pydantic_core-2.14.5-cp38-cp38-macosx_10_7_x86_64.whl", hash = "sha256:ef98ca7d5995a82f43ec0ab39c4caf6a9b994cb0b53648ff61716370eadc43cf"}, + {file = "pydantic_core-2.14.5-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:c6eae413494a1c3f89055da7a5515f32e05ebc1a234c27674a6956755fb2236f"}, + {file = "pydantic_core-2.14.5-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dcf4e6d85614f7a4956c2de5a56531f44efb973d2fe4a444d7251df5d5c4dcfd"}, + {file = "pydantic_core-2.14.5-cp38-cp38-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6637560562134b0e17de333d18e69e312e0458ee4455bdad12c37100b7cad706"}, + {file = "pydantic_core-2.14.5-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:77fa384d8e118b3077cccfcaf91bf83c31fe4dc850b5e6ee3dc14dc3d61bdba1"}, + {file = "pydantic_core-2.14.5-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:16e29bad40bcf97aac682a58861249ca9dcc57c3f6be22f506501833ddb8939c"}, + {file = "pydantic_core-2.14.5-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:531f4b4252fac6ca476fbe0e6f60f16f5b65d3e6b583bc4d87645e4e5ddde331"}, + {file = "pydantic_core-2.14.5-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:074f3d86f081ce61414d2dc44901f4f83617329c6f3ab49d2bc6c96948b2c26b"}, + {file = "pydantic_core-2.14.5-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:c2adbe22ab4babbca99c75c5d07aaf74f43c3195384ec07ccbd2f9e3bddaecec"}, + {file = "pydantic_core-2.14.5-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:0f6116a558fd06d1b7c2902d1c4cf64a5bd49d67c3540e61eccca93f41418124"}, + {file = "pydantic_core-2.14.5-cp38-none-win32.whl", hash = "sha256:fe0a5a1025eb797752136ac8b4fa21aa891e3d74fd340f864ff982d649691867"}, + {file = "pydantic_core-2.14.5-cp38-none-win_amd64.whl", hash = "sha256:079206491c435b60778cf2b0ee5fd645e61ffd6e70c47806c9ed51fc75af078d"}, + {file = "pydantic_core-2.14.5-cp39-cp39-macosx_10_7_x86_64.whl", hash = "sha256:a6a16f4a527aae4f49c875da3cdc9508ac7eef26e7977952608610104244e1b7"}, + {file = "pydantic_core-2.14.5-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:abf058be9517dc877227ec3223f0300034bd0e9f53aebd63cf4456c8cb1e0863"}, + {file = "pydantic_core-2.14.5-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:49b08aae5013640a3bfa25a8eebbd95638ec3f4b2eaf6ed82cf0c7047133f03b"}, + {file = "pydantic_core-2.14.5-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c2d97e906b4ff36eb464d52a3bc7d720bd6261f64bc4bcdbcd2c557c02081ed2"}, + {file = "pydantic_core-2.14.5-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3128e0bbc8c091ec4375a1828d6118bc20404883169ac95ffa8d983b293611e6"}, + {file = "pydantic_core-2.14.5-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:88e74ab0cdd84ad0614e2750f903bb0d610cc8af2cc17f72c28163acfcf372a4"}, + {file = "pydantic_core-2.14.5-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c339dabd8ee15f8259ee0f202679b6324926e5bc9e9a40bf981ce77c038553db"}, + {file = "pydantic_core-2.14.5-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:3387277f1bf659caf1724e1afe8ee7dbc9952a82d90f858ebb931880216ea955"}, + {file = "pydantic_core-2.14.5-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:ba6b6b3846cfc10fdb4c971980a954e49d447cd215ed5a77ec8190bc93dd7bc5"}, + {file = "pydantic_core-2.14.5-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:ca61d858e4107ce5e1330a74724fe757fc7135190eb5ce5c9d0191729f033209"}, + {file = "pydantic_core-2.14.5-cp39-none-win32.whl", hash = "sha256:ec1e72d6412f7126eb7b2e3bfca42b15e6e389e1bc88ea0069d0cc1742f477c6"}, + {file = "pydantic_core-2.14.5-cp39-none-win_amd64.whl", hash = "sha256:c0b97ec434041827935044bbbe52b03d6018c2897349670ff8fe11ed24d1d4ab"}, + {file = "pydantic_core-2.14.5-pp310-pypy310_pp73-macosx_10_7_x86_64.whl", hash = "sha256:79e0a2cdbdc7af3f4aee3210b1172ab53d7ddb6a2d8c24119b5706e622b346d0"}, + {file = "pydantic_core-2.14.5-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:678265f7b14e138d9a541ddabbe033012a2953315739f8cfa6d754cc8063e8ca"}, + {file = "pydantic_core-2.14.5-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:95b15e855ae44f0c6341ceb74df61b606e11f1087e87dcb7482377374aac6abe"}, + {file = "pydantic_core-2.14.5-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:09b0e985fbaf13e6b06a56d21694d12ebca6ce5414b9211edf6f17738d82b0f8"}, + {file = "pydantic_core-2.14.5-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:3ad873900297bb36e4b6b3f7029d88ff9829ecdc15d5cf20161775ce12306f8a"}, + {file = "pydantic_core-2.14.5-pp310-pypy310_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:2d0ae0d8670164e10accbeb31d5ad45adb71292032d0fdb9079912907f0085f4"}, + {file = "pydantic_core-2.14.5-pp310-pypy310_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:d37f8ec982ead9ba0a22a996129594938138a1503237b87318392a48882d50b7"}, + {file = "pydantic_core-2.14.5-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:35613015f0ba7e14c29ac6c2483a657ec740e5ac5758d993fdd5870b07a61d8b"}, + {file = "pydantic_core-2.14.5-pp37-pypy37_pp73-macosx_10_7_x86_64.whl", hash = "sha256:ab4ea451082e684198636565224bbb179575efc1658c48281b2c866bfd4ddf04"}, + {file = "pydantic_core-2.14.5-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4ce601907e99ea5b4adb807ded3570ea62186b17f88e271569144e8cca4409c7"}, + {file = "pydantic_core-2.14.5-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fb2ed8b3fe4bf4506d6dab3b93b83bbc22237e230cba03866d561c3577517d18"}, + {file = "pydantic_core-2.14.5-pp37-pypy37_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:70f947628e074bb2526ba1b151cee10e4c3b9670af4dbb4d73bc8a89445916b5"}, + {file = "pydantic_core-2.14.5-pp37-pypy37_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:4bc536201426451f06f044dfbf341c09f540b4ebdb9fd8d2c6164d733de5e634"}, + {file = "pydantic_core-2.14.5-pp37-pypy37_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:f4791cf0f8c3104ac668797d8c514afb3431bc3305f5638add0ba1a5a37e0d88"}, + {file = "pydantic_core-2.14.5-pp38-pypy38_pp73-macosx_10_7_x86_64.whl", hash = "sha256:038c9f763e650712b899f983076ce783175397c848da04985658e7628cbe873b"}, + {file = "pydantic_core-2.14.5-pp38-pypy38_pp73-macosx_11_0_arm64.whl", hash = "sha256:27548e16c79702f1e03f5628589c6057c9ae17c95b4c449de3c66b589ead0520"}, + {file = "pydantic_core-2.14.5-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c97bee68898f3f4344eb02fec316db93d9700fb1e6a5b760ffa20d71d9a46ce3"}, + {file = "pydantic_core-2.14.5-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b9b759b77f5337b4ea024f03abc6464c9f35d9718de01cfe6bae9f2e139c397e"}, + {file = "pydantic_core-2.14.5-pp38-pypy38_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:439c9afe34638ace43a49bf72d201e0ffc1a800295bed8420c2a9ca8d5e3dbb3"}, + {file = "pydantic_core-2.14.5-pp38-pypy38_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:ba39688799094c75ea8a16a6b544eb57b5b0f3328697084f3f2790892510d144"}, + {file = "pydantic_core-2.14.5-pp38-pypy38_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:ccd4d5702bb90b84df13bd491be8d900b92016c5a455b7e14630ad7449eb03f8"}, + {file = "pydantic_core-2.14.5-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:81982d78a45d1e5396819bbb4ece1fadfe5f079335dd28c4ab3427cd95389944"}, + {file = "pydantic_core-2.14.5-pp39-pypy39_pp73-macosx_10_7_x86_64.whl", hash = "sha256:7f8210297b04e53bc3da35db08b7302a6a1f4889c79173af69b72ec9754796b8"}, + {file = "pydantic_core-2.14.5-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:8c8a8812fe6f43a3a5b054af6ac2d7b8605c7bcab2804a8a7d68b53f3cd86e00"}, + {file = "pydantic_core-2.14.5-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:206ed23aecd67c71daf5c02c3cd19c0501b01ef3cbf7782db9e4e051426b3d0d"}, + {file = "pydantic_core-2.14.5-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c2027d05c8aebe61d898d4cffd774840a9cb82ed356ba47a90d99ad768f39789"}, + {file = "pydantic_core-2.14.5-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:40180930807ce806aa71eda5a5a5447abb6b6a3c0b4b3b1b1962651906484d68"}, + {file = "pydantic_core-2.14.5-pp39-pypy39_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:615a0a4bff11c45eb3c1996ceed5bdaa2f7b432425253a7c2eed33bb86d80abc"}, + {file = "pydantic_core-2.14.5-pp39-pypy39_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:f5e412d717366e0677ef767eac93566582518fe8be923361a5c204c1a62eaafe"}, + {file = "pydantic_core-2.14.5-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:513b07e99c0a267b1d954243845d8a833758a6726a3b5d8948306e3fe14675e3"}, + {file = "pydantic_core-2.14.5.tar.gz", hash = "sha256:6d30226dfc816dd0fdf120cae611dd2215117e4f9b124af8c60ab9093b6e8e71"}, ] [package.dependencies] @@ -920,24 +920,24 @@ python-versions = ">=3.6" files = [ {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:b42169467c42b692c19cf539c38d4602069d8c1505e97b86387fcf7afb766e1d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-macosx_13_0_arm64.whl", hash = "sha256:07238db9cbdf8fc1e9de2489a4f68474e70dffcb32232db7c08fa61ca0c7c462"}, - {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux2014_aarch64.whl", hash = "sha256:d92f81886165cb14d7b067ef37e142256f1c6a90a65cd156b063a43da1708cfd"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:fff3573c2db359f091e1589c3d7c5fc2f86f5bdb6f24252c2d8e539d4e45f412"}, + {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-manylinux_2_24_aarch64.whl", hash = "sha256:aa2267c6a303eb483de8d02db2871afb5c5fc15618d894300b88958f729ad74f"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:840f0c7f194986a63d2c2465ca63af8ccbbc90ab1c6001b1978f05119b5e7334"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:024cfe1fc7c7f4e1aff4a81e718109e13409767e4f871443cbff3dba3578203d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-win32.whl", hash = "sha256:c69212f63169ec1cfc9bb44723bf2917cbbd8f6191a00ef3410f5a7fe300722d"}, {file = "ruamel.yaml.clib-0.2.8-cp310-cp310-win_amd64.whl", hash = "sha256:cabddb8d8ead485e255fe80429f833172b4cadf99274db39abc080e068cbcc31"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bef08cd86169d9eafb3ccb0a39edb11d8e25f3dae2b28f5c52fd997521133069"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-macosx_13_0_arm64.whl", hash = "sha256:b16420e621d26fdfa949a8b4b47ade8810c56002f5389970db4ddda51dbff248"}, - {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux2014_aarch64.whl", hash = "sha256:b5edda50e5e9e15e54a6a8a0070302b00c518a9d32accc2346ad6c984aacd279"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl", hash = "sha256:25c515e350e5b739842fc3228d662413ef28f295791af5e5110b543cf0b57d9b"}, + {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-manylinux_2_24_aarch64.whl", hash = "sha256:1707814f0d9791df063f8c19bb51b0d1278b8e9a2353abbb676c2f685dee6afe"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:46d378daaac94f454b3a0e3d8d78cafd78a026b1d71443f4966c696b48a6d899"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:09b055c05697b38ecacb7ac50bdab2240bfca1a0c4872b0fd309bb07dc9aa3a9"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-win32.whl", hash = "sha256:53a300ed9cea38cf5a2a9b069058137c2ca1ce658a874b79baceb8f892f915a7"}, {file = "ruamel.yaml.clib-0.2.8-cp311-cp311-win_amd64.whl", hash = "sha256:c2a72e9109ea74e511e29032f3b670835f8a59bbdc9ce692c5b4ed91ccf1eedb"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:ebc06178e8821efc9692ea7544aa5644217358490145629914d8020042c24aa1"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-macosx_13_0_arm64.whl", hash = "sha256:edaef1c1200c4b4cb914583150dcaa3bc30e592e907c01117c08b13a07255ec2"}, - {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux2014_aarch64.whl", hash = "sha256:7048c338b6c86627afb27faecf418768acb6331fc24cfa56c93e8c9780f815fa"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d176b57452ab5b7028ac47e7b3cf644bcfdc8cacfecf7e71759f7f51a59e5c92"}, + {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-manylinux_2_24_aarch64.whl", hash = "sha256:1dc67314e7e1086c9fdf2680b7b6c2be1c0d8e3a8279f2e993ca2a7545fecf62"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_i686.whl", hash = "sha256:3213ece08ea033eb159ac52ae052a4899b56ecc124bb80020d9bbceeb50258e9"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:aab7fd643f71d7946f2ee58cc88c9b7bfc97debd71dcc93e03e2d174628e7e2d"}, {file = "ruamel.yaml.clib-0.2.8-cp312-cp312-win32.whl", hash = "sha256:5c365d91c88390c8d0a8545df0b5857172824b1c604e867161e6b3d59a827eaa"}, @@ -945,7 +945,7 @@ files = [ {file = "ruamel.yaml.clib-0.2.8-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:a5aa27bad2bb83670b71683aae140a1f52b0857a2deff56ad3f6c13a017a26ed"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c58ecd827313af6864893e7af0a3bb85fd529f862b6adbefe14643947cfe2942"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-macosx_12_0_arm64.whl", hash = "sha256:f481f16baec5290e45aebdc2a5168ebc6d35189ae6fea7a58787613a25f6e875"}, - {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:3fcc54cb0c8b811ff66082de1680b4b14cf8a81dce0d4fbf665c2265a81e07a1"}, + {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux_2_24_aarch64.whl", hash = "sha256:77159f5d5b5c14f7c34073862a6b7d34944075d9f93e681638f6d753606c6ce6"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:7f67a1ee819dc4562d444bbafb135832b0b909f81cc90f7aa00260968c9ca1b3"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:4ecbf9c3e19f9562c7fdd462e8d18dd902a47ca046a2e64dba80699f0b6c09b7"}, {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:87ea5ff66d8064301a154b3933ae406b0863402a799b16e4a1d24d9fbbcbe0d3"}, @@ -953,7 +953,7 @@ files = [ {file = "ruamel.yaml.clib-0.2.8-cp37-cp37m-win_amd64.whl", hash = "sha256:3f215c5daf6a9d7bbed4a0a4f760f3113b10e82ff4c5c44bec20a68c8014f675"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:1b617618914cb00bf5c34d4357c37aa15183fa229b24767259657746c9077615"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-macosx_12_0_arm64.whl", hash = "sha256:a6a9ffd280b71ad062eae53ac1659ad86a17f59a0fdc7699fd9be40525153337"}, - {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:665f58bfd29b167039f714c6998178d27ccd83984084c286110ef26b230f259f"}, + {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux_2_24_aarch64.whl", hash = "sha256:305889baa4043a09e5b76f8e2a51d4ffba44259f6b4c72dec8ca56207d9c6fe1"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:700e4ebb569e59e16a976857c8798aee258dceac7c7d6b50cab63e080058df91"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:e2b4c44b60eadec492926a7270abb100ef9f72798e18743939bdbf037aab8c28"}, {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:e79e5db08739731b0ce4850bed599235d601701d5694c36570a99a0c5ca41a9d"}, @@ -961,7 +961,7 @@ files = [ {file = "ruamel.yaml.clib-0.2.8-cp38-cp38-win_amd64.whl", hash = "sha256:56f4252222c067b4ce51ae12cbac231bce32aee1d33fbfc9d17e5b8d6966c312"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:03d1162b6d1df1caa3a4bd27aa51ce17c9afc2046c31b0ad60a0a96ec22f8001"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-macosx_12_0_arm64.whl", hash = "sha256:bba64af9fa9cebe325a62fa398760f5c7206b215201b0ec825005f1b18b9bccf"}, - {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:9eb5dee2772b0f704ca2e45b1713e4e5198c18f515b52743576d196348f374d3"}, + {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux_2_24_aarch64.whl", hash = "sha256:a1a45e0bb052edf6a1d3a93baef85319733a888363938e1fc9924cb00c8df24c"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:da09ad1c359a728e112d60116f626cc9f29730ff3e0e7db72b9a2dbc2e4beed5"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:184565012b60405d93838167f425713180b949e9d8dd0bbc7b49f074407c5a8b"}, {file = "ruamel.yaml.clib-0.2.8-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a75879bacf2c987c003368cf14bed0ffe99e8e85acfa6c0bfffc21a090f16880"}, @@ -972,28 +972,28 @@ files = [ [[package]] name = "ruff" -version = "0.1.3" -description = "An extremely fast Python linter, written in Rust." +version = "0.1.6" +description = "An extremely fast Python linter and code formatter, written in Rust." optional = false python-versions = ">=3.7" files = [ - {file = "ruff-0.1.3-py3-none-macosx_10_7_x86_64.whl", hash = "sha256:b46d43d51f7061652eeadb426a9e3caa1e0002470229ab2fc19de8a7b0766901"}, - {file = "ruff-0.1.3-py3-none-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:b8afeb9abd26b4029c72adc9921b8363374f4e7edb78385ffaa80278313a15f9"}, - {file = "ruff-0.1.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca3cf365bf32e9ba7e6db3f48a4d3e2c446cd19ebee04f05338bc3910114528b"}, - {file = "ruff-0.1.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4874c165f96c14a00590dcc727a04dca0cfd110334c24b039458c06cf78a672e"}, - {file = "ruff-0.1.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:eec2dd31eed114e48ea42dbffc443e9b7221976554a504767ceaee3dd38edeb8"}, - {file = "ruff-0.1.3-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:dc3ec4edb3b73f21b4aa51337e16674c752f1d76a4a543af56d7d04e97769613"}, - {file = "ruff-0.1.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2e3de9ed2e39160800281848ff4670e1698037ca039bda7b9274f849258d26ce"}, - {file = "ruff-0.1.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1c595193881922cc0556a90f3af99b1c5681f0c552e7a2a189956141d8666fe8"}, - {file = "ruff-0.1.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0f75e670d529aa2288cd00fc0e9b9287603d95e1536d7a7e0cafe00f75e0dd9d"}, - {file = "ruff-0.1.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:76dd49f6cd945d82d9d4a9a6622c54a994689d8d7b22fa1322983389b4892e20"}, - {file = "ruff-0.1.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:918b454bc4f8874a616f0d725590277c42949431ceb303950e87fef7a7d94cb3"}, - {file = "ruff-0.1.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:d8859605e729cd5e53aa38275568dbbdb4fe882d2ea2714c5453b678dca83784"}, - {file = "ruff-0.1.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:0b6c55f5ef8d9dd05b230bb6ab80bc4381ecb60ae56db0330f660ea240cb0d4a"}, - {file = "ruff-0.1.3-py3-none-win32.whl", hash = "sha256:3e7afcbdcfbe3399c34e0f6370c30f6e529193c731b885316c5a09c9e4317eef"}, - {file = "ruff-0.1.3-py3-none-win_amd64.whl", hash = "sha256:7a18df6638cec4a5bd75350639b2bb2a2366e01222825562c7346674bdceb7ea"}, - {file = "ruff-0.1.3-py3-none-win_arm64.whl", hash = "sha256:12fd53696c83a194a2db7f9a46337ce06445fb9aa7d25ea6f293cf75b21aca9f"}, - {file = "ruff-0.1.3.tar.gz", hash = "sha256:3ba6145369a151401d5db79f0a47d50e470384d0d89d0d6f7fab0b589ad07c34"}, + {file = "ruff-0.1.6-py3-none-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:88b8cdf6abf98130991cbc9f6438f35f6e8d41a02622cc5ee130a02a0ed28703"}, + {file = "ruff-0.1.6-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:5c549ed437680b6105a1299d2cd30e4964211606eeb48a0ff7a93ef70b902248"}, + {file = "ruff-0.1.6-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1cf5f701062e294f2167e66d11b092bba7af6a057668ed618a9253e1e90cfd76"}, + {file = "ruff-0.1.6-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:05991ee20d4ac4bb78385360c684e4b417edd971030ab12a4fbd075ff535050e"}, + {file = "ruff-0.1.6-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:87455a0c1f739b3c069e2f4c43b66479a54dea0276dd5d4d67b091265f6fd1dc"}, + {file = "ruff-0.1.6-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:683aa5bdda5a48cb8266fcde8eea2a6af4e5700a392c56ea5fb5f0d4bfdc0240"}, + {file = "ruff-0.1.6-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:137852105586dcbf80c1717facb6781555c4e99f520c9c827bd414fac67ddfb6"}, + {file = "ruff-0.1.6-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bd98138a98d48a1c36c394fd6b84cd943ac92a08278aa8ac8c0fdefcf7138f35"}, + {file = "ruff-0.1.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3a0cd909d25f227ac5c36d4e7e681577275fb74ba3b11d288aff7ec47e3ae745"}, + {file = "ruff-0.1.6-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e8fd1c62a47aa88a02707b5dd20c5ff20d035d634aa74826b42a1da77861b5ff"}, + {file = "ruff-0.1.6-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:fd89b45d374935829134a082617954120d7a1470a9f0ec0e7f3ead983edc48cc"}, + {file = "ruff-0.1.6-py3-none-musllinux_1_2_i686.whl", hash = "sha256:491262006e92f825b145cd1e52948073c56560243b55fb3b4ecb142f6f0e9543"}, + {file = "ruff-0.1.6-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:ea284789861b8b5ca9d5443591a92a397ac183d4351882ab52f6296b4fdd5462"}, + {file = "ruff-0.1.6-py3-none-win32.whl", hash = "sha256:1610e14750826dfc207ccbcdd7331b6bd285607d4181df9c1c6ae26646d6848a"}, + {file = "ruff-0.1.6-py3-none-win_amd64.whl", hash = "sha256:4558b3e178145491e9bc3b2ee3c4b42f19d19384eaa5c59d10acf6e8f8b57e33"}, + {file = "ruff-0.1.6-py3-none-win_arm64.whl", hash = "sha256:03910e81df0d8db0e30050725a5802441c2022ea3ae4fe0609b76081731accbc"}, + {file = "ruff-0.1.6.tar.gz", hash = "sha256:1b09f29b16c6ead5ea6b097ef2764b42372aebe363722f1605ecbcd2b9207184"}, ] [[package]] @@ -1021,17 +1021,17 @@ gitlab = ["python-gitlab (>=1.3.0)"] [[package]] name = "setuptools" -version = "68.2.2" +version = "69.0.2" description = "Easily download, build, install, upgrade, and uninstall Python packages" optional = false python-versions = ">=3.8" files = [ - {file = "setuptools-68.2.2-py3-none-any.whl", hash = "sha256:b454a35605876da60632df1a60f736524eb73cc47bbc9f3f1ef1b644de74fd2a"}, - {file = "setuptools-68.2.2.tar.gz", hash = "sha256:4ac1475276d2f1c48684874089fefcd83bd7162ddaafb81fac866ba0db282a87"}, + {file = "setuptools-69.0.2-py3-none-any.whl", hash = "sha256:1e8fdff6797d3865f37397be788a4e3cba233608e9b509382a2777d25ebde7f2"}, + {file = "setuptools-69.0.2.tar.gz", hash = "sha256:735896e78a4742605974de002ac60562d286fa8051a7e2299445e8e8fbb01aa6"}, ] [package.extras] -docs = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-hoverxref (<2)", "sphinx-inline-tabs", "sphinx-lint", "sphinx-notfound-page (>=1,<2)", "sphinx-reredirects", "sphinxcontrib-towncrier"] +docs = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "rst.linker (>=1.9)", "sphinx (<7.2.5)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-inline-tabs", "sphinx-lint", "sphinx-notfound-page (>=1,<2)", "sphinx-reredirects", "sphinxcontrib-towncrier"] testing = ["build[virtualenv]", "filelock (>=3.4.0)", "flake8-2020", "ini2toml[lite] (>=0.9)", "jaraco.develop (>=7.21)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "pip (>=19.1)", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-mypy (>=0.9.1)", "pytest-perf", "pytest-ruff", "pytest-timeout", "pytest-xdist", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel"] testing-integration = ["build[virtualenv] (>=1.0.3)", "filelock (>=3.4.0)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.2.0)", "packaging (>=23.1)", "pytest", "pytest-enabler", "pytest-xdist", "tomli", "virtualenv (>=13.0.0)", "wheel"] @@ -1070,18 +1070,18 @@ files = [ [[package]] name = "taskipy" -version = "1.12.0" +version = "1.12.2" description = "tasks runner for python projects" optional = false python-versions = ">=3.6,<4.0" files = [ - {file = "taskipy-1.12.0-py3-none-any.whl", hash = "sha256:38306fbc952a7ca314b8f842a74b2fc38535cdab21031fe89e714a83e6259a84"}, - {file = "taskipy-1.12.0.tar.gz", hash = "sha256:e3dd7c53f7c9c4fd17dc908b1037f545afc452907eb0953b84e91c0a9a9d809d"}, + {file = "taskipy-1.12.2-py3-none-any.whl", hash = "sha256:ffdbb0bb0db54c0ec5c424610a3a087eea22706d4d1f6e3e8b4f12ebba05f98f"}, + {file = "taskipy-1.12.2.tar.gz", hash = "sha256:eadfdc20d6bb94d8018eda32f1dbf584cf4aa6cffb71ba5cc2de20d344f8c4fb"}, ] [package.dependencies] colorama = ">=0.4.4,<0.5.0" -mslex = {version = ">=0.3.0,<0.4.0", markers = "sys_platform == \"win32\""} +mslex = {version = ">=1.1.0,<2.0.0", markers = "sys_platform == \"win32\""} psutil = ">=5.7.2,<6.0.0" tomli = {version = ">=2.0.1,<3.0.0", markers = "python_version >= \"3.7\" and python_version < \"4.0\""} @@ -1163,18 +1163,17 @@ files = [ [[package]] name = "urllib3" -version = "2.0.7" +version = "2.1.0" description = "HTTP library with thread-safe connection pooling, file post, and more." optional = false -python-versions = ">=3.7" +python-versions = ">=3.8" files = [ - {file = "urllib3-2.0.7-py3-none-any.whl", hash = "sha256:fdb6d215c776278489906c2f8916e6e7d4f5a9b602ccbcfdf7f016fc8da0596e"}, - {file = "urllib3-2.0.7.tar.gz", hash = "sha256:c97dfde1f7bd43a71c8d2a58e369e9b2bf692d1334ea9f9cae55add7d0dd0f84"}, + {file = "urllib3-2.1.0-py3-none-any.whl", hash = "sha256:55901e917a5896a349ff771be919f8bd99aff50b79fe58fec595eb37bbc56bb3"}, + {file = "urllib3-2.1.0.tar.gz", hash = "sha256:df7aa8afb0148fa78488e7899b2c59b5f4ffcfa82e6c54ccb9dd37c1d7b52d54"}, ] [package.extras] brotli = ["brotli (>=1.0.9)", "brotlicffi (>=0.8.0)"] -secure = ["certifi", "cryptography (>=1.9)", "idna (>=2.0.0)", "pyopenssl (>=17.1.0)", "urllib3-secure-extra"] socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"] zstd = ["zstandard (>=0.18.0)"] diff --git a/tests/test_parser/test_openapi.py b/tests/test_parser/test_openapi.py index 4b82c7540..ebc9522bb 100644 --- a/tests/test_parser/test_openapi.py +++ b/tests/test_parser/test_openapi.py @@ -578,7 +578,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, ) From 8a8aba2deddfc478bc0c816e4dfc625dc2a31fb8 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 29 Dec 2023 12:26:37 -0700 Subject: [PATCH 08/30] Document removal of query param special case --- ...emoved_query_parameter_nullablerequired_special_case.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .changeset/removed_query_parameter_nullablerequired_special_case.md 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. From dd8f1913c7748fee632f9d08e910cbed1b34796b Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 29 Dec 2023 12:37:33 -0700 Subject: [PATCH 09/30] Document OpenAPI 3.1 support --- .changeset/openapi_31_support.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .changeset/openapi_31_support.md diff --git a/.changeset/openapi_31_support.md b/.changeset/openapi_31_support.md new file mode 100644 index 000000000..24d3df1f6 --- /dev/null +++ b/.changeset/openapi_31_support.md @@ -0,0 +1,13 @@ +--- +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). From 8f09b80697ef691723ce41efae9b376dfa32a228 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 29 Dec 2023 12:38:01 -0700 Subject: [PATCH 10/30] chore: regen --- end_to_end_tests/test-3-1-golden-record/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index 51d655e1d..2f9d177f0 100644 --- a/end_to_end_tests/test-3-1-golden-record/pyproject.toml +++ b/end_to_end_tests/test-3-1-golden-record/pyproject.toml @@ -13,7 +13,7 @@ include = ["CHANGELOG.md", "test_3_1_features_client/py.typed"] [tool.poetry.dependencies] python = "^3.8" -httpx = ">=0.20.0,<0.26.0" +httpx = ">=0.20.0,<0.27.0" attrs = ">=21.3.0" python-dateutil = "^2.8.0" From c5ed9a65cc74fef648507884e71527ef2739829d Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 29 Dec 2023 12:43:21 -0700 Subject: [PATCH 11/30] docs: Update README --- README.md | 27 +++++++++------------------ 1 file changed, 9 insertions(+), 18 deletions(-) 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 From b359b6e00225aa6ac0a3360a6a09a8c20c298e07 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 29 Dec 2023 13:45:08 -0700 Subject: [PATCH 12/30] Work on coverage improvements --- .../parser/properties/any.py | 14 ++--- .../parser/properties/boolean.py | 21 ++++--- .../parser/properties/const.py | 35 +++-------- .../parser/properties/date.py | 10 +-- .../parser/properties/datetime.py | 10 +-- .../parser/properties/enum_property.py | 10 +-- .../parser/properties/file.py | 23 ++++--- .../parser/properties/float.py | 18 ++++-- .../parser/properties/int.py | 14 +++-- .../parser/properties/list_property.py | 4 +- .../parser/properties/model_property.py | 6 +- .../parser/properties/none.py | 15 ++--- .../parser/properties/protocol.py | 4 +- .../parser/properties/string.py | 24 ++++++-- .../parser/properties/union.py | 6 +- tests/test_parser/test_properties/test_any.py | 12 ++++ .../test_properties/test_boolean.py | 54 ++++++++++++++++ .../test_parser/test_properties/test_const.py | 28 +++++++++ .../test_parser/test_properties/test_date.py | 33 ++++++++++ .../test_properties/test_datetime.py | 33 ++++++++++ .../test_properties/test_enum_property.py | 14 ++++- .../test_parser/test_properties/test_file.py | 15 +++++ .../test_parser/test_properties/test_float.py | 43 +++++++++++++ .../test_parser/test_properties/test_init.py | 61 +------------------ 24 files changed, 351 insertions(+), 156 deletions(-) create mode 100644 tests/test_parser/test_properties/test_any.py create mode 100644 tests/test_parser/test_properties/test_boolean.py create mode 100644 tests/test_parser/test_properties/test_const.py create mode 100644 tests/test_parser/test_properties/test_date.py create mode 100644 tests/test_parser/test_properties/test_datetime.py create mode 100644 tests/test_parser/test_properties/test_file.py create mode 100644 tests/test_parser/test_properties/test_float.py diff --git a/openapi_python_client/parser/properties/any.py b/openapi_python_client/parser/properties/any.py index e52339b17..fdeef93a1 100644 --- a/openapi_python_client/parser/properties/any.py +++ b/openapi_python_client/parser/properties/any.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import ClassVar +from typing import Any, ClassVar from attr import define @@ -17,7 +17,7 @@ def build( cls, name: str, required: bool, - default: str | None, + default: Any, python_name: PythonIdentifier, description: str | None, example: str | None, @@ -25,17 +25,17 @@ def build( return cls( name=name, required=required, - default=Value(default) if default is not None else None, + default=AnyProperty.convert_value(default), python_name=python_name, description=description, example=example, ) @classmethod - def convert_value(cls, value: str | Value | None) -> Value | None: - if isinstance(value, str): - return Value(value) - return value + 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 diff --git a/openapi_python_client/parser/properties/boolean.py b/openapi_python_client/parser/properties/boolean.py index dc1adcc15..e6bb883a8 100644 --- a/openapi_python_client/parser/properties/boolean.py +++ b/openapi_python_client/parser/properties/boolean.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import ClassVar +from typing import Any, ClassVar from attr import define @@ -36,7 +36,7 @@ def build( cls, name: str, required: bool, - default: str | None | Value, + default: Any, python_name: PythonIdentifier, description: str | None, example: str | None, @@ -54,11 +54,14 @@ def build( ) @classmethod - def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if isinstance(value, Value) or value is None: + return value if isinstance(value, str): - try: - bool(value) - except ValueError: - return PropertyError(f"Invalid boolean value: {value}") - return Value(value) - return value + 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 index 4babbf1d0..73fa55d07 100644 --- a/openapi_python_client/parser/properties/const.py +++ b/openapi_python_client/parser/properties/const.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import overload +from typing import Any from attr import define @@ -27,7 +27,7 @@ def build( cls, *, const: str | int, - default: str | int | None, + default: Any, name: str, python_name: PythonIdentifier, required: bool, @@ -63,36 +63,19 @@ def build( prop.default = converted_default return prop - def convert_value(self, value: str | Value | None | int) -> Value | None | PropertyError: - if value is None: - return None - value_or_error = self._convert_value(value) - if isinstance(value_or_error, PropertyError): - return value_or_error - if value_or_error != self.value: - return PropertyError(detail=f"Invalid value for const {self.name}; {value_or_error} != {self.value}") - return value_or_error + def convert_value(self, value: Any) -> Value | None | PropertyError: + value = self._convert_value(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: str | int) -> Value | PropertyError: - ... - - @staticmethod - @overload - def _convert_value(value: None) -> None: - ... - - @staticmethod - def _convert_value(value: str | int | Value | None) -> Value | None | PropertyError: - if value is None: - return None + def _convert_value(value: Any) -> Value: if isinstance(value, Value): return value if isinstance(value, str): return StringProperty.convert_value(value) - if isinstance(value, int): - return Value(repr(value)) + return Value(str(value)) def get_type_string( self, diff --git a/openapi_python_client/parser/properties/date.py b/openapi_python_client/parser/properties/date.py index 654d8d181..24e0c34fe 100644 --- a/openapi_python_client/parser/properties/date.py +++ b/openapi_python_client/parser/properties/date.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import ClassVar +from typing import Any, ClassVar from attr import define from dateutil.parser import isoparse @@ -30,7 +30,7 @@ def build( cls, name: str, required: bool, - default: str | Value | None, + default: Any, python_name: PythonIdentifier, description: str | None, example: str | None, @@ -49,14 +49,16 @@ def build( ) @classmethod - def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: + 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 value + return PropertyError(f"Cannot convert {value} to a date") def get_imports(self, *, prefix: str) -> set[str]: """ diff --git a/openapi_python_client/parser/properties/datetime.py b/openapi_python_client/parser/properties/datetime.py index 7ad35c37a..abb28ac22 100644 --- a/openapi_python_client/parser/properties/datetime.py +++ b/openapi_python_client/parser/properties/datetime.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import ClassVar +from typing import Any, ClassVar from attr import define from dateutil.parser import isoparse @@ -32,7 +32,7 @@ def build( cls, name: str, required: bool, - default: str | Value | None, + default: Any, python_name: PythonIdentifier, description: str | None, example: str | None, @@ -51,14 +51,16 @@ def build( ) @classmethod - def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: + 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 value + return PropertyError(f"Cannot convert {value} to a datetime") def get_imports(self, *, prefix: str) -> set[str]: """ diff --git a/openapi_python_client/parser/properties/enum_property.py b/openapi_python_client/parser/properties/enum_property.py index 26c07ec93..4348989ea 100644 --- a/openapi_python_client/parser/properties/enum_property.py +++ b/openapi_python_client/parser/properties/enum_property.py @@ -2,7 +2,7 @@ __all__ = ["EnumProperty"] -from typing import ClassVar, Union, cast +from typing import Any, ClassVar, Union, cast from attr import evolve from attrs import define @@ -144,14 +144,16 @@ def build( schemas = evolve(schemas, classes_by_name={**schemas.classes_by_name, class_info.name: prop}) return prop, schemas - def convert_value(self, value: str | Value | None) -> Value | PropertyError | None: - if isinstance(value, str): + 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 value + 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 diff --git a/openapi_python_client/parser/properties/file.py b/openapi_python_client/parser/properties/file.py index 9346d938f..505876b63 100644 --- a/openapi_python_client/parser/properties/file.py +++ b/openapi_python_client/parser/properties/file.py @@ -1,11 +1,12 @@ from __future__ import annotations -from typing import ClassVar +from typing import Any, ClassVar from attr import define from ...utils import PythonIdentifier -from .protocol import PropertyProtocol, Value +from ..errors import PropertyError +from .protocol import PropertyProtocol @define @@ -14,7 +15,7 @@ class FileProperty(PropertyProtocol): name: str required: bool - default: Value | None + default: None python_name: PythonIdentifier description: str | None example: str | None @@ -29,24 +30,28 @@ def build( cls, name: str, required: bool, - default: str | Value | None, + default: Any, python_name: PythonIdentifier, description: str | None, example: str | None, - ) -> FileProperty: + ) -> 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=cls.convert_value(default), + default=default_or_err, python_name=python_name, description=description, example=example, ) @classmethod - def convert_value(cls, value: str | Value | None) -> Value | None: - if isinstance(value, str): - return Value(value) + 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]: diff --git a/openapi_python_client/parser/properties/float.py b/openapi_python_client/parser/properties/float.py index e32efe345..d8f469c69 100644 --- a/openapi_python_client/parser/properties/float.py +++ b/openapi_python_client/parser/properties/float.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import ClassVar +from typing import Any, ClassVar from attr import define @@ -36,7 +36,7 @@ def build( cls, name: str, required: bool, - default: str | None | Value, + default: Any, python_name: PythonIdentifier, description: str | None, example: str | None, @@ -55,11 +55,17 @@ def build( ) @classmethod - def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if isinstance(value, Value) or value is None: + return value if isinstance(value, str): try: - float(value) + parsed = float(value) + return Value(str(parsed)) except ValueError: return PropertyError(f"Invalid float value: {value}") - return Value(value) - return 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 index a1578a12c..b75d6e3c1 100644 --- a/openapi_python_client/parser/properties/int.py +++ b/openapi_python_client/parser/properties/int.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import ClassVar +from typing import Any, ClassVar from attr import define @@ -36,7 +36,7 @@ def build( cls, name: str, required: bool, - default: str | None | Value, + default: Any, python_name: PythonIdentifier, description: str | None, example: str | None, @@ -55,11 +55,17 @@ def build( ) @classmethod - def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: + 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) - return value + if isinstance(value, int): + return Value(str(value)) + if isinstance(value, float): + return Value(str(int(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 index 0e373be05..ad46ca305 100644 --- a/openapi_python_client/parser/properties/list_property.py +++ b/openapi_python_client/parser/properties/list_property.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import ClassVar +from typing import Any, ClassVar from attr import define @@ -86,7 +86,7 @@ def build( schemas, ) - def convert_value(self, value: str | Value | None) -> Value | None | PropertyError: + def convert_value(self, value: Any) -> Value | None | PropertyError: return self.inner_property.convert_value(value) def get_base_type_string(self, *, quoted: bool = False) -> str: diff --git a/openapi_python_client/parser/properties/model_property.py b/openapi_python_client/parser/properties/model_property.py index e8f9e554b..70620b03c 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 @@ -38,7 +38,9 @@ class ModelProperty(PropertyProtocol): is_multipart_body: bool = False @classmethod - def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: + def convert_value(cls, value: Any) -> Value | None | PropertyError: + if value is not None: + return PropertyError(detail="ModelProperty cannot have a default value") return None def __attrs_post_init__(self) -> None: diff --git a/openapi_python_client/parser/properties/none.py b/openapi_python_client/parser/properties/none.py index a0ce4e93f..c329dac40 100644 --- a/openapi_python_client/parser/properties/none.py +++ b/openapi_python_client/parser/properties/none.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import ClassVar +from typing import Any, ClassVar from attr import define @@ -34,7 +34,7 @@ def build( cls, name: str, required: bool, - default: str | None, + default: Any, python_name: PythonIdentifier, description: str | None, example: str | None, @@ -52,9 +52,10 @@ def build( ) @classmethod - def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: + 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 PropertyError(f"Value {value} is not valid, only None is allowed") - return Value(value) - return value + 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/protocol.py b/openapi_python_client/parser/properties/protocol.py index cb2d7176b..b7ea7b6ff 100644 --- a/openapi_python_client/parser/properties/protocol.py +++ b/openapi_python_client/parser/properties/protocol.py @@ -3,7 +3,7 @@ __all__ = ["PropertyProtocol", "Value"] from abc import abstractmethod -from typing import TYPE_CHECKING, ClassVar, Protocol, TypeVar +from typing import TYPE_CHECKING, Any, ClassVar, Protocol, TypeVar from ... import Config from ... import schema as oai @@ -55,7 +55,7 @@ class PropertyProtocol(Protocol): json_is_dict: ClassVar[bool] = False @abstractmethod - def convert_value(self, value: str | Value | None) -> Value | None | PropertyError: + def convert_value(self, value: Any) -> Value | None | PropertyError: """Convert a string value to a Value object""" raise NotImplementedError() diff --git a/openapi_python_client/parser/properties/string.py b/openapi_python_client/parser/properties/string.py index 7099ca314..34fc22b2d 100644 --- a/openapi_python_client/parser/properties/string.py +++ b/openapi_python_client/parser/properties/string.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import ClassVar +from typing import Any, ClassVar, overload from attr import define @@ -37,7 +37,7 @@ def build( cls, name: str, required: bool, - default: str | None | Value, + default: Any, python_name: PythonIdentifier, description: str | None, example: str | None, @@ -57,7 +57,19 @@ def build( ) @classmethod - def convert_value(cls, value: str | Value | None) -> Value | None | PropertyError: - if isinstance(value, str): - return Value(repr(utils.remove_string_escapes(value))) - return value + @overload + def convert_value(cls, value: None) -> None: # type: ignore[misc] + ... + + @classmethod + @overload + def convert_value(cls, value: Any) -> Value: + ... + + @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 index 7a3c07a04..2d256a7b6 100644 --- a/openapi_python_client/parser/properties/union.py +++ b/openapi_python_client/parser/properties/union.py @@ -1,7 +1,7 @@ from __future__ import annotations from itertools import chain -from typing import ClassVar +from typing import Any, ClassVar from attr import define, evolve @@ -83,8 +83,8 @@ def build( prop = evolve(prop, default=default_or_error) return prop, schemas - def convert_value(self, value: str | Value | None) -> Value | None | PropertyError: - if value is None: + 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}" 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..2b40028ba --- /dev/null +++ b/tests/test_parser/test_properties/test_const.py @@ -0,0 +1,28 @@ +from openapi_python_client.parser.errors import PropertyError +from openapi_python_client.parser.properties import ConstProperty + + +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) 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 index 866a986c0..dc41a9f51 100644 --- a/tests/test_parser/test_properties/test_enum_property.py +++ b/tests/test_parser/test_properties/test_enum_property.py @@ -37,7 +37,7 @@ def test_no_values(): assert err == PropertyError(detail="No values provided for Enum", data=data) -def test_bad_default(): +def test_bad_default_value(): data = oai.Schema(default="B") schemas = Schemas() @@ -47,3 +47,15 @@ def test_bad_default(): 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 73388b2df..590b1173c 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 @@ -8,11 +7,7 @@ from openapi_python_client import Config from openapi_python_client.parser.errors import ParameterError, PropertyError from openapi_python_client.parser.properties import ( - BooleanProperty, - FloatProperty, - IntProperty, ListProperty, - Property, Schemas, StringProperty, UnionProperty, @@ -481,7 +476,7 @@ def test_property_from_data_int_enum(self, enum_property_factory): values={"VALUE_1": 1, "VALUE_2": 2, "VALUE_3": 3}, class_info=Class(name="ParentAnEnum", module_name="parent_an_enum"), value_type=int, - default=3, + default="ParentAnEnum.VALUE_3", ) assert schemas != new_schemas, "Provided Schemas was mutated" assert new_schemas.classes_by_name == { @@ -650,60 +645,6 @@ 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): - from openapi_python_client.parser.properties import Schemas, property_from_data - - name = "test_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), - python_name=name, - description=description, - example=example, - ) - assert new_schemas == schemas - - # Test nullable values - data.default = 0 - - 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), - 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): from openapi_python_client.parser.properties import Schemas, property_from_data From 7eab8dc7e2e6eef797060ab62ac05c054bac6976 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 29 Dec 2023 13:51:51 -0700 Subject: [PATCH 13/30] chore: regen --- .../get_parameter_references_path_param.py | 4 ++-- .../api/tests/defaults_tests_defaults_post.py | 8 ++++---- openapi_python_client/parser/properties/const.py | 6 +++++- 3 files changed, 11 insertions(+), 7 deletions(-) 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 b24e1990b..f3dcce94c 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 @@ -74,7 +74,7 @@ def sync_detailed( Args: path_param (str): string_param (Union[Unset, str]): - integer_param (Union[Unset, int]): + integer_param (Union[Unset, int]): Default: 0. header_param (Union[None, Unset, str]): cookie_param (Union[Unset, str]): @@ -115,7 +115,7 @@ async def asyncio_detailed( Args: path_param (str): string_param (Union[Unset, str]): - integer_param (Union[Unset, int]): + integer_param (Union[Unset, int]): Default: 0. header_param (Union[None, Unset, str]): cookie_param (Union[Unset, str]): 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/tests/defaults_tests_defaults_post.py index d0d26f74f..3a5e2b593 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/tests/defaults_tests_defaults_post.py @@ -138,7 +138,7 @@ def sync_detailed( 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, Unset, float]): Default: 0.6. @@ -197,7 +197,7 @@ def sync( 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, Unset, float]): Default: 0.6. @@ -251,7 +251,7 @@ async def asyncio_detailed( 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, Unset, float]): Default: 0.6. @@ -308,7 +308,7 @@ async def asyncio( 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, Unset, float]): Default: 0.6. diff --git a/openapi_python_client/parser/properties/const.py b/openapi_python_client/parser/properties/const.py index 73fa55d07..48458cbd0 100644 --- a/openapi_python_client/parser/properties/const.py +++ b/openapi_python_client/parser/properties/const.py @@ -65,12 +65,16 @@ def build( def convert_value(self, value: Any) -> Value | None | PropertyError: value = self._convert_value(value) + if value is None or isinstance(value, Value): + return value if value != self.value: return PropertyError(detail=f"Invalid value for const {self.name}; {value} != {self.value}") return value @staticmethod - def _convert_value(value: Any) -> Value: + def _convert_value(value: Any) -> Value | None: + if value is None or isinstance(value, Value): + return value if isinstance(value, Value): return value if isinstance(value, str): From ab5bf3a59925025bb1a3e5d884460c6734c86d83 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 29 Dec 2023 13:56:36 -0700 Subject: [PATCH 14/30] fix const null checking --- openapi_python_client/parser/properties/const.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/openapi_python_client/parser/properties/const.py b/openapi_python_client/parser/properties/const.py index 48458cbd0..e268c5864 100644 --- a/openapi_python_client/parser/properties/const.py +++ b/openapi_python_client/parser/properties/const.py @@ -45,8 +45,8 @@ def build( description: The description of this property, used for docstrings """ value = cls._convert_value(const) - if isinstance(value, PropertyError): - return value + if value is None: + return PropertyError("Invalid const value, cannot be null") prop = cls( value=value, @@ -64,8 +64,10 @@ def build( 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 or isinstance(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}") From 75816eec4449d4cdbf004c05bd53a574f2c2ab01 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 29 Dec 2023 14:19:43 -0700 Subject: [PATCH 15/30] Update CONTRIBUTING.md --- CONTRIBUTING.md | 53 +++++++++++++++++++++++++++---------------------- 1 file changed, 29 insertions(+), 24 deletions(-) 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/ From 8438150654646ec19bcd8d1f71023025709222f8 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Fri, 29 Dec 2023 14:48:10 -0700 Subject: [PATCH 16/30] Improve coverage --- .../parser/properties/const.py | 14 ++++++-- .../parser/properties/int.py | 4 +-- .../parser/properties/list_property.py | 2 +- .../test_parser/test_properties/test_const.py | 27 ++++++++++++++ tests/test_parser/test_properties/test_int.py | 35 +++++++++++++++++++ 5 files changed, 75 insertions(+), 7 deletions(-) create mode 100644 tests/test_parser/test_properties/test_int.py diff --git a/openapi_python_client/parser/properties/const.py b/openapi_python_client/parser/properties/const.py index e268c5864..a7097cbb1 100644 --- a/openapi_python_client/parser/properties/const.py +++ b/openapi_python_client/parser/properties/const.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any +from typing import Any, overload from attr import define @@ -45,8 +45,6 @@ def build( description: The description of this property, used for docstrings """ value = cls._convert_value(const) - if value is None: - return PropertyError("Invalid const value, cannot be null") prop = cls( value=value, @@ -73,6 +71,16 @@ def convert_value(self, value: Any) -> Value | None | PropertyError: 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] + ... + + @staticmethod + @overload + def _convert_value(value: Any) -> Value: + ... + @staticmethod def _convert_value(value: Any) -> Value | None: if value is None or isinstance(value, Value): diff --git a/openapi_python_client/parser/properties/int.py b/openapi_python_client/parser/properties/int.py index b75d6e3c1..ab7173d3d 100644 --- a/openapi_python_client/parser/properties/int.py +++ b/openapi_python_client/parser/properties/int.py @@ -64,8 +64,6 @@ def convert_value(cls, value: Any) -> Value | None | PropertyError: except ValueError: return PropertyError(f"Invalid int value: {value}") return Value(value) - if isinstance(value, int): + if isinstance(value, int) and not isinstance(value, bool): return Value(str(value)) - if isinstance(value, float): - return Value(str(int(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 index ad46ca305..7adc1f682 100644 --- a/openapi_python_client/parser/properties/list_property.py +++ b/openapi_python_client/parser/properties/list_property.py @@ -87,7 +87,7 @@ def build( ) def convert_value(self, value: Any) -> Value | None | PropertyError: - return self.inner_property.convert_value(value) + 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)}]" diff --git a/tests/test_parser/test_properties/test_const.py b/tests/test_parser/test_properties/test_const.py index 2b40028ba..6d2ad0bfe 100644 --- a/tests/test_parser/test_properties/test_const.py +++ b/tests/test_parser/test_properties/test_const.py @@ -1,5 +1,6 @@ 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(): @@ -26,3 +27,29 @@ def test_non_string_const(): ) 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_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) From b1e8ec2556f1273649707e0866f0527ccc69cc33 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sat, 30 Dec 2023 18:57:52 -0700 Subject: [PATCH 17/30] Improve coverage --- .../parser/properties/__init__.py | 4 +- .../parser/properties/const.py | 6 +- .../parser/properties/model_property.py | 165 +++++++++--------- .../parser/properties/protocol.py | 2 +- .../parser/properties/string.py | 6 +- .../test_parser/test_properties/test_init.py | 38 ---- .../test_properties/test_model_property.py | 30 ++-- .../test_parser/test_properties/test_none.py | 29 +++ 8 files changed, 136 insertions(+), 144 deletions(-) create mode 100644 tests/test_parser/test_properties/test_none.py diff --git a/openapi_python_client/parser/properties/__init__.py b/openapi_python_client/parser/properties/__init__.py index 42a60653c..7d3cc1c21 100644 --- a/openapi_python_client/parser/properties/__init__.py +++ b/openapi_python_client/parser/properties/__init__.py @@ -30,7 +30,7 @@ from .float import FloatProperty from .int import IntProperty from .list_property import ListProperty -from .model_property import ModelProperty, build_model_property, process_model +from .model_property import ModelProperty, process_model from .none import NoneProperty from .property import Property from .schemas import ( @@ -259,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, diff --git a/openapi_python_client/parser/properties/const.py b/openapi_python_client/parser/properties/const.py index a7097cbb1..249808a8a 100644 --- a/openapi_python_client/parser/properties/const.py +++ b/openapi_python_client/parser/properties/const.py @@ -74,19 +74,19 @@ def convert_value(self, value: Any) -> Value | None | PropertyError: @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 + return value # pragma: no cover if isinstance(value, str): return StringProperty.convert_value(value) return Value(str(value)) diff --git a/openapi_python_client/parser/properties/model_property.py b/openapi_python_client/parser/properties/model_property.py index 70620b03c..76c55a97c 100644 --- a/openapi_python_client/parser/properties/model_property.py +++ b/openapi_python_client/parser/properties/model_property.py @@ -37,10 +37,93 @@ class ModelProperty(PropertyProtocol): 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") + return PropertyError(detail="ModelProperty cannot have a default value") # pragma: no cover return None def __attrs_post_init__(self) -> None: @@ -374,83 +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, - 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/protocol.py b/openapi_python_client/parser/properties/protocol.py index b7ea7b6ff..c7907da98 100644 --- a/openapi_python_client/parser/properties/protocol.py +++ b/openapi_python_client/parser/properties/protocol.py @@ -57,7 +57,7 @@ class PropertyProtocol(Protocol): @abstractmethod def convert_value(self, value: Any) -> Value | None | PropertyError: """Convert a string value to a Value object""" - raise NotImplementedError() + 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""" diff --git a/openapi_python_client/parser/properties/string.py b/openapi_python_client/parser/properties/string.py index 34fc22b2d..9a1603f01 100644 --- a/openapi_python_client/parser/properties/string.py +++ b/openapi_python_client/parser/properties/string.py @@ -44,8 +44,6 @@ def build( pattern: str | None = None, ) -> StringProperty | PropertyError: checked_default = cls.convert_value(default) - if isinstance(checked_default, PropertyError): - return checked_default return cls( name=name, required=required, @@ -59,12 +57,12 @@ def build( @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: diff --git a/tests/test_parser/test_properties/test_init.py b/tests/test_parser/test_properties/test_init.py index 590b1173c..50f3559e0 100644 --- a/tests/test_parser/test_properties/test_init.py +++ b/tests/test_parser/test_properties/test_init.py @@ -669,44 +669,6 @@ def test_property_from_data_array(self): assert isinstance(response, ListProperty) assert isinstance(response.inner_property, StringProperty) - def test_property_from_data_object(self, mocker): - from openapi_python_client.parser.properties import Schemas, property_from_data - - name = mocker.MagicMock() - required = mocker.MagicMock() - data = oai.Schema( - type="object", - ) - 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 - - response = property_from_data( - name=name, - required=required, - data=data, - schemas=schemas, - parent_name="parent", - config=config, - process_properties=process_properties, - roots=roots, - ) - - 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, - ) - def test_property_from_data_union(self): from openapi_python_client.parser.properties import Schemas, property_from_data diff --git a/tests/test_parser/test_properties/test_model_property.py b/tests/test_parser/test_properties/test_model_property.py index cddc3c87f..f92a94de3 100644 --- a/tests/test_parser/test_properties/test_model_property.py +++ b/tests/test_parser/test_properties/test_model_property.py @@ -66,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", [ @@ -88,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(), @@ -108,7 +108,7 @@ 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" required = True @@ -126,7 +126,7 @@ def test_happy_path(self, model_property_factory, string_property_factory, date_ 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, @@ -167,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, @@ -208,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(), @@ -227,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(), @@ -247,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", @@ -256,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(), @@ -269,7 +269,7 @@ 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" required = True @@ -287,7 +287,7 @@ def test_process_properties_false(self, model_property_factory): 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, 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) From f56a3edcc8a1300183a700b226f5492ef02d850c Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sat, 30 Dec 2023 19:13:05 -0700 Subject: [PATCH 18/30] Improve coverage --- end_to_end_tests/baseline_openapi_3.0.json | 10 ++++++++++ end_to_end_tests/baseline_openapi_3.1.yaml | 10 ++++++++++ .../api/tests/defaults_tests_defaults_post.py | 15 +++++++++++++++ tests/test_parser/test_properties/test_union.py | 17 +++++++++++++++++ 4 files changed, 52 insertions(+) diff --git a/end_to_end_tests/baseline_openapi_3.0.json b/end_to_end_tests/baseline_openapi_3.0.json index f29460f38..9fc2b969f 100644 --- a/end_to_end_tests/baseline_openapi_3.0.json +++ b/end_to_end_tests/baseline_openapi_3.0.json @@ -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": { diff --git a/end_to_end_tests/baseline_openapi_3.1.yaml b/end_to_end_tests/baseline_openapi_3.1.yaml index ac0908f5d..53007d656 100644 --- a/end_to_end_tests/baseline_openapi_3.1.yaml +++ b/end_to_end_tests/baseline_openapi_3.1.yaml @@ -465,6 +465,16 @@ info: "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": { 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/tests/defaults_tests_defaults_post.py index 3a5e2b593..b69596372 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/tests/defaults_tests_defaults_post.py @@ -16,6 +16,7 @@ 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, @@ -30,6 +31,8 @@ def _get_kwargs( 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 @@ -120,6 +123,7 @@ 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, @@ -135,6 +139,7 @@ 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. @@ -156,6 +161,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, @@ -179,6 +185,7 @@ 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, @@ -194,6 +201,7 @@ 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. @@ -216,6 +224,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, @@ -233,6 +242,7 @@ 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, @@ -248,6 +258,7 @@ 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. @@ -269,6 +280,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, @@ -290,6 +302,7 @@ 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, @@ -305,6 +318,7 @@ 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. @@ -328,6 +342,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/tests/test_parser/test_properties/test_union.py b/tests/test_parser/test_properties/test_union.py index 3ea1ed59d..9cd7726ab 100644 --- a/tests/test_parser/test_properties/test_union.py +++ b/tests/test_parser/test_properties/test_union.py @@ -43,3 +43,20 @@ def test_build_union_property_invalid_property(): 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) From 805ada460d5e2a23489ba035d0b16913fc38d06a Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sat, 30 Dec 2023 19:20:22 -0700 Subject: [PATCH 19/30] Reformat --- tests/test_parser/test_properties/test_union.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_parser/test_properties/test_union.py b/tests/test_parser/test_properties/test_union.py index 9cd7726ab..d6c0a3bb5 100644 --- a/tests/test_parser/test_properties/test_union.py +++ b/tests/test_parser/test_properties/test_union.py @@ -44,6 +44,7 @@ def test_build_union_property_invalid_property(): ) assert p == PropertyError(detail=f"Invalid property in union {name}", data=reference) + def test_invalid_default(): data = oai.Schema( type=[DataType.NUMBER, DataType.INTEGER], From e6efc74085041057f42a1750c6aa80e0d9e3bff9 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sat, 30 Dec 2023 19:28:42 -0700 Subject: [PATCH 20/30] fix: type list union defaults --- end_to_end_tests/baseline_openapi_3.0.json | 4 +- end_to_end_tests/baseline_openapi_3.1.yaml | 14 +- .../my_test_api_client/api/__init__.py | 5 + .../api/defaults/__init__.py | 14 + .../my_test_api_client/api/tests/__init__.py | 8 - .../api/tests/defaults_tests_defaults_post.py | 357 ------------------ .../parser/properties/union.py | 2 +- 7 files changed, 27 insertions(+), 377 deletions(-) create mode 100644 end_to_end_tests/custom-templates-golden-record/my_test_api_client/api/defaults/__init__.py delete mode 100644 end_to_end_tests/golden-record/my_test_api_client/api/tests/defaults_tests_defaults_post.py diff --git a/end_to_end_tests/baseline_openapi_3.0.json b/end_to_end_tests/baseline_openapi_3.0.json index 9fc2b969f..14493030f 100644 --- a/end_to_end_tests/baseline_openapi_3.0.json +++ b/end_to_end_tests/baseline_openapi_3.0.json @@ -449,10 +449,10 @@ } } }, - "/tests/defaults": { + "/defaults": { "post": { "tags": [ - "tests" + "defaults" ], "summary": "Defaults", "operationId": "defaults_tests_defaults_post", diff --git a/end_to_end_tests/baseline_openapi_3.1.yaml b/end_to_end_tests/baseline_openapi_3.1.yaml index 53007d656..2d1c1f9ac 100644 --- a/end_to_end_tests/baseline_openapi_3.1.yaml +++ b/end_to_end_tests/baseline_openapi_3.1.yaml @@ -447,10 +447,10 @@ info: } } }, - "/tests/defaults": { + "/defaults": { "post": { "tags": [ - "tests" + "defaults" ], "summary": "Defaults", "operationId": "defaults_tests_defaults_post", @@ -536,13 +536,9 @@ info: "required": true, "schema": { "title": "Union Prop", - "anyOf": [ - { - "type": "number" - }, - { - "type": "string" - } + "type": [ + "number", + "string" ], "default": "not a float" }, 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/tests/defaults_tests_defaults_post.py b/end_to_end_tests/golden-record/my_test_api_client/api/tests/defaults_tests_defaults_post.py deleted file mode 100644 index b69596372..000000000 --- a/end_to_end_tests/golden-record/my_test_api_client/api/tests/defaults_tests_defaults_post.py +++ /dev/null @@ -1,357 +0,0 @@ -import datetime -from http import HTTPStatus -from typing import Any, Dict, List, Optional, Union - -import httpx -from dateutil.parser import isoparse - -from ... import errors -from ...client import AuthenticatedClient, Client -from ...models.an_enum import AnEnum -from ...models.http_validation_error import HTTPValidationError -from ...models.model_with_union_property import ModelWithUnionProperty -from ...types import UNSET, Response, Unset - - -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, 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 - - params["float_prop"] = float_prop - - params["int_prop"] = int_prop - - params["boolean_prop"] = boolean_prop - - 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[Unset, float, str] - if isinstance(union_prop_with_ref, Unset): - json_union_prop_with_ref = UNSET - - elif isinstance(union_prop_with_ref, AnEnum): - json_union_prop_with_ref = UNSET - if not isinstance(union_prop_with_ref, Unset): - json_union_prop_with_ref = union_prop_with_ref.value - - 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", - "params": params, - } - - -def _parse_response( - *, client: Union[AuthenticatedClient, Client], response: httpx.Response -) -> Optional[Union[Any, HTTPValidationError]]: - if response.status_code == HTTPStatus.OK: - response_200 = response.json() - return response_200 - if response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY: - response_422 = HTTPValidationError.from_dict(response.json()) - - return response_422 - 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[Union[Any, HTTPValidationError]]: - return Response( - status_code=HTTPStatus(response.status_code), - content=response.content, - headers=response.headers, - parsed=_parse_response(client=client, response=response), - ) - - -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, Unset, float] = 0.6, - enum_prop: AnEnum, - model_prop: "ModelWithUnionProperty", - required_model_prop: "ModelWithUnionProperty", -) -> Response[Union[Any, HTTPValidationError]]: - """Defaults - - 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): Default: False. - list_prop (List[AnEnum]): - union_prop (Union[float, str]): Default: 'not a float'. - 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): - - 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[Union[Any, HTTPValidationError]] - """ - - 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, - boolean_prop=boolean_prop, - list_prop=list_prop, - union_prop=union_prop, - union_prop_with_ref=union_prop_with_ref, - enum_prop=enum_prop, - model_prop=model_prop, - required_model_prop=required_model_prop, - ) - - response = client.get_httpx_client().request( - **kwargs, - ) - - return _build_response(client=client, response=response) - - -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, Unset, float] = 0.6, - enum_prop: AnEnum, - model_prop: "ModelWithUnionProperty", - required_model_prop: "ModelWithUnionProperty", -) -> Optional[Union[Any, HTTPValidationError]]: - """Defaults - - 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): Default: False. - list_prop (List[AnEnum]): - union_prop (Union[float, str]): Default: 'not a float'. - 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): - - 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: - Union[Any, HTTPValidationError] - """ - - 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, - boolean_prop=boolean_prop, - list_prop=list_prop, - union_prop=union_prop, - union_prop_with_ref=union_prop_with_ref, - enum_prop=enum_prop, - model_prop=model_prop, - required_model_prop=required_model_prop, - ).parsed - - -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, Unset, float] = 0.6, - enum_prop: AnEnum, - model_prop: "ModelWithUnionProperty", - required_model_prop: "ModelWithUnionProperty", -) -> Response[Union[Any, HTTPValidationError]]: - """Defaults - - 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): Default: False. - list_prop (List[AnEnum]): - union_prop (Union[float, str]): Default: 'not a float'. - 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): - - 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[Union[Any, HTTPValidationError]] - """ - - 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, - boolean_prop=boolean_prop, - list_prop=list_prop, - union_prop=union_prop, - union_prop_with_ref=union_prop_with_ref, - enum_prop=enum_prop, - model_prop=model_prop, - required_model_prop=required_model_prop, - ) - - response = await client.get_async_httpx_client().request(**kwargs) - - return _build_response(client=client, response=response) - - -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, Unset, float] = 0.6, - enum_prop: AnEnum, - model_prop: "ModelWithUnionProperty", - required_model_prop: "ModelWithUnionProperty", -) -> Optional[Union[Any, HTTPValidationError]]: - """Defaults - - 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): Default: False. - list_prop (List[AnEnum]): - union_prop (Union[float, str]): Default: 'not a float'. - 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): - - 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: - Union[Any, HTTPValidationError] - """ - - return ( - 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, - boolean_prop=boolean_prop, - list_prop=list_prop, - union_prop=union_prop, - union_prop_with_ref=union_prop_with_ref, - enum_prop=enum_prop, - model_prop=model_prop, - required_model_prop=required_model_prop, - ) - ).parsed diff --git a/openapi_python_client/parser/properties/union.py b/openapi_python_client/parser/properties/union.py index 2d256a7b6..c68c0e8cd 100644 --- a/openapi_python_client/parser/properties/union.py +++ b/openapi_python_client/parser/properties/union.py @@ -52,7 +52,7 @@ def build( type_list_data = [] if isinstance(data.type, list): for _type in data.type: - type_list_data.append(data.model_copy(update={"type": _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( From 2e84f3ba40f983333dde12a61faf0f5e35dcc7c1 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sat, 30 Dec 2023 19:29:01 -0700 Subject: [PATCH 21/30] fix: type list union defaults --- .../api/defaults/__init__.py | 0 .../defaults/defaults_tests_defaults_post.py | 357 ++++++++++++++++++ 2 files changed, 357 insertions(+) create mode 100644 end_to_end_tests/golden-record/my_test_api_client/api/defaults/__init__.py create mode 100644 end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py 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/defaults/defaults_tests_defaults_post.py b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py new file mode 100644 index 000000000..e191ef410 --- /dev/null +++ b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py @@ -0,0 +1,357 @@ +import datetime +from http import HTTPStatus +from typing import Any, Dict, List, Optional, Union + +import httpx +from dateutil.parser import isoparse + +from ... import errors +from ...client import AuthenticatedClient, Client +from ...models.an_enum import AnEnum +from ...models.http_validation_error import HTTPValidationError +from ...models.model_with_union_property import ModelWithUnionProperty +from ...types import UNSET, Response, Unset + + +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, 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 + + params["float_prop"] = float_prop + + params["int_prop"] = int_prop + + params["boolean_prop"] = boolean_prop + + 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[Unset, float, str] + if isinstance(union_prop_with_ref, Unset): + json_union_prop_with_ref = UNSET + + elif isinstance(union_prop_with_ref, AnEnum): + json_union_prop_with_ref = UNSET + if not isinstance(union_prop_with_ref, Unset): + json_union_prop_with_ref = union_prop_with_ref.value + + 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": "/defaults", + "params": params, + } + + +def _parse_response( + *, client: Union[AuthenticatedClient, Client], response: httpx.Response +) -> Optional[Union[Any, HTTPValidationError]]: + if response.status_code == HTTPStatus.OK: + response_200 = response.json() + return response_200 + if response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY: + response_422 = HTTPValidationError.from_dict(response.json()) + + return response_422 + 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[Union[Any, HTTPValidationError]]: + return Response( + status_code=HTTPStatus(response.status_code), + content=response.content, + headers=response.headers, + parsed=_parse_response(client=client, response=response), + ) + + +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, Unset, float] = 0.6, + enum_prop: AnEnum, + model_prop: "ModelWithUnionProperty", + required_model_prop: "ModelWithUnionProperty", +) -> Response[Union[Any, HTTPValidationError]]: + """Defaults + + 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): Default: False. + list_prop (List[AnEnum]): + union_prop (Union[float, str]): Default: 'not a float'. + 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): + + 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[Union[Any, HTTPValidationError]] + """ + + 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, + boolean_prop=boolean_prop, + list_prop=list_prop, + union_prop=union_prop, + union_prop_with_ref=union_prop_with_ref, + enum_prop=enum_prop, + model_prop=model_prop, + required_model_prop=required_model_prop, + ) + + response = client.get_httpx_client().request( + **kwargs, + ) + + return _build_response(client=client, response=response) + + +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, Unset, float] = 0.6, + enum_prop: AnEnum, + model_prop: "ModelWithUnionProperty", + required_model_prop: "ModelWithUnionProperty", +) -> Optional[Union[Any, HTTPValidationError]]: + """Defaults + + 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): Default: False. + list_prop (List[AnEnum]): + union_prop (Union[float, str]): Default: 'not a float'. + 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): + + 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: + Union[Any, HTTPValidationError] + """ + + 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, + boolean_prop=boolean_prop, + list_prop=list_prop, + union_prop=union_prop, + union_prop_with_ref=union_prop_with_ref, + enum_prop=enum_prop, + model_prop=model_prop, + required_model_prop=required_model_prop, + ).parsed + + +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, Unset, float] = 0.6, + enum_prop: AnEnum, + model_prop: "ModelWithUnionProperty", + required_model_prop: "ModelWithUnionProperty", +) -> Response[Union[Any, HTTPValidationError]]: + """Defaults + + 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): Default: False. + list_prop (List[AnEnum]): + union_prop (Union[float, str]): Default: 'not a float'. + 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): + + 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[Union[Any, HTTPValidationError]] + """ + + 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, + boolean_prop=boolean_prop, + list_prop=list_prop, + union_prop=union_prop, + union_prop_with_ref=union_prop_with_ref, + enum_prop=enum_prop, + model_prop=model_prop, + required_model_prop=required_model_prop, + ) + + response = await client.get_async_httpx_client().request(**kwargs) + + return _build_response(client=client, response=response) + + +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, Unset, float] = 0.6, + enum_prop: AnEnum, + model_prop: "ModelWithUnionProperty", + required_model_prop: "ModelWithUnionProperty", +) -> Optional[Union[Any, HTTPValidationError]]: + """Defaults + + 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): Default: False. + list_prop (List[AnEnum]): + union_prop (Union[float, str]): Default: 'not a float'. + 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): + + 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: + Union[Any, HTTPValidationError] + """ + + return ( + 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, + boolean_prop=boolean_prop, + list_prop=list_prop, + union_prop=union_prop, + union_prop_with_ref=union_prop_with_ref, + enum_prop=enum_prop, + model_prop=model_prop, + required_model_prop=required_model_prop, + ) + ).parsed From 4d2636ccb30cd845fad6a365ff154e6673eb4ba0 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sat, 30 Dec 2023 19:39:38 -0700 Subject: [PATCH 22/30] Mor coverage --- .../test_parser/test_properties/test_union.py | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/tests/test_parser/test_properties/test_union.py b/tests/test_parser/test_properties/test_union.py index d6c0a3bb5..50b1f68fa 100644 --- a/tests/test_parser/test_properties/test_union.py +++ b/tests/test_parser/test_properties/test_union.py @@ -1,8 +1,8 @@ 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.errors import ParseError, PropertyError from openapi_python_client.parser.properties import Schemas, UnionProperty -from openapi_python_client.schema import DataType +from openapi_python_client.schema import DataType, ParameterLocation def test_property_from_data_union(union_property_factory, date_time_property_factory, string_property_factory): @@ -61,3 +61,39 @@ def test_invalid_default(): ) 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( + type=[DataType.NUMBER, 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) From 6342244662af7fc141fbaedec6ef3d5d0eb89c3f Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sat, 30 Dec 2023 19:46:06 -0700 Subject: [PATCH 23/30] More coverage --- openapi_python_client/parser/properties/union.py | 2 -- tests/test_parser/test_properties/test_union.py | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/openapi_python_client/parser/properties/union.py b/openapi_python_client/parser/properties/union.py index c68c0e8cd..a18ad24d2 100644 --- a/openapi_python_client/parser/properties/union.py +++ b/openapi_python_client/parser/properties/union.py @@ -175,6 +175,4 @@ def validate_location(self, location: oai.ParameterLocation) -> ParseError | Non 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}") - if location == oai.ParameterLocation.PATH and not self.required: - return ParseError(detail="Path parameter must be required") return None diff --git a/tests/test_parser/test_properties/test_union.py b/tests/test_parser/test_properties/test_union.py index 50b1f68fa..621921f0c 100644 --- a/tests/test_parser/test_properties/test_union.py +++ b/tests/test_parser/test_properties/test_union.py @@ -83,7 +83,7 @@ def test_invalid_location(): def test_not_required_in_path(): data = oai.Schema( - type=[DataType.NUMBER, DataType.INTEGER], + oneOf=[oai.Schema(type=DataType.NUMBER), oai.Schema(type=DataType.INTEGER)], ) prop, _ = UnionProperty.build( From a897c779e24921a6c1f77542cc95cda41a0c90b5 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sun, 31 Dec 2023 14:50:19 -0700 Subject: [PATCH 24/30] Mention people who helped in release notes --- .changeset/openapi_31_support.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.changeset/openapi_31_support.md b/.changeset/openapi_31_support.md index 24d3df1f6..cf890d64b 100644 --- a/.changeset/openapi_31_support.md +++ b/.changeset/openapi_31_support.md @@ -11,3 +11,12 @@ The generator will now attempt to generate code for OpenAPI documents with versi - `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 From 85b737bc80f3c05fbcde260ead5a05c1fa8b5184 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sun, 31 Dec 2023 15:04:33 -0700 Subject: [PATCH 25/30] Clean up some extra blank lines --- .../api/defaults/defaults_tests_defaults_post.py | 2 -- .../my_test_api_client/api/tests/get_user_list.py | 2 -- .../api/tests/int_enum_tests_int_enum_post.py | 1 - .../golden-record/my_test_api_client/models/a_model.py | 3 --- .../a_model_with_properties_reference_that_are_not_object.py | 3 --- .../models/model_with_additional_properties_refed.py | 1 - .../templates/property_templates/enum_property.py.jinja | 2 +- 7 files changed, 1 insertion(+), 13 deletions(-) diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py index e191ef410..06a108f41 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py @@ -46,7 +46,6 @@ 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 @@ -72,7 +71,6 @@ def _get_kwargs( 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() 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 348b8a970..50ac038f6 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 @@ -24,7 +24,6 @@ def _get_kwargs( 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 @@ -35,7 +34,6 @@ def _get_kwargs( 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 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..d74b487ad 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 @@ -16,7 +16,6 @@ def _get_kwargs( ) -> Dict[str, Any]: params: Dict[str, Any] = {} 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/models/a_model.py b/end_to_end_tests/golden-record/my_test_api_client/models/a_model.py index b1f1db2be..7a655ea6e 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 @@ -76,9 +76,7 @@ def to_dict(self) -> Dict[str, Any]: from ..models.model_with_union_property import ModelWithUnionProperty an_enum_value = self.an_enum_value.value - 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): @@ -146,7 +144,6 @@ 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) 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 e14556f9a..da7aabf9c 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 @@ -126,7 +125,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 @@ -160,7 +158,6 @@ def to_dict(self) -> Dict[str, Any]: bytestream_properties = self.bytestream_properties enum_property_ref = self.enum_property_ref.value - str_property_ref = self.str_property_ref date_property_ref = self.date_property_ref.isoformat() 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/openapi_python_client/templates/property_templates/enum_property.py.jinja b/openapi_python_client/templates/property_templates/enum_property.py.jinja index 1c9c02927..08744ee90 100644 --- a/openapi_python_client/templates/property_templates/enum_property.py.jinja +++ b/openapi_python_client/templates/property_templates/enum_property.py.jinja @@ -19,7 +19,7 @@ {% endif %} {% if property.required %} {{ destination }} = {{ transformed }} -{% else %} +{%- else %} {{ destination }}{% if declare_type %}: {{ type_string }}{% endif %} = UNSET if not isinstance({{ source }}, Unset): {{ destination }} = {{ transformed }} From 8f894e8e341ec4b5117dd9ce775b96c6a7cf08d7 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sun, 31 Dec 2023 15:11:04 -0700 Subject: [PATCH 26/30] Clean up some extra blank lines --- .../api/defaults/defaults_tests_defaults_post.py | 1 - .../my_test_api_client/api/tests/get_user_list.py | 1 - .../golden-record/my_test_api_client/models/a_model.py | 2 -- .../a_model_with_properties_reference_that_are_not_object.py | 3 --- .../templates/property_templates/date_property.py.jinja | 2 +- 5 files changed, 1 insertion(+), 8 deletions(-) diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py index 06a108f41..96e86cb53 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py @@ -34,7 +34,6 @@ def _get_kwargs( params["string with num"] = string_with_num json_date_prop = date_prop.isoformat() - params["date_prop"] = json_date_prop params["float_prop"] = float_prop 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 50ac038f6..c06b22eed 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 @@ -49,7 +49,6 @@ def _get_kwargs( if isinstance(some_date, datetime.date): json_some_date = some_date.isoformat() - else: json_some_date = some_date.isoformat() 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 7a655ea6e..84652bbea 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 @@ -86,12 +86,10 @@ def to_dict(self) -> Dict[str, Any]: 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 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 da7aabf9c..5b3025fb2 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 @@ -93,7 +93,6 @@ def to_dict(self) -> Dict[str, Any]: componentsschemas_an_other_array_of_date_item = ( componentsschemas_an_other_array_of_date_item_data.isoformat() ) - date_properties_ref.append(componentsschemas_an_other_array_of_date_item) datetime_properties_ref = [] @@ -132,7 +131,6 @@ def to_dict(self) -> Dict[str, Any]: date_properties = [] for componentsschemas_an_array_of_date_item_data in self.date_properties: componentsschemas_an_array_of_date_item = componentsschemas_an_array_of_date_item_data.isoformat() - date_properties.append(componentsschemas_an_array_of_date_item) datetime_properties = [] @@ -160,7 +158,6 @@ 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 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 517b83b87..d351f8b1e 100644 --- a/openapi_python_client/templates/property_templates/date_property.py.jinja +++ b/openapi_python_client/templates/property_templates/date_property.py.jinja @@ -17,7 +17,7 @@ isoparse({{ source }}).date() {% endif %} {% if property.required %} {{ destination }} = {{ transformed }} -{% 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 %} From a8a6749b54f199effeb615a490092eced2fe4e47 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sun, 31 Dec 2023 15:32:18 -0700 Subject: [PATCH 27/30] Clean up some extra blank lines --- .../defaults/defaults_tests_defaults_post.py | 4 --- .../get_location_query_optionality.py | 4 --- .../api/tests/get_user_list.py | 2 -- .../my_test_api_client/models/a_model.py | 22 ------------- ...roperties_reference_that_are_not_object.py | 3 -- ...h_a_circular_ref_in_items_object_a_item.py | 1 - ...ems_object_additional_properties_a_item.py | 1 - ...ems_object_additional_properties_b_item.py | 1 - ...h_a_circular_ref_in_items_object_b_item.py | 1 - ...items_object_additional_properties_item.py | 1 - ...th_a_recursive_ref_in_items_object_item.py | 1 - .../body_upload_file_tests_upload_post.py | 10 ------ .../models/http_validation_error.py | 1 - ...odel_with_additional_properties_inlined.py | 1 - .../models/model_with_any_json_properties.py | 1 - ...circular_ref_in_additional_properties_a.py | 1 - ...circular_ref_in_additional_properties_b.py | 1 - ...ive_additional_properties_a_date_holder.py | 1 - ..._recursive_ref_in_additional_properties.py | 1 - .../models/model_with_union_property.py | 1 - .../model_with_union_property_inlined.py | 2 -- ...ions_simple_before_complex_response_200.py | 2 -- .../models/post_const_path_json_body.py | 1 - .../integration_tests/models/public_error.py | 1 - .../datetime_property.py.jinja | 2 +- .../model_property.py.jinja | 4 +-- .../union_property.py.jinja | 1 - .../test_date_property/required_not_null.py | 1 - .../datetime_property_template.py | 8 +++++ .../required_not_null.py | 9 +++++ .../test_datetime_property.py | 33 +++++++++++++++++++ 31 files changed, 53 insertions(+), 70 deletions(-) create mode 100644 tests/test_templates/test_property_templates/test_datetime_property/datetime_property_template.py create mode 100644 tests/test_templates/test_property_templates/test_datetime_property/required_not_null.py create mode 100644 tests/test_templates/test_property_templates/test_datetime_property/test_datetime_property.py diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py index 96e86cb53..7988fd715 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py @@ -50,7 +50,6 @@ def _get_kwargs( params["list_prop"] = json_list_prop json_union_prop: Union[float, str] - json_union_prop = union_prop params["union_prop"] = json_union_prop @@ -58,7 +57,6 @@ def _get_kwargs( json_union_prop_with_ref: Union[Unset, float, str] if isinstance(union_prop_with_ref, Unset): json_union_prop_with_ref = UNSET - elif isinstance(union_prop_with_ref, AnEnum): json_union_prop_with_ref = UNSET if not isinstance(union_prop_with_ref, Unset): @@ -73,11 +71,9 @@ def _get_kwargs( 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} 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 341d4c3d0..0660ad467 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 @@ -18,14 +18,11 @@ def _get_kwargs( ) -> Dict[str, Any]: params: Dict[str, Any] = {} json_not_null_required = not_null_required.isoformat() - params["not_null_required"] = json_not_null_required json_null_required: Union[None, str] - if isinstance(null_required, datetime.datetime): json_null_required = null_required.isoformat() - else: json_null_required = null_required @@ -34,7 +31,6 @@ def _get_kwargs( 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): 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 c06b22eed..9d2abef3c 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 @@ -31,7 +31,6 @@ def _get_kwargs( 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: 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: @@ -46,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: 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 84652bbea..e43b7176e 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 @@ -78,55 +78,42 @@ def to_dict(self) -> Dict[str, Any]: an_enum_value = self.an_enum_value.value 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]] - 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 @@ -155,7 +142,6 @@ def to_dict(self) -> Dict[str, Any]: not_required_nullable: Union[None, Unset, str] if isinstance(self.not_required_nullable, Unset): not_required_nullable = UNSET - else: not_required_nullable = self.not_required_nullable @@ -163,12 +149,10 @@ def to_dict(self) -> Dict[str, Any]: 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): @@ -177,33 +161,27 @@ 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 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 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[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 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 5b3025fb2..08e2e0b20 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 @@ -100,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 @@ -136,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 @@ -159,7 +157,6 @@ def to_dict(self) -> Dict[str, Any]: 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 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/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 87228aa40..10ae522c5 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 @@ -66,12 +66,9 @@ def to_dict(self) -> Dict[str, Any]: 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 @@ -96,7 +93,6 @@ def to_dict(self) -> Dict[str, Any]: some_optional_object: Union[Unset, Dict[str, Any]] = UNSET if not isinstance(self.some_optional_object, Unset): some_optional_object = self.some_optional_object.to_dict() - some_enum: Union[Unset, str] = UNSET if not isinstance(self.some_enum, Unset): some_enum = self.some_enum.value @@ -104,7 +100,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, @@ -135,12 +130,9 @@ def to_multipart(self) -> Dict[str, Any]: some_file = self.some_file.to_tuple() 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 @@ -174,7 +166,6 @@ def to_multipart(self) -> Dict[str, Any]: some_optional_object: Union[Unset, Tuple[None, bytes, str]] = UNSET if not isinstance(self.some_optional_object, Unset): some_optional_object = (None, json.dumps(self.some_optional_object.to_dict()).encode(), "application/json") - 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") @@ -182,7 +173,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, 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_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_any_json_properties.py b/end_to_end_tests/golden-record/my_test_api_client/models/model_with_any_json_properties.py index d9c4561a4..a34c1bd7f 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,7 +29,6 @@ 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 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_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/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 index 00b9dbabc..5852f3a1e 100644 --- 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 @@ -25,7 +25,6 @@ class PostConstPathJsonBody: 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 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/templates/property_templates/datetime_property.py.jinja b/openapi_python_client/templates/property_templates/datetime_property.py.jinja index ea6d100d8..5e2734c85 100644 --- a/openapi_python_client/templates/property_templates/datetime_property.py.jinja +++ b/openapi_python_client/templates/property_templates/datetime_property.py.jinja @@ -17,7 +17,7 @@ isoparse({{ source }}) {% endif %} {% if property.required %} {{ destination }} = {{ transformed }} -{% 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 %} 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 3e4890504..bdfd3cca5 100644 --- a/openapi_python_client/templates/property_templates/model_property.py.jinja +++ b/openapi_python_client/templates/property_templates/model_property.py.jinja @@ -20,11 +20,11 @@ {% endif %} {% if property.required %} {{ destination }} = {{ transformed }} -{% else %} +{%- else %} {{ destination }}{% if declare_type %}: {{ type_string }}{% endif %} = UNSET if not isinstance({{ source }}, Unset): {{ destination }} = {{ transformed }} -{% endif %} +{%- endif %} {% endmacro %} {% macro transform_multipart(property, source, destination) %} 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 9944383be..269423783 100644 --- a/openapi_python_client/templates/property_templates/union_property.py.jinja +++ b/openapi_python_client/templates/property_templates/union_property.py.jinja @@ -48,7 +48,6 @@ if isinstance({{ source }}, Unset): {{ destination }} = UNSET {% set ns.has_if = true %} {% endif %} - {% for inner_property in property.inner_properties %} {% import "property_templates/" + inner_property.template as inner_template %} {% if not inner_template.transform %} 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 e71bbbf96..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 @@ -4,7 +4,6 @@ from dateutil.parser import isoparse some_source = date(2020, 10, 12) some_destination = some_source.isoformat() - a_prop = isoparse(some_destination).date() 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() From 5064faf04afbd4dcb7f3663b979fe957fa8c430b Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sun, 31 Dec 2023 15:36:33 -0700 Subject: [PATCH 28/30] More whitespace improvements --- .../api/location/get_location_query_optionality.py | 2 -- .../my_test_api_client/models/a_form_data.py | 1 + .../golden-record/my_test_api_client/models/a_model.py | 10 ++++++++++ ...el_with_properties_reference_that_are_not_object.py | 8 ++++++++ .../models/all_of_has_properties_but_no_type.py | 2 ++ .../my_test_api_client/models/all_of_sub_model.py | 2 ++ .../models/another_all_of_sub_model.py | 1 + .../models/body_upload_file_tests_upload_post.py | 8 ++++++++ .../body_upload_file_tests_upload_post_some_object.py | 1 + .../my_test_api_client/models/model_from_all_of.py | 1 + .../models/post_form_data_inline_data.py | 1 + ...t_naming_property_conflict_with_import_json_body.py | 1 + ...aming_property_conflict_with_import_response_200.py | 1 + .../my_test_api_client/models/validation_error.py | 1 + .../models/post_const_path_json_body.py | 1 + .../models/post_body_multipart_multipart_data.py | 2 ++ .../models/post_body_multipart_response_200.py | 4 ++++ .../models/post_parameters_header_response_200.py | 3 +++ integration-tests/integration_tests/models/problem.py | 1 + .../templates/endpoint_macros.py.jinja | 2 +- openapi_python_client/templates/model.py.jinja | 1 + .../property_templates/date_property.py.jinja | 2 +- .../property_templates/datetime_property.py.jinja | 2 +- 23 files changed, 53 insertions(+), 5 deletions(-) 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 0660ad467..822018357 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 @@ -35,7 +35,6 @@ def _get_kwargs( 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 @@ -44,7 +43,6 @@ def _get_kwargs( 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() - 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} 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 e43b7176e..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 @@ -76,7 +76,9 @@ def to_dict(self) -> Dict[str, Any]: from ..models.model_with_union_property import ModelWithUnionProperty an_enum_value = self.an_enum_value.value + 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() @@ -84,6 +86,7 @@ def to_dict(self) -> Dict[str, Any]: 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() @@ -94,6 +97,7 @@ def to_dict(self) -> Dict[str, Any]: required_nullable = self.required_nullable required_not_nullable = self.required_not_nullable + one_of_models: Union[Any, Dict[str, Any]] if isinstance(self.one_of_models, FreeFormModel): one_of_models = self.one_of_models.to_dict() @@ -111,6 +115,7 @@ def to_dict(self) -> Dict[str, Any]: 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() @@ -118,6 +123,7 @@ def to_dict(self) -> Dict[str, Any]: 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 @@ -138,7 +144,9 @@ def to_dict(self) -> Dict[str, Any]: 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 + not_required_nullable: Union[None, Unset, str] if isinstance(self.not_required_nullable, Unset): not_required_nullable = UNSET @@ -146,6 +154,7 @@ def to_dict(self) -> Dict[str, Any]: 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 @@ -175,6 +184,7 @@ def to_dict(self) -> Dict[str, Any]: 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[Dict[str, Any], None, Unset] if isinstance(self.not_required_nullable_model, Unset): not_required_nullable_model = UNSET 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 08e2e0b20..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 @@ -154,13 +154,21 @@ def to_dict(self) -> Dict[str, Any]: bytestream_properties = self.bytestream_properties 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/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 10ae522c5..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 @@ -66,6 +66,7 @@ def to_dict(self) -> Dict[str, Any]: 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() @@ -77,6 +78,7 @@ def to_dict(self) -> Dict[str, Any]: 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() @@ -86,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 @@ -93,6 +96,7 @@ def to_dict(self) -> Dict[str, Any]: some_optional_object: Union[Unset, Dict[str, Any]] = UNSET if not isinstance(self.some_optional_object, Unset): some_optional_object = self.some_optional_object.to_dict() + some_enum: Union[Unset, str] = UNSET if not isinstance(self.some_enum, Unset): some_enum = self.some_enum.value @@ -130,6 +134,7 @@ def to_multipart(self) -> Dict[str, Any]: some_file = self.some_file.to_tuple() 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") @@ -145,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() @@ -158,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 @@ -166,6 +173,7 @@ def to_multipart(self) -> Dict[str, Any]: some_optional_object: Union[Unset, Tuple[None, bytes, str]] = UNSET if not isinstance(self.some_optional_object, Unset): some_optional_object = (None, json.dumps(self.some_optional_object.to_dict()).encode(), "application/json") + 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") 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/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/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/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/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 index 5852f3a1e..e7cfcf3a8 100644 --- 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 @@ -24,6 +24,7 @@ class PostConstPathJsonBody: def to_dict(self) -> Dict[str, Any]: required = self.required + nullable: Union[Literal["this or null goes in the body"], None] nullable = self.nullable 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/openapi_python_client/templates/endpoint_macros.py.jinja b/openapi_python_client/templates/endpoint_macros.py.jinja index 000f2c368..4953f69a9 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 %} @@ -53,7 +54,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/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 d351f8b1e..c1f8b668f 100644 --- a/openapi_python_client/templates/property_templates/date_property.py.jinja +++ b/openapi_python_client/templates/property_templates/date_property.py.jinja @@ -27,5 +27,5 @@ isoparse({{ source }}).date() {% endif %} if not isinstance({{ source }}, Unset): {{ destination }} = {{ transformed }} -{% 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 5e2734c85..18673087e 100644 --- a/openapi_python_client/templates/property_templates/datetime_property.py.jinja +++ b/openapi_python_client/templates/property_templates/datetime_property.py.jinja @@ -27,5 +27,5 @@ isoparse({{ source }}) {% endif %} if not isinstance({{ source }}, Unset): {{ destination }} = {{ transformed }} -{% endif %} +{%- endif %} {% endmacro %} From 2a48ee15d8ec21a4e2ee801b9c1c1885651abab8 Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sun, 31 Dec 2023 15:39:19 -0700 Subject: [PATCH 29/30] More whitespace improvements --- .../api/defaults/defaults_tests_defaults_post.py | 2 -- .../api/location/get_location_query_optionality.py | 2 -- .../my_test_api_client/api/tests/get_user_list.py | 1 - .../models/model_with_any_json_properties.py | 1 - .../templates/property_templates/union_property.py.jinja | 5 ++--- 5 files changed, 2 insertions(+), 9 deletions(-) diff --git a/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py index 7988fd715..2bc78960d 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py @@ -51,7 +51,6 @@ def _get_kwargs( json_union_prop: Union[float, str] json_union_prop = union_prop - params["union_prop"] = json_union_prop json_union_prop_with_ref: Union[Unset, float, str] @@ -64,7 +63,6 @@ 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 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 822018357..2e8cef5ca 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 @@ -25,7 +25,6 @@ def _get_kwargs( json_null_required = null_required.isoformat() else: json_null_required = null_required - params["null_required"] = json_null_required json_null_not_required: Union[None, Unset, str] @@ -37,7 +36,6 @@ def _get_kwargs( 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, str] = UNSET 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 9d2abef3c..2006eba60 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 @@ -35,7 +35,6 @@ def _get_kwargs( 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 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 a34c1bd7f..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 @@ -34,7 +34,6 @@ def to_dict(self) -> Dict[str, Any]: else: field_dict[prop_name] = prop - field_dict.update({}) return field_dict 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 269423783..df77be05b 100644 --- a/openapi_python_client/templates/property_templates/union_property.py.jinja +++ b/openapi_python_client/templates/property_templates/union_property.py.jinja @@ -69,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 %} From cf7d94e3ea42c0e783166b8a3689f726f791f33f Mon Sep 17 00:00:00 2001 From: Dylan Anthony Date: Sun, 31 Dec 2023 15:41:12 -0700 Subject: [PATCH 30/30] More whitespace improvements --- .../my_test_api_client/api/default/get_common_parameters.py | 1 + .../my_test_api_client/api/default/post_common_parameters.py | 1 + .../my_test_api_client/api/default/reserved_parameters.py | 1 + .../api/defaults/defaults_tests_defaults_post.py | 1 + .../api/location/get_location_query_optionality.py | 1 + .../parameter_references/get_parameter_references_path_param.py | 1 + .../api/parameters/delete_common_parameters_overriding_param.py | 1 + .../api/parameters/get_common_parameters_overriding_param.py | 1 + .../api/parameters/get_same_name_multiple_locations_param.py | 1 + .../golden-record/my_test_api_client/api/tests/get_user_list.py | 1 + .../my_test_api_client/api/tests/int_enum_tests_int_enum_post.py | 1 + .../golden-record/my_test_api_client/api/true_/false_.py | 1 + .../test_3_1_features_client/api/const/post_const_path.py | 1 + openapi_python_client/templates/endpoint_macros.py.jinja | 1 + 14 files changed, 14 insertions(+) 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 840bee628..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 @@ -13,6 +13,7 @@ def _get_kwargs( 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} 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 ad59688e6..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 @@ -13,6 +13,7 @@ def _get_kwargs( 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} 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/defaults_tests_defaults_post.py b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py index 2bc78960d..529190562 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py +++ b/end_to_end_tests/golden-record/my_test_api_client/api/defaults/defaults_tests_defaults_post.py @@ -29,6 +29,7 @@ def _get_kwargs( required_model_prop: "ModelWithUnionProperty", ) -> Dict[str, Any]: params: Dict[str, Any] = {} + params["string_prop"] = string_prop params["string with num"] = string_with_num 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 2e8cef5ca..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 @@ -17,6 +17,7 @@ def _get_kwargs( not_null_not_required: Union[Unset, datetime.datetime] = UNSET, ) -> Dict[str, Any]: params: Dict[str, Any] = {} + json_not_null_required = not_null_required.isoformat() params["not_null_required"] = json_not_null_required 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 f3dcce94c..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 @@ -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 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 0c2321a6b..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 @@ -14,6 +14,7 @@ def _get_kwargs( 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} 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 a99f4f9c5..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 @@ -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} 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 2006eba60..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 @@ -21,6 +21,7 @@ def _get_kwargs( 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 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 d74b487ad..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,6 +15,7 @@ def _get_kwargs( int_enum: AnIntEnum, ) -> Dict[str, Any]: params: Dict[str, Any] = {} + json_int_enum = int_enum.value params["int_enum"] = json_int_enum 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/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 index 7e39c3683..306968daf 100644 --- 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 @@ -17,6 +17,7 @@ def _get_kwargs( 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 diff --git a/openapi_python_client/templates/endpoint_macros.py.jinja b/openapi_python_client/templates/endpoint_macros.py.jinja index 4953f69a9..f5904a509 100644 --- a/openapi_python_client/templates/endpoint_macros.py.jinja +++ b/openapi_python_client/templates/endpoint_macros.py.jinja @@ -41,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 %}